• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ecmascript/module/js_module_namespace.h"
17 
18 #include "ecmascript/global_env.h"
19 #include "ecmascript/object_factory-inl.h"
20 #include "ecmascript/module/module_manager_helper.h"
21 #include "ecmascript/module/module_path_helper.h"
22 #include "ecmascript/module/js_module_deregister.h"
23 #include "ecmascript/module/js_shared_module_manager.h"
24 #include "ecmascript/shared_objects/js_shared_array.h"
25 
26 namespace panda::ecmascript {
CreateSortedExports(JSThread * thread,const JSHandle<TaggedArray> & exports)27 JSHandle<JSTaggedValue> ModuleNamespace::CreateSortedExports(JSThread *thread, const JSHandle<TaggedArray> &exports)
28 {
29     auto globalConst = thread->GlobalConstants();
30     // 7. Let sortedExports be a new List containing the same values as the list exports where the values
31     // are ordered as if an Array of the same values had been sorted using
32     // Array.prototype.sort using undefined as comparefn.
33     JSHandle<JSArray> exportsArray = JSArray::CreateArrayFromList(thread, exports);
34     JSHandle<JSTaggedValue> sortedExports = JSHandle<JSTaggedValue>::Cast(exportsArray);
35     JSHandle<JSTaggedValue> fn = globalConst->GetHandledUndefined();
36     JSArray::Sort(thread, sortedExports, fn);
37     return sortedExports;
38 }
39 
ModuleNamespaceCreate(JSThread * thread,const JSHandle<JSTaggedValue> & module,const JSHandle<TaggedArray> & exports)40 JSHandle<ModuleNamespace> ModuleNamespace::ModuleNamespaceCreate(JSThread *thread,
41                                                                  const JSHandle<JSTaggedValue> &module,
42                                                                  const JSHandle<TaggedArray> &exports)
43 {
44     auto globalConst = thread->GlobalConstants();
45     // 1. Assert: module is a Module Record.
46     ASSERT(module->IsModuleRecord());
47     if (SourceTextModule::IsSharedModule(JSHandle<SourceTextModule>::Cast(module))) {
48         return SharedModuleManager::GetInstance()->SModuleNamespaceCreate(thread, module, exports);
49     }
50 
51     // 2. Assert: module.[[Namespace]] is undefined.
52     // 3. Assert: exports is a List of String values.
53     // 4. Let M be a newly created object.
54     // 5. Set M's essential internal methods to the definitions specified in 9.4.6.
55     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
56     JSHandle<ModuleNamespace> mNp = factory->NewModuleNamespace();
57     // 6. Set M.[[Module]] to module.
58     mNp->SetModule(thread, module);
59 
60     JSHandle<JSTaggedValue> sortedExports = CreateSortedExports(thread, exports);
61     // 8. Set M.[[Exports]] to sortedExports.
62     mNp->SetExports(thread, sortedExports);
63     // 9. Create own properties of M corresponding to the definitions in 26.3.
64 
65     JSHandle<JSTaggedValue> toStringTag = thread->GetEcmaVM()->GetGlobalEnv()->GetToStringTagSymbol();
66     JSHandle<JSTaggedValue> moduleString = globalConst->GetHandledModuleString();
67     PropertyDescriptor des(thread, moduleString, false, false, false);
68     JSHandle<JSObject> mNpObj = JSHandle<JSObject>::Cast(mNp);
69     JSObject::DefineOwnProperty(thread, mNpObj, toStringTag, des);
70     // 10. Set module.[[Namespace]] to M.
71     SetModuleDeregisterProcession(thread, mNp, ModuleDeregister::FreeModuleRecord);
72     JSHandle<ModuleRecord> moduleRecord = JSHandle<ModuleRecord>::Cast(module);
73     SourceTextModule::Cast(moduleRecord.GetTaggedValue().GetTaggedObject())->SetNamespace(thread,
74                                                                                           mNp.GetTaggedValue());
75     mNp->GetJSHClass()->SetExtensible(false);
76     return mNp;
77 }
78 
GetProperty(JSThread * thread,const JSHandle<JSTaggedValue> & obj,const JSHandle<JSTaggedValue> & key)79 OperationResult ModuleNamespace::GetProperty(JSThread *thread, const JSHandle<JSTaggedValue> &obj,
80                                              const JSHandle<JSTaggedValue> &key)
81 {
82     // 1. Assert: IsPropertyKey(P) is true.
83     ASSERT_PRINT(JSTaggedValue::IsPropertyKey(key), "Key is not a property key");
84     // 2. If Type(P) is Symbol, then
85     //   a. Return ? OrdinaryGet(O, P, Receiver).
86     if (key->IsSymbol()) {
87         return JSObject::GetProperty(thread, obj, key);
88     }
89     JSHandle<ModuleNamespace> moduleNamespace = JSHandle<ModuleNamespace>::Cast(obj);
90     // 3. Let exports be O.[[Exports]].
91     JSHandle<JSTaggedValue> exports(thread, moduleNamespace->GetExports());
92     // 4. If P is not an element of exports, return undefined.
93     if (exports->IsUndefined()) {
94         return OperationResult(thread, thread->GlobalConstants()->GetUndefined(), PropertyMetaData(false));
95     }
96     if (exports->IsJSArray()) {
97         if (!JSArray::IncludeInSortedValue(thread, exports, key))
98         return OperationResult(thread, thread->GlobalConstants()->GetUndefined(), PropertyMetaData(false));
99     } else if (exports->IsJSSharedArray() && !JSSharedArray::IncludeInSortedValue(thread, exports, key)) {
100         return OperationResult(thread, thread->GlobalConstants()->GetUndefined(), PropertyMetaData(false));
101     }
102     // 5. Let m be O.[[Module]].
103     JSHandle<SourceTextModule> mm(thread, moduleNamespace->GetModule());
104     // 6. Let binding be ! m.ResolveExport(P, « »).
105     CVector<std::pair<JSHandle<SourceTextModule>, JSHandle<JSTaggedValue>>> resolveSet;
106     JSHandle<JSTaggedValue> binding = SourceTextModule::ResolveExport(thread, mm, key, resolveSet);
107     // 7. Assert: binding is a ResolvedBinding Record.
108     // If resolution is null or "ambiguous", throw a SyntaxError exception.
109     if (binding->IsNull() || binding->IsString()) {
110         CString requestMod = ModulePathHelper::ReformatPath(mm->GetEcmaModuleFilenameString());
111         LOG_FULL(FATAL) << "Module: '" << requestMod << SourceTextModule::GetResolveErrorReason(binding) <<
112             ConvertToString(key.GetTaggedValue()) << ".";
113     }
114     JSTaggedValue result;
115     // 8. Let targetModule be binding.[[Module]].
116     JSType type = binding->GetTaggedObject()->GetClass()->GetObjectType();
117     switch (type) {
118         case JSType::RESOLVEDBINDING_RECORD: {
119             JSHandle<ResolvedBinding> resolvedBind = JSHandle<ResolvedBinding>::Cast(binding);
120             JSTaggedValue targetModule = resolvedBind->GetModule();
121             // 9. Assert: targetModule is not undefined.
122             ASSERT(!targetModule.IsUndefined());
123             JSHandle<SourceTextModule> module(thread, targetModule);
124             // DFX: make sure lazy module is already evaluated.
125             if (module->GetStatus() == ModuleStatus::INSTANTIATED) {
126                 LOG_FULL(ERROR) << "Module is not evaluated, module is :" << module->GetEcmaModuleRecordNameString();
127             }
128             ModuleTypes moduleType = module->GetTypes();
129             if (UNLIKELY(SourceTextModule::IsNativeModule(moduleType))) {
130                 result = ModuleManagerHelper::GetModuleValue(thread, module, resolvedBind->GetBindingName());
131                 RETURN_VALUE_IF_ABRUPT_COMPLETION(
132                     thread, OperationResult(thread, JSTaggedValue::Exception(), PropertyMetaData(false)));
133             } else {
134                 result = module->GetModuleValue(thread, resolvedBind->GetBindingName(), true);
135             }
136             break;
137         }
138         case JSType::RESOLVEDINDEXBINDING_RECORD: {
139             JSHandle<ResolvedIndexBinding> resolvedBind = JSHandle<ResolvedIndexBinding>::Cast(binding);
140             JSTaggedValue targetModule = resolvedBind->GetModule();
141             // 9. Assert: targetModule is not undefined.
142             ASSERT(!targetModule.IsUndefined());
143             JSHandle<SourceTextModule> module(thread, targetModule);
144             // DFX: make sure lazy module is already evaluated.
145             if (module->GetStatus() == ModuleStatus::INSTANTIATED) {
146                 LOG_FULL(ERROR) << "Module is not evaluated, module is :" << module->GetEcmaModuleRecordNameString();
147             }
148             ModuleTypes moduleType = module->GetTypes();
149             if (UNLIKELY(SourceTextModule::IsNativeModule(moduleType))) {
150                 result = ModuleManagerHelper::GetNativeOrCjsModuleValue(
151                     thread, targetModule, resolvedBind->GetIndex());
152                 RETURN_VALUE_IF_ABRUPT_COMPLETION(
153                     thread, OperationResult(thread, JSTaggedValue::Exception(), PropertyMetaData(false)));
154             } else {
155                 result = module->GetModuleValue(thread, resolvedBind->GetIndex(), true);
156             }
157             break;
158         }
159         case JSType::RESOLVEDRECORDINDEXBINDING_RECORD:
160             LOG_FULL(INFO) << "RESOLVEDRECORDINDEXBINDING_RECORD";
161             break;
162         case JSType::RESOLVEDRECORDBINDING_RECORD:
163             LOG_FULL(INFO) << "RESOLVEDRECORDINDEXBINDING_RECORD";
164             break;
165         default:
166             LOG_FULL(FATAL) << "UNREACHABLE";
167     }
168     return OperationResult(thread, result, PropertyMetaData(true));
169 }
170 
OwnPropertyKeys(JSThread * thread,const JSHandle<JSTaggedValue> & obj)171 JSHandle<TaggedArray> ModuleNamespace::OwnPropertyKeys(JSThread *thread, const JSHandle<JSTaggedValue> &obj)
172 {
173     ASSERT(obj->IsModuleNamespace());
174     // 1. Let exports be a copy of O.[[Exports]].
175     JSHandle<ModuleNamespace> moduleNamespace = JSHandle<ModuleNamespace>::Cast(obj);
176     JSHandle<JSTaggedValue> exports(thread, moduleNamespace->GetExports());
177     JSHandle<TaggedArray> exportsArray = JSArray::ToTaggedArray(thread, exports);
178     if (!moduleNamespace->ValidateKeysAvailable(thread, exportsArray)) {
179         return exportsArray;
180     }
181 
182     // 2. Let symbolKeys be ! OrdinaryOwnPropertyKeys(O).
183     JSHandle<TaggedArray> symbolKeys = JSObject::GetOwnPropertyKeys(thread, JSHandle<JSObject>(obj));
184     // 3. Append all the entries of symbolKeys to the end of exports.
185     JSHandle<TaggedArray> result = TaggedArray::Append(thread, exportsArray, symbolKeys);
186     // 4. Return exports.
187     return result;
188 }
189 
OwnEnumPropertyKeys(JSThread * thread,const JSHandle<JSTaggedValue> & obj)190 JSHandle<TaggedArray> ModuleNamespace::OwnEnumPropertyKeys(JSThread *thread, const JSHandle<JSTaggedValue> &obj)
191 {
192     ASSERT(obj->IsModuleNamespace());
193     // 1. Let exports be a copy of O.[[Exports]].
194     JSHandle<ModuleNamespace> moduleNamespace = JSHandle<ModuleNamespace>::Cast(obj);
195     JSHandle<JSTaggedValue> exports(thread, moduleNamespace->GetExports());
196     JSHandle<TaggedArray> exportsArray = JSArray::ToTaggedArray(thread, exports);
197     if (!moduleNamespace->ValidateKeysAvailable(thread, exportsArray)) {
198         return exportsArray;
199     }
200 
201     // 2. Let symbolKeys be ! OrdinaryOwnPropertyKeys(O).
202     JSHandle<TaggedArray> symbolKeys = JSObject::GetOwnEnumPropertyKeys(thread, JSHandle<JSObject>(obj));
203     // 3. Append all the entries of symbolKeys to the end of exports.
204     JSHandle<TaggedArray> result = TaggedArray::Append(thread, exportsArray, symbolKeys);
205     // 4. Return exports.
206     return result;
207 }
208 
PreventExtensions()209 bool ModuleNamespace::PreventExtensions()
210 {
211     return true;
212 }
213 
DefineOwnProperty(JSThread * thread,const JSHandle<JSTaggedValue> & obj,const JSHandle<JSTaggedValue> & key,PropertyDescriptor desc)214 bool ModuleNamespace::DefineOwnProperty(JSThread *thread,
215                                         const JSHandle<JSTaggedValue> &obj,
216                                         const JSHandle<JSTaggedValue> &key,
217                                         PropertyDescriptor desc)
218 {
219     ASSERT(obj->IsModuleNamespace());
220     // 1. If Type(P) is Symbol, return ! OrdinaryDefineOwnProperty(O, P, Desc).
221     if (key->IsSymbol()) {
222         bool res = JSObject::OrdinaryDefineOwnProperty(thread, JSHandle<JSObject>(obj), key, desc);
223         return res;
224     }
225 
226     // 2. Let current be ? O.[[GetOwnProperty]](P).
227     PropertyDescriptor current(thread);
228     // 3. If current is undefined, return false.
229     if (!GetOwnProperty(thread, obj, key, current)) {
230         return false;
231     }
232     // 4. If Desc has a [[Configurable]] field and Desc.[[Configurable]] is true, return false.
233     // 5. If Desc has an [[Enumerable]] field and Desc.[[Enumerable]] is false, return false.
234     // 6. If IsAccessorDescriptor(Desc) is true, return false.
235     // 7. If Desc has a [[Writable]] field and Desc.[[Writable]] is false, return false.
236     if (desc.IsAccessorDescriptor()) {
237         return false;
238     }
239     if (desc.HasConfigurable() && desc.IsConfigurable()) {
240         return false;
241     }
242     if (desc.HasEnumerable() && !desc.IsEnumerable()) {
243         return false;
244     }
245     if (desc.HasWritable() && !desc.IsWritable()) {
246         return false;
247     }
248 
249     // 8. If Desc has a [[Value]] field, return SameValue(Desc.[[Value]], current.[[Value]]).
250     if (desc.HasValue()) {
251         JSHandle<JSTaggedValue> descValue = desc.GetValue();
252         JSHandle<JSTaggedValue> currentValue = current.GetValue();
253         return JSTaggedValue::SameValue(descValue, currentValue);
254     }
255 
256     // 9. Return true.
257     return true;
258 }
259 
HasProperty(JSThread * thread,const JSHandle<JSTaggedValue> & obj,const JSHandle<JSTaggedValue> & key)260 bool ModuleNamespace::HasProperty(JSThread *thread, const JSHandle<JSTaggedValue> &obj,
261                                   const JSHandle<JSTaggedValue> &key)
262 {
263     ASSERT(obj->IsModuleNamespace());
264     // 1. If Type(P) is Symbol, return OrdinaryHasProperty(O, P).
265     if (key->IsSymbol()) {
266         return JSObject::HasProperty(thread, JSHandle<JSObject>(obj), key);
267     }
268     // 2. Let exports be O.[[Exports]].
269     JSHandle<ModuleNamespace> moduleNamespace = JSHandle<ModuleNamespace>::Cast(obj);
270     JSHandle<JSTaggedValue> exports(thread, moduleNamespace->GetExports());
271     // 3. If P is an element of exports, return true.
272     if (exports->IsUndefined()) {
273         return false;
274     }
275     if (JSArray::IncludeInSortedValue(thread, exports, key)) {
276         return true;
277     }
278     // 4. Return false.
279     return false;
280 }
281 
SetPrototype(const JSHandle<JSTaggedValue> & obj,const JSHandle<JSTaggedValue> & proto)282 bool ModuleNamespace::SetPrototype([[maybe_unused]] const JSHandle<JSTaggedValue> &obj,
283                                    const JSHandle<JSTaggedValue> &proto)
284 {
285     ASSERT(obj->IsModuleNamespace());
286     // 1. Assert: Either Type(V) is Object or Type(V) is Null.
287     ASSERT(proto->IsECMAObject() || proto->IsNull());
288     return proto->IsNull();
289 }
290 
GetOwnProperty(JSThread * thread,const JSHandle<JSTaggedValue> & obj,const JSHandle<JSTaggedValue> & key,PropertyDescriptor & desc)291 bool ModuleNamespace::GetOwnProperty(JSThread *thread, const JSHandle<JSTaggedValue> &obj,
292                                      const JSHandle<JSTaggedValue> &key, PropertyDescriptor &desc)
293 {
294     // 1. If Type(P) is Symbol, return OrdinaryGetOwnProperty(O, P).
295     if (key->IsSymbol()) {
296         return JSObject::GetOwnProperty(thread, JSHandle<JSObject>(obj), key, desc);
297     }
298     // 2. Let exports be O.[[Exports]].
299     JSHandle<ModuleNamespace> moduleNamespace = JSHandle<ModuleNamespace>::Cast(obj);
300     JSHandle<JSTaggedValue> exports(thread, moduleNamespace->GetExports());
301     // 3. If P is not an element of exports, return undefined.
302     if (exports->IsUndefined()) {
303         return false;
304     }
305     if (!JSArray::IncludeInSortedValue(thread, exports, key)) {
306         return false;
307     }
308     // 4. Let value be ? O.[[Get]](P, O).
309     JSHandle<JSTaggedValue> value = ModuleNamespace::GetProperty(thread, obj, key).GetValue();
310     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, false);
311     // 5. Return PropertyDescriptor {
312     //    [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }.
313     desc.SetValue(value);
314     desc.SetEnumerable(true);
315     desc.SetWritable(true);
316     desc.SetConfigurable(false);
317     return true;
318 }
319 
SetProperty(JSThread * thread,bool mayThrow)320 bool ModuleNamespace::SetProperty(JSThread *thread, bool mayThrow)
321 {
322     if (mayThrow) {
323         THROW_TYPE_ERROR_AND_RETURN(thread, "Cannot assign to read only property of Object Module", false);
324     }
325     return false;
326 }
327 
DeleteProperty(JSThread * thread,const JSHandle<JSTaggedValue> & obj,const JSHandle<JSTaggedValue> & key)328 bool ModuleNamespace::DeleteProperty(JSThread *thread, const JSHandle<JSTaggedValue> &obj,
329                                      const JSHandle<JSTaggedValue> &key)
330 {
331     ASSERT(obj->IsModuleNamespace());
332     // 1. Assert: IsPropertyKey(P) is true.
333     ASSERT_PRINT(JSTaggedValue::IsPropertyKey(key), "Key is not a property key");
334     // 2. If Type(P) is Symbol, then
335     //    Return ? OrdinaryDelete(O, P).
336     if (key->IsSymbol()) {
337         return JSObject::DeleteProperty(thread, JSHandle<JSObject>(obj), key);
338     }
339     // 3. Let exports be O.[[Exports]].
340     JSHandle<ModuleNamespace> moduleNamespace = JSHandle<ModuleNamespace>::Cast(obj);
341     JSHandle<JSTaggedValue> exports(thread, moduleNamespace->GetExports());
342     // 4. If P is an element of exports, return false.
343     if (exports->IsUndefined()) {
344         return true;
345     }
346     if (JSArray::IncludeInSortedValue(thread, exports, key)) {
347         return false;
348     }
349     return true;
350 }
351 
ValidateKeysAvailable(JSThread * thread,const JSHandle<TaggedArray> & exports)352 bool ModuleNamespace::ValidateKeysAvailable(JSThread *thread, const JSHandle<TaggedArray> &exports)
353 {
354     JSHandle<ModuleNamespace> moduleNamespace(thread, this);
355     JSHandle<SourceTextModule> mm(thread, moduleNamespace->GetModule());
356     uint32_t exportsLength = exports->GetLength();
357     for (uint32_t idx = 0; idx < exportsLength; idx++) {
358         JSHandle<JSTaggedValue> key(thread, exports->Get(idx));
359         CVector<std::pair<JSHandle<SourceTextModule>, JSHandle<JSTaggedValue>>> resolveSet;
360         JSHandle<JSTaggedValue> binding = SourceTextModule::ResolveExport(thread, mm, key, resolveSet);
361         // Adapter new module
362         ASSERT(binding->IsResolvedBinding() || binding->IsResolvedIndexBinding());
363         JSTaggedValue targetModule = JSTaggedValue::Undefined();
364         if (binding->IsResolvedBinding()) {
365             targetModule = JSHandle<ResolvedBinding>::Cast(binding)->GetModule();
366         } else if (binding->IsResolvedIndexBinding()) {
367             targetModule = JSHandle<ResolvedIndexBinding>::Cast(binding)->GetModule();
368         }
369         ASSERT(!targetModule.IsUndefined());
370         JSTaggedValue dictionary = SourceTextModule::Cast(targetModule.GetTaggedObject())->GetNameDictionary();
371         if (dictionary.IsUndefined()) {
372             THROW_REFERENCE_ERROR_AND_RETURN(thread, "module environment is undefined", false);
373         }
374     }
375     return true;
376 }
377 
SetModuleDeregisterProcession(JSThread * thread,const JSHandle<ModuleNamespace> & nameSpace,const NativePointerCallback & callback)378 void ModuleNamespace::SetModuleDeregisterProcession(JSThread *thread, const JSHandle<ModuleNamespace> &nameSpace,
379     const NativePointerCallback &callback)
380 {
381     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
382 
383     JSHandle<SourceTextModule> module(thread, nameSpace->GetModule());
384     CString moduleStr = SourceTextModule::GetModuleName(module.GetTaggedValue());
385     int srcLength = strlen(moduleStr.c_str()) + 1;
386     auto moduleNameData = thread->GetEcmaVM()->GetNativeAreaAllocator()->AllocateBuffer(srcLength);
387     if (memcpy_s(moduleNameData, srcLength, moduleStr.c_str(), srcLength) != EOK) { // LCOV_EXCL_BR_LINE
388         LOG_ECMA(FATAL) << "Failed to copy module name's data.";
389         UNREACHABLE();
390     }
391     char *tmpData = reinterpret_cast<char *>(moduleNameData);
392     tmpData[srcLength - 1] = '\0';
393     ASSERT(nameSpace->GetDeregisterProcession().IsUndefined());
394     JSHandle<JSNativePointer> registerPointer = factory->NewJSNativePointer(
395         reinterpret_cast<void *>(moduleNameData), callback, reinterpret_cast<void *>(thread), false, srcLength);
396     nameSpace->SetDeregisterProcession(thread, registerPointer.GetTaggedValue());
397 }
398 }  // namespace panda::ecmascript
399