• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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/dfx/native_module_failure_info.h"
17 #include "ecmascript/builtins/builtins.h"
18 #include "ecmascript/builtins/builtins_errors.h"
19 #include "ecmascript/ecma_string_table.h"
20 #include "ecmascript/ecma_string-inl.h"
21 #include "ecmascript/ic/ic_handler.h"
22 #include "ecmascript/ic/profile_type_info.h"
23 #include "ecmascript/ic/proto_change_details.h"
24 #include "ecmascript/jobs/pending_job.h"
25 #include "ecmascript/js_api/js_api_arraylist.h"
26 #include "ecmascript/js_api/js_api_arraylist_iterator.h"
27 #include "ecmascript/js_api/js_api_bitvector.h"
28 #include "ecmascript/js_api/js_api_bitvector_iterator.h"
29 #include "ecmascript/js_api/js_api_deque.h"
30 #include "ecmascript/js_api/js_api_deque_iterator.h"
31 #include "ecmascript/js_api/js_api_hashmap_iterator.h"
32 #include "ecmascript/js_api/js_api_hashset.h"
33 #include "ecmascript/js_api/js_api_hashset_iterator.h"
34 #include "ecmascript/js_api/js_api_lightweightmap.h"
35 #include "ecmascript/js_api/js_api_lightweightmap_iterator.h"
36 #include "ecmascript/js_api/js_api_lightweightset.h"
37 #include "ecmascript/js_api/js_api_lightweightset_iterator.h"
38 #include "ecmascript/js_api/js_api_linked_list.h"
39 #include "ecmascript/js_api/js_api_linked_list_iterator.h"
40 #include "ecmascript/js_api/js_api_list.h"
41 #include "ecmascript/js_api/js_api_list_iterator.h"
42 #include "ecmascript/js_api/js_api_plain_array.h"
43 #include "ecmascript/js_api/js_api_plain_array_iterator.h"
44 #include "ecmascript/js_api/js_api_queue.h"
45 #include "ecmascript/js_api/js_api_queue_iterator.h"
46 #include "ecmascript/js_api/js_api_stack_iterator.h"
47 #include "ecmascript/js_api/js_api_tree_map.h"
48 #include "ecmascript/js_api/js_api_tree_map_iterator.h"
49 #include "ecmascript/js_api/js_api_tree_set.h"
50 #include "ecmascript/js_api/js_api_tree_set_iterator.h"
51 #include "ecmascript/js_api/js_api_vector.h"
52 #include "ecmascript/js_api/js_api_vector_iterator.h"
53 #include "ecmascript/js_arguments.h"
54 #include "ecmascript/js_array_iterator.h"
55 #include "ecmascript/js_arraybuffer.h"
56 #include "ecmascript/js_async_from_sync_iterator.h"
57 #include "ecmascript/js_async_function.h"
58 #include "ecmascript/js_async_generator_object.h"
59 #include "ecmascript/js_finalization_registry.h"
60 #include "ecmascript/js_for_in_iterator.h"
61 #include "ecmascript/js_map.h"
62 #include "ecmascript/js_map_iterator.h"
63 #include "ecmascript/js_primitive_ref.h"
64 #include "ecmascript/js_promise.h"
65 #include "ecmascript/js_realm.h"
66 #include "ecmascript/js_regexp.h"
67 #include "ecmascript/js_regexp_iterator.h"
68 #include "ecmascript/js_set.h"
69 #include "ecmascript/js_set_iterator.h"
70 #include "ecmascript/js_string_iterator.h"
71 #include "ecmascript/js_weak_container.h"
72 #include "ecmascript/js_weak_ref.h"
73 #include "ecmascript/jspandafile/program_object.h"
74 #include "ecmascript/marker_cell.h"
75 #include "ecmascript/object_factory.h"
76 #include "ecmascript/require/js_cjs_exports.h"
77 #include "ecmascript/require/js_cjs_require.h"
78 #include "ecmascript/shared_mm/shared_mm.h"
79 #include "ecmascript/shared_objects/js_shared_array.h"
80 #include "ecmascript/shared_objects/js_sendable_arraybuffer.h"
81 #include "ecmascript/shared_objects/js_shared_array_iterator.h"
82 #include "ecmascript/shared_objects/js_shared_map.h"
83 #include "ecmascript/shared_objects/js_shared_map_iterator.h"
84 #include "ecmascript/shared_objects/js_shared_set.h"
85 #include "ecmascript/shared_objects/js_shared_set_iterator.h"
86 #include "ecmascript/shared_objects/js_shared_typed_array.h"
87 #include "ecmascript/symbol_table.h"
88 #include "ecmascript/template_map.h"
89 #include "ecmascript/vtable.h"
90 #ifdef ARK_SUPPORT_INTL
91 #include "ecmascript/js_collator.h"
92 #include "ecmascript/js_date_time_format.h"
93 #include "ecmascript/js_displaynames.h"
94 #include "ecmascript/js_list_format.h"
95 #include "ecmascript/js_number_format.h"
96 #include "ecmascript/js_plural_rules.h"
97 #include "ecmascript/js_relative_time_format.h"
98 #include "ecmascript/js_segmenter.h"
99 #include "ecmascript/js_segments.h"
100 #include "ecmascript/js_segment_iterator.h"
101 #endif
102 namespace panda::ecmascript {
103 using Error = builtins::BuiltinsError;
104 using RangeError = builtins::BuiltinsRangeError;
105 using ReferenceError = builtins::BuiltinsReferenceError;
106 using TypeError = builtins::BuiltinsTypeError;
107 using AggregateError = builtins::BuiltinsAggregateError;
108 using URIError = builtins::BuiltinsURIError;
109 using SyntaxError = builtins::BuiltinsSyntaxError;
110 using EvalError = builtins::BuiltinsEvalError;
111 using OOMError = builtins::BuiltinsOOMError;
112 using ErrorType = base::ErrorType;
113 using ErrorHelper = base::ErrorHelper;
114 
ObjectFactory(JSThread * thread,Heap * heap,SharedHeap * sHeap)115 ObjectFactory::ObjectFactory(JSThread *thread, Heap *heap, SharedHeap *sHeap)
116     : thread_(thread), vm_(thread->GetEcmaVM()), heap_(heap), sHeap_(sHeap) {}
117 
NewMethodForNativeFunction(const void * func,FunctionKind kind,kungfu::BuiltinsStubCSigns::ID builtinId,MemSpaceType methodSpaceType)118 JSHandle<Method> ObjectFactory::NewMethodForNativeFunction(const void *func, FunctionKind kind,
119                                                            kungfu::BuiltinsStubCSigns::ID builtinId,
120                                                            MemSpaceType methodSpaceType)
121 {
122     uint32_t numArgs = 2;  // function object and this
123     auto method = NewSMethod(nullptr, methodSpaceType);
124     method->SetNativePointer(const_cast<void *>(func));
125     method->SetNativeBit(true);
126     if (builtinId != kungfu::BuiltinsStubCSigns::INVALID) {
127         bool isFast = kungfu::BuiltinsStubCSigns::IsFastBuiltin(builtinId);
128         method->SetFastBuiltinBit(isFast);
129         method->SetBuiltinId(static_cast<uint8_t>(builtinId));
130     }
131     method->SetNumArgsWithCallField(numArgs);
132     method->SetFunctionKind(kind);
133     return method;
134 }
135 
NewEcmaHClassClass(JSHClass * hclass,uint32_t size,JSType type)136 JSHandle<JSHClass> ObjectFactory::NewEcmaHClassClass(JSHClass *hclass, uint32_t size, JSType type)
137 {
138     NewObjectHook();
139     uint32_t classSize = JSHClass::SIZE;
140     auto *newClass = static_cast<JSHClass *>(heap_->AllocateClassClass(hclass, classSize));
141     newClass->Initialize(thread_, size, type, 0);
142 
143     return JSHandle<JSHClass>(thread_, newClass);
144 }
145 
InitClassClass()146 JSHandle<JSHClass> ObjectFactory::InitClassClass()
147 {
148     JSHandle<JSHClass> hClassHandle = NewEcmaHClassClass(nullptr, JSHClass::SIZE, JSType::HCLASS);
149     JSHClass *hclass = reinterpret_cast<JSHClass *>(hClassHandle.GetTaggedValue().GetTaggedObject());
150     hclass->SetClass(thread_, hclass);
151     return hClassHandle;
152 }
153 
NewEcmaHClass(JSHClass * hclass,uint32_t size,JSType type,uint32_t inlinedProps)154 JSHandle<JSHClass> ObjectFactory::NewEcmaHClass(JSHClass *hclass, uint32_t size, JSType type, uint32_t inlinedProps)
155 {
156     NewObjectHook();
157     uint32_t classSize = JSHClass::SIZE;
158     auto *newClass = static_cast<JSHClass *>(heap_->AllocateNonMovableOrHugeObject(hclass, classSize));
159     newClass->Initialize(thread_, size, type, inlinedProps);
160 
161     return JSHandle<JSHClass>(thread_, newClass);
162 }
163 
164 // This function don't UpdateProtoClass
NewEcmaHClass(uint32_t size,uint32_t inlinedProps,JSType type,const JSHandle<JSTaggedValue> & prototype,const JSHandle<JSTaggedValue> & layout)165 JSHandle<JSHClass> ObjectFactory::NewEcmaHClass(uint32_t size, uint32_t inlinedProps, JSType type,
166     const JSHandle<JSTaggedValue> &prototype, const JSHandle<JSTaggedValue> &layout)
167 {
168     NewSObjectHook();
169     uint32_t classSize = JSHClass::SIZE;
170     auto *newClass = static_cast<JSHClass *>(heap_->AllocateNonMovableOrHugeObject(
171         JSHClass::Cast(thread_->GlobalConstants()->GetHClassClass().GetTaggedObject()), classSize));
172     newClass->Initialize(thread_, size, type, inlinedProps, layout);
173     JSHandle<JSHClass> hclass(thread_, newClass);
174     if (prototype->IsJSObject()) {
175         prototype->GetTaggedObject()->GetClass()->SetIsPrototype(true);
176     }
177     hclass->SetProto(thread_, prototype.GetTaggedValue());
178     hclass->SetNumberOfProps(inlinedProps);
179     hclass->SetExtensible(false);
180     return hclass;
181 }
182 
NewEcmaReadOnlyHClass(JSHClass * hclass,uint32_t size,JSType type,uint32_t inlinedProps)183 JSHandle<JSHClass> ObjectFactory::NewEcmaReadOnlyHClass(JSHClass *hclass, uint32_t size, JSType type,
184                                                         uint32_t inlinedProps)
185 {
186     NewObjectHook();
187     uint32_t classSize = JSHClass::SIZE;
188     auto *newClass = static_cast<JSHClass *>(heap_->AllocateReadOnlyOrHugeObject(hclass, classSize));
189     ASSERT(newClass != nullptr);
190     newClass->Initialize(thread_, size, type, inlinedProps);
191 
192     return JSHandle<JSHClass>(thread_, newClass);
193 }
194 
NewEcmaHClass(uint32_t size,JSType type,uint32_t inlinedProps)195 JSHandle<JSHClass> ObjectFactory::NewEcmaHClass(uint32_t size, JSType type, uint32_t inlinedProps)
196 {
197     return NewEcmaHClass(JSHClass::Cast(thread_->GlobalConstants()->GetHClassClass().GetTaggedObject()),
198                          size, type, inlinedProps);
199 }
200 
InitObjectFields(const TaggedObject * object)201 void ObjectFactory::InitObjectFields(const TaggedObject *object)
202 {
203     auto *klass = object->GetClass();
204     auto objBodySize = klass->GetObjectSize() - TaggedObject::TaggedObjectSize();
205     ASSERT(objBodySize % JSTaggedValue::TaggedTypeSize() == 0);
206     uint32_t numOfFields = objBodySize / JSTaggedValue::TaggedTypeSize();
207     size_t addr = reinterpret_cast<uintptr_t>(object) + TaggedObject::TaggedObjectSize();
208     for (uint32_t i = 0; i < numOfFields; i++) {
209         auto *fieldAddr = reinterpret_cast<JSTaggedType *>(addr + i * JSTaggedValue::TaggedTypeSize());
210         *fieldAddr = JSTaggedValue::Undefined().GetRawData();
211     }
212 }
213 
NewJSArrayBufferData(const JSHandle<JSArrayBuffer> & array,int32_t length)214 void ObjectFactory::NewJSArrayBufferData(const JSHandle<JSArrayBuffer> &array, int32_t length)
215 {
216     if (length == 0) {
217         return;
218     }
219 
220     JSTaggedValue data = array->GetArrayBufferData();
221     size_t size = static_cast<size_t>(length) * sizeof(uint8_t);
222     if (!data.IsUndefined()) {
223         auto *pointer = JSNativePointer::Cast(data.GetTaggedObject());
224         auto newData = vm_->GetNativeAreaAllocator()->AllocateBuffer(size);
225         heap_->IncNativeSizeAfterLastGC(size);
226         if (memset_s(newData, length, 0, length) != EOK) {
227             LOG_FULL(FATAL) << "memset_s failed";
228             UNREACHABLE();
229         }
230         pointer->ResetExternalPointer(thread_, newData);
231         vm_->GetNativeAreaAllocator()->ModifyNativeSizeStats(pointer->GetBindingSize(), size,
232                                                              NativeFlag::ARRAY_BUFFER);
233         return;
234     }
235 
236     auto newData = vm_->GetNativeAreaAllocator()->AllocateBuffer(size);
237     heap_->IncNativeSizeAfterLastGC(size);
238     if (memset_s(newData, length, 0, length) != EOK) {
239         LOG_FULL(FATAL) << "memset_s failed";
240         UNREACHABLE();
241     }
242     JSHandle<JSNativePointer> pointer = NewJSNativePointer(newData, NativeAreaAllocator::FreeBufferFunc,
243                                                            vm_->GetNativeAreaAllocator(), false, size, Concurrent::NO,
244                                                            NativeFlag::ARRAY_BUFFER);
245     array->SetArrayBufferData(thread_, pointer);
246     array->SetWithNativeAreaAllocator(true);
247     vm_->GetNativeAreaAllocator()->IncreaseNativeSizeStats(length, NativeFlag::ARRAY_BUFFER);
248 }
249 
NewJSSendableArrayBufferData(const JSHandle<JSSendableArrayBuffer> & array,int32_t length)250 void ObjectFactory::NewJSSendableArrayBufferData(const JSHandle<JSSendableArrayBuffer> &array, int32_t length)
251 {
252     if (length == 0) {
253         return;
254     }
255 
256     JSTaggedValue data = array->GetArrayBufferData();
257     size_t size = static_cast<size_t>(length) * sizeof(uint8_t);
258     NativeAreaAllocator *nativeAreaAllocator = sHeap_->GetNativeAreaAllocator();
259     if (!data.IsUndefined()) {
260         auto *pointer = JSNativePointer::Cast(data.GetTaggedObject());
261         auto newData = nativeAreaAllocator->AllocateBuffer(size);
262         if (newData == nullptr) {
263             LOG_ECMA(FATAL) << "ObjectFactory::NewJSSendableArrayBufferData:newData is nullptr";
264         }
265         if (memset_s(newData, length, 0, length) != EOK) {
266             LOG_FULL(FATAL) << "memset_s failed";
267             UNREACHABLE();
268         }
269         pointer->ResetExternalPointer(thread_, newData);
270         nativeAreaAllocator->ModifyNativeSizeStats(pointer->GetBindingSize(), size,
271                                                    NativeFlag::ARRAY_BUFFER);
272         return;
273     }
274 
275     auto newData = nativeAreaAllocator->AllocateBuffer(size);
276     if (newData == nullptr) {
277         LOG_ECMA(FATAL) << "ObjectFactory::NewJSSendableArrayBufferData:newData is nullptr";
278     }
279     if (memset_s(newData, length, 0, length) != EOK) {
280         LOG_FULL(FATAL) << "memset_s failed";
281         UNREACHABLE();
282     }
283     JSHandle<JSNativePointer> pointer = NewSJSNativePointer(newData, NativeAreaAllocator::FreeBufferFunc,
284                                                             nativeAreaAllocator, false, size,
285                                                             NativeFlag::ARRAY_BUFFER);
286     array->SetArrayBufferData(thread_, pointer);
287     array->SetWithNativeAreaAllocator(true);
288     nativeAreaAllocator->IncreaseNativeSizeStats(length, NativeFlag::ARRAY_BUFFER);
289 }
290 
NewJSSendableArrayBuffer(int32_t length)291 JSHandle<JSSendableArrayBuffer> ObjectFactory::NewJSSendableArrayBuffer(int32_t length)
292 {
293     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
294 
295     JSHandle<JSFunction> constructor(env->GetSBuiltininArrayBufferFunction());
296     JSHandle<JSSendableArrayBuffer> sendableArrayBuffer(NewJSObjectByConstructor(constructor));
297     sendableArrayBuffer->SetArrayBufferByteLength(length);
298     if (length > 0) {
299         NewJSSendableArrayBufferData(sendableArrayBuffer, length);
300         sendableArrayBuffer->SetShared(false);
301     }
302     return sendableArrayBuffer;
303 }
304 
NewJSSendableArrayBuffer(void * buffer,int32_t length,const NativePointerCallback & deleter,void * data)305 JSHandle<JSSendableArrayBuffer> ObjectFactory::NewJSSendableArrayBuffer(void *buffer, int32_t length,
306                                                                         const NativePointerCallback &deleter,
307                                                                         void *data)
308 {
309     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
310 
311     JSHandle<JSFunction> constructor(env->GetSBuiltininArrayBufferFunction());
312     JSHandle<JSSendableArrayBuffer> sendableArrayBuffer(NewJSObjectByConstructor(constructor));
313     length = buffer == nullptr ? 0 : length;
314     sendableArrayBuffer->SetArrayBufferByteLength(length);
315     if (length > 0) {
316         JSHandle<JSNativePointer> pointer = NewSJSNativePointer(buffer, deleter, data, false, length);
317         sendableArrayBuffer->SetArrayBufferData(thread_, pointer.GetTaggedValue());
318         sendableArrayBuffer->SetShared(false);
319         sendableArrayBuffer->SetWithNativeAreaAllocator(deleter == NativeAreaAllocator::FreeBufferFunc &&
320                                                 data == vm_->GetNativeAreaAllocator());
321     }
322     return sendableArrayBuffer;
323 }
324 
NewJSSharedArrayBufferData(const JSHandle<JSArrayBuffer> & array,int32_t length)325 void ObjectFactory::NewJSSharedArrayBufferData(const JSHandle<JSArrayBuffer> &array, int32_t length)
326 {
327     if (length == 0) {
328         return;
329     }
330     void *newData = nullptr;
331     size_t size =
332         JSSharedMemoryManager::GetInstance()->CreateOrLoad(&newData, length) ? static_cast<size_t>(length) : 0U;
333     if (memset_s(newData, length, 0, length) != EOK) {
334         LOG_FULL(FATAL) << "memset_s failed";
335         UNREACHABLE();
336     }
337     JSHandle<JSNativePointer> pointer = NewJSNativePointer(newData, JSSharedMemoryManager::RemoveSharedMemory,
338                                                            JSSharedMemoryManager::GetInstance(), false, size);
339     array->SetArrayBufferData(thread_, pointer);
340     array->SetWithNativeAreaAllocator(false);
341 }
342 
NewJSArrayBuffer(int32_t length)343 JSHandle<JSArrayBuffer> ObjectFactory::NewJSArrayBuffer(int32_t length)
344 {
345     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
346 
347     JSHandle<JSFunction> constructor(env->GetArrayBufferFunction());
348     JSHandle<JSArrayBuffer> arrayBuffer(NewJSObjectByConstructor(constructor));
349     arrayBuffer->SetArrayBufferByteLength(length);
350     if (length > 0) {
351         auto newData = vm_->GetNativeAreaAllocator()->AllocateBuffer(length);
352         heap_->IncNativeSizeAfterLastGC(length);
353         if (memset_s(newData, length, 0, length) != EOK) {
354             LOG_FULL(FATAL) << "memset_s failed";
355             UNREACHABLE();
356         }
357         JSHandle<JSNativePointer> pointer = NewJSNativePointer(newData, NativeAreaAllocator::FreeBufferFunc,
358                                                                vm_->GetNativeAreaAllocator(), false, length,
359                                                                Concurrent::NO, NativeFlag::ARRAY_BUFFER);
360         arrayBuffer->SetArrayBufferData(thread_, pointer.GetTaggedValue());
361         arrayBuffer->SetWithNativeAreaAllocator(true);
362         vm_->GetNativeAreaAllocator()->IncreaseNativeSizeStats(length, NativeFlag::ARRAY_BUFFER);
363     }
364     return arrayBuffer;
365 }
366 
NewJSArrayBuffer(void * buffer,int32_t length,const NativePointerCallback & deleter,void * data,bool share)367 JSHandle<JSArrayBuffer> ObjectFactory::NewJSArrayBuffer(void *buffer, int32_t length,
368                                                         const NativePointerCallback &deleter, void *data, bool share)
369 {
370     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
371 
372     JSHandle<JSFunction> constructor(env->GetArrayBufferFunction());
373     JSHandle<JSArrayBuffer> arrayBuffer(NewJSObjectByConstructor(constructor));
374     length = buffer == nullptr ? 0 : length;
375     arrayBuffer->SetArrayBufferByteLength(length);
376     if (length > 0) {
377         JSHandle<JSNativePointer> pointer = NewJSNativePointer(buffer, deleter, data, false, length);
378         arrayBuffer->SetArrayBufferData(thread_, pointer.GetTaggedValue());
379         arrayBuffer->SetShared(share);
380         arrayBuffer->SetWithNativeAreaAllocator(deleter == NativeAreaAllocator::FreeBufferFunc &&
381                                                 data == vm_->GetNativeAreaAllocator());
382     }
383     return arrayBuffer;
384 }
385 
NewJSDataView(JSHandle<JSArrayBuffer> buffer,uint32_t offset,uint32_t length)386 JSHandle<JSDataView> ObjectFactory::NewJSDataView(JSHandle<JSArrayBuffer> buffer, uint32_t offset, uint32_t length)
387 {
388     uint32_t arrayLength = buffer->GetArrayBufferByteLength();
389     if (arrayLength - offset < length) {
390         THROW_TYPE_ERROR_AND_RETURN(thread_, "offset or length error",
391                                     JSHandle<JSDataView>(thread_, JSTaggedValue::Undefined()));
392     }
393     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
394 
395     JSHandle<JSFunction> constructor(env->GetDataViewFunction());
396     JSHandle<JSDataView> arrayBuffer(NewJSObjectByConstructor(constructor));
397     arrayBuffer->SetDataView(thread_, JSTaggedValue::True());
398     arrayBuffer->SetViewedArrayBuffer(thread_, buffer.GetTaggedValue());
399     arrayBuffer->SetByteLength(length);
400     arrayBuffer->SetByteOffset(offset);
401     return arrayBuffer;
402 }
403 
NewJSSharedArrayBuffer(int32_t length)404 JSHandle<JSArrayBuffer> ObjectFactory::NewJSSharedArrayBuffer(int32_t length)
405 {
406     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
407 
408     JSHandle<JSFunction> constructor(env->GetSharedArrayBufferFunction());
409     JSHandle<JSArrayBuffer> sharedArrayBuffer(NewJSObjectByConstructor(constructor));
410     sharedArrayBuffer->SetArrayBufferByteLength(length);
411     if (length > 0) {
412         NewJSSharedArrayBufferData(sharedArrayBuffer, length);
413         sharedArrayBuffer->SetShared(true);
414     }
415     return sharedArrayBuffer;
416 }
417 
NewJSSharedArrayBuffer(void * buffer,int32_t length)418 JSHandle<JSArrayBuffer> ObjectFactory::NewJSSharedArrayBuffer(void *buffer, int32_t length)
419 {
420     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
421 
422     JSHandle<JSFunction> constructor(env->GetSharedArrayBufferFunction());
423     JSHandle<JSArrayBuffer> sharedArrayBuffer(NewJSObjectByConstructor(constructor));
424     length = buffer == nullptr ? 0 : length;
425     sharedArrayBuffer->SetArrayBufferByteLength(length);
426     if (length > 0) {
427         JSHandle<JSNativePointer> pointer = NewJSNativePointer(buffer, JSSharedMemoryManager::RemoveSharedMemory,
428                                                                JSSharedMemoryManager::GetInstance(), false, length);
429         sharedArrayBuffer->SetArrayBufferData(thread_, pointer);
430         sharedArrayBuffer->SetShared(true);
431         sharedArrayBuffer->SetWithNativeAreaAllocator(false);
432     }
433     return sharedArrayBuffer;
434 }
435 
NewJSRegExpByteCodeData(const JSHandle<JSRegExp> & regexp,void * buffer,size_t size)436 void ObjectFactory::NewJSRegExpByteCodeData(const JSHandle<JSRegExp> &regexp, void *buffer, size_t size)
437 {
438     if (buffer == nullptr) {
439         return;
440     }
441 
442     auto newBuffer = vm_->GetNativeAreaAllocator()->AllocateBuffer(size);
443     heap_->IncNativeSizeAfterLastGC(size);
444     if (memcpy_s(newBuffer, size, buffer, size) != EOK) {
445         LOG_FULL(FATAL) << "memcpy_s failed";
446         UNREACHABLE();
447     }
448     JSTaggedValue data = regexp->GetByteCodeBuffer();
449     if (!data.IsUndefined()) {
450         JSNativePointer *native = JSNativePointer::Cast(data.GetTaggedObject());
451         native->ResetExternalPointer(thread_, newBuffer);
452         return;
453     }
454     JSHandle<JSNativePointer> pointer = NewJSNativePointer(newBuffer, NativeAreaAllocator::FreeBufferFunc,
455                                                            vm_->GetNativeAreaAllocator(), false, size, Concurrent::NO,
456                                                            NativeFlag::REGEXP_BTYECODE);
457     regexp->SetByteCodeBuffer(thread_, pointer.GetTaggedValue());
458     regexp->SetLength(static_cast<uint32_t>(size));
459     vm_->GetNativeAreaAllocator()->IncreaseNativeSizeStats(size, NativeFlag::REGEXP_BTYECODE);
460 }
461 
NewEcmaHClass(uint32_t size,JSType type,const JSHandle<JSTaggedValue> & prototype)462 JSHandle<JSHClass> ObjectFactory::NewEcmaHClass(uint32_t size, JSType type, const JSHandle<JSTaggedValue> &prototype)
463 {
464     const int inlinedProps = JSHClass::DEFAULT_CAPACITY_OF_IN_OBJECTS;
465     return NewEcmaHClass(size, inlinedProps, type, prototype);
466 }
467 
NewEcmaHClass(uint32_t size,uint32_t inlinedProps,JSType type,const JSHandle<JSTaggedValue> & prototype)468 JSHandle<JSHClass> ObjectFactory::NewEcmaHClass(uint32_t size, uint32_t inlinedProps, JSType type,
469                                                 const JSHandle<JSTaggedValue> &prototype)
470 {
471     NewObjectHook();
472     uint32_t classSize = JSHClass::SIZE;
473     auto *newClass = static_cast<JSHClass *>(heap_->AllocateNonMovableOrHugeObject(
474         JSHClass::Cast(thread_->GlobalConstants()->GetHClassClass().GetTaggedObject()), classSize));
475     newClass->Initialize(thread_, size, type, inlinedProps);
476     JSHandle<JSHClass> hclass(thread_, newClass);
477     hclass->SetPrototype(thread_, prototype.GetTaggedValue());
478     return hclass;
479 }
480 
NewJSObject(const JSHandle<JSHClass> & jshclass)481 JSHandle<JSObject> ObjectFactory::NewJSObject(const JSHandle<JSHClass> &jshclass)
482 {
483     JSHandle<JSObject> obj(thread_, JSObject::Cast(NewObject(jshclass)));
484     JSHandle<TaggedArray> emptyArray = EmptyArray();
485     obj->InitializeHash();
486     obj->SetElements(thread_, emptyArray, SKIP_BARRIER);
487     obj->SetProperties(thread_, emptyArray, SKIP_BARRIER);
488     return obj;
489 }
490 
CloneProperties(const JSHandle<TaggedArray> & old)491 JSHandle<TaggedArray> ObjectFactory::CloneProperties(const JSHandle<TaggedArray> &old)
492 {
493     uint32_t newLength = old->GetLength();
494     if (newLength == 0) {
495         return EmptyArray();
496     }
497     NewObjectHook();
498     auto klass = old->GetClass();
499     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), newLength);
500     auto header = heap_->AllocateYoungOrHugeObject(klass, size);
501     JSHandle<TaggedArray> newArray(thread_, header);
502     newArray->InitializeWithSpecialValue(JSTaggedValue::Hole(), newLength, old->GetExtraLength());
503     for (uint32_t i = 0; i < newLength; i++) {
504         JSTaggedValue value = old->Get(i);
505         newArray->Set(thread_, i, value);
506     }
507     return newArray;
508 }
509 
CloneObjectLiteral(JSHandle<JSObject> object)510 JSHandle<JSObject> ObjectFactory::CloneObjectLiteral(JSHandle<JSObject> object)
511 {
512     NewObjectHook();
513     auto klass = JSHandle<JSHClass>(thread_, object->GetClass());
514 
515     JSHandle<JSObject> cloneObject = NewJSObject(klass);
516 
517     JSHandle<TaggedArray> elements(thread_, object->GetElements());
518     auto newElements = CloneProperties(elements);
519     cloneObject->SetElements(thread_, newElements.GetTaggedValue());
520 
521     JSHandle<TaggedArray> properties(thread_, object->GetProperties());
522     auto newProperties = CloneProperties(properties);
523     cloneObject->SetProperties(thread_, newProperties.GetTaggedValue());
524     uint32_t length = std::min(klass->GetInlinedProperties(), klass->NumberOfProps());
525 
526     for (uint32_t i = 0; i < length; i++) {
527         cloneObject->SetPropertyInlinedPropsWithRep(thread_, i, object->GetPropertyInlinedProps(i));
528     }
529     return cloneObject;
530 }
531 
CloneArrayLiteral(JSHandle<JSArray> object)532 JSHandle<JSArray> ObjectFactory::CloneArrayLiteral(JSHandle<JSArray> object)
533 {
534     NewObjectHook();
535     auto klass = JSHandle<JSHClass>(thread_, object->GetClass());
536 
537     JSHandle<JSArray> cloneObject(NewJSObject(klass));
538     cloneObject->SetArrayLength(thread_, object->GetArrayLength());
539     cloneObject->SetTrackInfo(thread_, JSTaggedValue::Undefined());
540 
541     JSHandle<TaggedArray> elements(thread_, object->GetElements());
542     static constexpr uint8_t MAX_READ_ONLY_ARRAY_LENGTH = 10;
543     uint32_t elementsLength = elements->GetLength();
544     MemSpaceType type = elementsLength > MAX_READ_ONLY_ARRAY_LENGTH ?
545         MemSpaceType::SEMI_SPACE : MemSpaceType::NON_MOVABLE;
546 
547 #if !defined ENABLE_COW_ARRAY
548     type = MemSpaceType::SEMI_SPACE;
549 #endif
550 
551     if (type == MemSpaceType::NON_MOVABLE && elements.GetTaggedValue().IsCOWArray()) {
552         // share the same elements array in nonmovable space.
553         cloneObject->SetElements(thread_, elements.GetTaggedValue());
554     } else {
555         auto newElements = CopyArray(elements, elementsLength, elementsLength, JSTaggedValue::Hole(), type);
556         cloneObject->SetElements(thread_, newElements.GetTaggedValue());
557     }
558 
559     if (type == MemSpaceType::NON_MOVABLE && !object->GetElements().IsCOWArray()) {
560         ASSERT(!Region::ObjectAddressToRange(object->GetElements().GetTaggedObject())->InNonMovableSpace());
561         // Set the first shared elements into the old object.
562         object->SetElements(thread_, cloneObject->GetElements());
563     }
564 
565     JSHandle<TaggedArray> properties(thread_, object->GetProperties());
566     uint32_t propertiesLength = properties->GetLength();
567     type = propertiesLength > MAX_READ_ONLY_ARRAY_LENGTH ?
568         MemSpaceType::SEMI_SPACE : MemSpaceType::NON_MOVABLE;
569 
570 #if !defined ENABLE_COW_ARRAY
571     type = MemSpaceType::SEMI_SPACE;
572 #endif
573 
574     if (type == MemSpaceType::NON_MOVABLE && properties.GetTaggedValue().IsCOWArray()) {
575         // share the same properties array in nonmovable space.
576         cloneObject->SetProperties(thread_, properties.GetTaggedValue());
577     } else {
578         auto newProperties = CopyArray(properties, propertiesLength, propertiesLength, JSTaggedValue::Hole(), type);
579         cloneObject->SetProperties(thread_, newProperties.GetTaggedValue());
580     }
581 
582     if (type == MemSpaceType::NON_MOVABLE && !object->GetProperties().IsCOWArray()) {
583         ASSERT(!Region::ObjectAddressToRange(object->GetProperties().GetTaggedObject())->InNonMovableSpace());
584         // Set the first shared properties into the old object.
585         object->SetProperties(thread_, cloneObject->GetProperties());
586     }
587 
588     for (uint32_t i = 0; i < klass->GetInlinedProperties(); i++) {
589         cloneObject->SetPropertyInlinedPropsWithRep(thread_, i, object->GetPropertyInlinedProps(i));
590     }
591     return cloneObject;
592 }
593 
CloneProperties(const JSHandle<TaggedArray> & old,const JSHandle<JSTaggedValue> & env,const JSHandle<JSObject> & obj)594 JSHandle<TaggedArray> ObjectFactory::CloneProperties(const JSHandle<TaggedArray> &old,
595                                                      const JSHandle<JSTaggedValue> &env, const JSHandle<JSObject> &obj)
596 {
597     uint32_t newLength = old->GetLength();
598     if (newLength == 0) {
599         return EmptyArray();
600     }
601     NewObjectHook();
602     auto klass = old->GetClass();
603     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), newLength);
604     auto header = heap_->AllocateYoungOrHugeObject(klass, size);
605     JSHandle<TaggedArray> newArray(thread_, header);
606     newArray->InitializeWithSpecialValue(JSTaggedValue::Hole(), newLength, old->GetExtraLength());
607 
608     for (uint32_t i = 0; i < newLength; i++) {
609         JSTaggedValue value = old->Get(i);
610         if (!value.IsJSFunction()) {
611             newArray->Set(thread_, i, value);
612         } else {
613             JSHandle<JSFunction> valueHandle(thread_, value);
614             JSHandle<JSFunction> newFunc = CloneJSFunction(valueHandle);
615             newFunc->SetLexicalEnv(thread_, env);
616             newFunc->SetHomeObject(thread_, obj);
617             newArray->Set(thread_, i, newFunc);
618         }
619     }
620     return newArray;
621 }
622 
CloneObjectLiteral(JSHandle<JSObject> object,const JSHandle<JSTaggedValue> & env,bool canShareHClass)623 JSHandle<JSObject> ObjectFactory::CloneObjectLiteral(JSHandle<JSObject> object,
624                                                      const JSHandle<JSTaggedValue> &env,
625                                                      bool canShareHClass)
626 {
627     NewObjectHook();
628     auto klass = JSHandle<JSHClass>(thread_, object->GetClass());
629 
630     if (!canShareHClass) {
631         klass = JSHClass::Clone(thread_, klass);
632     }
633 
634     JSHandle<JSObject> cloneObject = NewJSObject(klass);
635 
636     JSHandle<TaggedArray> elements(thread_, object->GetElements());
637     auto newElements = CloneProperties(elements, env, cloneObject);
638     cloneObject->SetElements(thread_, newElements.GetTaggedValue());
639 
640     JSHandle<TaggedArray> properties(thread_, object->GetProperties());
641     auto newProperties = CloneProperties(properties, env, cloneObject);
642     cloneObject->SetProperties(thread_, newProperties.GetTaggedValue());
643     uint32_t length = std::min(klass->GetInlinedProperties(), klass->NumberOfProps());
644 
645     for (uint32_t i = 0; i < length; i++) {
646         auto layout = LayoutInfo::Cast(klass->GetLayout().GetTaggedObject());
647         JSTaggedValue value = object->GetPropertyInlinedProps(i);
648         if (!layout->GetAttr(i).IsTaggedRep() || (!value.IsJSFunction() && !value.IsAccessorData())) {
649             cloneObject->SetPropertyInlinedPropsWithRep(thread_, i, value);
650         } else if (value.IsJSFunction()) {
651             JSHandle<JSFunction> valueHandle(thread_, value);
652             JSHandle<JSFunction> newFunc = CloneJSFunction(valueHandle);
653             newFunc->SetLexicalEnv(thread_, env);
654             newFunc->SetHomeObject(thread_, cloneObject);
655             cloneObject->SetPropertyInlinedProps(thread_, i, newFunc.GetTaggedValue());
656         } else {
657             if (value.IsAccessorData()) {
658                 JSHandle<AccessorData> accessor = NewAccessorData();
659                 value = accessor.GetTaggedValue();
660             }
661             cloneObject->SetPropertyInlinedPropsWithRep(thread_, i, value);
662         }
663     }
664     return cloneObject;
665 }
666 
CloneJSFunction(JSHandle<JSFunction> func)667 JSHandle<JSFunction> ObjectFactory::CloneJSFunction(JSHandle<JSFunction> func)
668 {
669     JSHandle<JSHClass> jshclass(thread_, func->GetJSHClass());
670     JSHandle<Method> method(thread_, func->GetMethod());
671     JSHandle<JSFunction> cloneFunc = NewJSFunctionByHClass(method, jshclass);
672 
673     JSTaggedValue length = func->GetPropertyInlinedProps(JSFunction::LENGTH_INLINE_PROPERTY_INDEX);
674     cloneFunc->SetPropertyInlinedProps(thread_, JSFunction::LENGTH_INLINE_PROPERTY_INDEX, length);
675     cloneFunc->SetLength(func->GetLength());
676     cloneFunc->SetModule(thread_, func->GetModule());
677     return cloneFunc;
678 }
679 
CloneSFunction(JSHandle<JSFunction> func)680 JSHandle<JSFunction> ObjectFactory::CloneSFunction(JSHandle<JSFunction> func)
681 {
682     ASSERT(func.GetTaggedValue().IsJSSharedFunction());
683     JSHandle<JSHClass> jshclass(thread_, func->GetJSHClass());
684     JSHandle<Method> method(thread_, func->GetMethod());
685     JSHandle<JSFunction> cloneFunc = NewSFunctionByHClass(method, jshclass);
686 
687     JSTaggedValue length = func->GetPropertyInlinedProps(JSFunction::LENGTH_INLINE_PROPERTY_INDEX);
688     cloneFunc->SetPropertyInlinedProps(thread_, JSFunction::LENGTH_INLINE_PROPERTY_INDEX, length);
689     cloneFunc->SetLength(func->GetLength());
690     cloneFunc->SetModule(thread_, func->GetModule());
691     return cloneFunc;
692 }
693 
CreateJSFunctionFromTemplate(JSHandle<FunctionTemplate> funcTemp)694 JSHandle<JSFunction> ObjectFactory::CreateJSFunctionFromTemplate(JSHandle<FunctionTemplate> funcTemp)
695 {
696     NewObjectHook();
697     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
698     auto kind = funcTemp->GetFunctionKind();
699     JSHandle<JSHClass> jshclass;
700     if (kind == FunctionKind::NORMAL_FUNCTION ||
701         kind == FunctionKind::GETTER_FUNCTION ||
702         kind == FunctionKind::SETTER_FUNCTION) {
703         jshclass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithoutProto());
704     } else if (kind == FunctionKind::ASYNC_FUNCTION) {
705         jshclass = JSHandle<JSHClass>::Cast(env->GetAsyncFunctionClass());
706     } else {
707         jshclass = JSHandle<JSHClass>::Cast(env->GetGeneratorFunctionClass());
708     }
709     JSHandle<Method> method = JSHandle<Method>(thread_, funcTemp->GetMethod());
710     JSHandle<JSFunction> newFunc = NewJSFunctionByHClass(method, jshclass);
711 
712     newFunc->SetLength(funcTemp->GetLength());
713     newFunc->SetModule(thread_, funcTemp->GetModule());
714     return newFunc;
715 }
716 
CreateSFunctionFromTemplate(JSHandle<FunctionTemplate> funcTemp)717 JSHandle<JSFunction> ObjectFactory::CreateSFunctionFromTemplate(JSHandle<FunctionTemplate> funcTemp)
718 {
719     NewObjectHook();
720     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
721     auto kind = funcTemp->GetFunctionKind();
722     JSHandle<JSHClass> jshclass;
723     if (kind == FunctionKind::NORMAL_FUNCTION ||
724         kind == FunctionKind::GETTER_FUNCTION ||
725         kind == FunctionKind::SETTER_FUNCTION) {
726         jshclass = JSHandle<JSHClass>::Cast(env->GetSFunctionClassWithoutProto());
727     } else if (kind == FunctionKind::ASYNC_FUNCTION) {
728         jshclass = JSHandle<JSHClass>::Cast(env->GetAsyncFunctionClass());
729     } else {
730         jshclass = JSHandle<JSHClass>::Cast(env->GetGeneratorFunctionClass());
731     }
732     JSHandle<Method> method(thread_, funcTemp->GetMethod());
733     JSHandle<JSFunction> newFunc = NewSFunctionByHClass(method, jshclass);
734 
735     newFunc->SetLength(funcTemp->GetLength());
736     newFunc->SetModule(thread_, funcTemp->GetModule());
737     return newFunc;
738 }
739 
CloneClassCtor(JSHandle<JSFunction> ctor,const JSHandle<JSTaggedValue> & lexenv,bool canShareHClass)740 JSHandle<JSFunction> ObjectFactory::CloneClassCtor(JSHandle<JSFunction> ctor, const JSHandle<JSTaggedValue> &lexenv,
741                                                    bool canShareHClass)
742 {
743     NewObjectHook();
744     JSHandle<JSHClass> hclass(thread_, ctor->GetClass());
745 
746     if (!canShareHClass) {
747         hclass = JSHClass::Clone(thread_, hclass);
748     }
749 
750     JSHandle<Method> method(thread_, ctor->GetMethod());
751     ASSERT_PRINT(method->GetFunctionKind() == FunctionKind::CLASS_CONSTRUCTOR ||
752                  method->GetFunctionKind() == FunctionKind::DERIVED_CONSTRUCTOR,
753                  "cloned function is not class");
754     JSHandle<JSFunction> cloneCtor = NewJSFunctionByHClass(method, hclass);
755     uint32_t length = std::min(hclass->GetInlinedProperties(), hclass->NumberOfProps());
756 
757     for (uint32_t i = 0; i < length; i++) {
758         auto layout = LayoutInfo::Cast(hclass->GetLayout().GetTaggedObject());
759         JSTaggedValue value = ctor->GetPropertyInlinedProps(i);
760         if (!layout->GetAttr(i).IsTaggedRep() || !value.IsJSFunction()) {
761             cloneCtor->SetPropertyInlinedPropsWithRep(thread_, i, value);
762         } else {
763             JSHandle<JSFunction> valueHandle(thread_, value);
764             JSHandle<JSFunction> newFunc = CloneJSFunction(valueHandle);
765             newFunc->SetLexicalEnv(thread_, lexenv);
766             newFunc->SetHomeObject(thread_, cloneCtor);
767             cloneCtor->SetPropertyInlinedProps(thread_, i, newFunc.GetTaggedValue());
768         }
769     }
770 
771     JSHandle<TaggedArray> elements(thread_, ctor->GetElements());
772     auto newElements = CloneProperties(elements, lexenv, JSHandle<JSObject>(cloneCtor));
773     cloneCtor->SetElements(thread_, newElements.GetTaggedValue());
774 
775     JSHandle<TaggedArray> properties(thread_, ctor->GetProperties());
776     auto newProperties = CloneProperties(properties, lexenv, JSHandle<JSObject>(cloneCtor));
777     cloneCtor->SetProperties(thread_, newProperties.GetTaggedValue());
778 
779     return cloneCtor;
780 }
781 
NewNonMovableJSObject(const JSHandle<JSHClass> & jshclass)782 JSHandle<JSObject> ObjectFactory::NewNonMovableJSObject(const JSHandle<JSHClass> &jshclass)
783 {
784     JSHandle<JSObject> obj(thread_,
785                            JSObject::Cast(NewNonMovableObject(jshclass, jshclass->GetInlinedProperties())));
786     obj->InitializeHash();
787     obj->SetElements(thread_, EmptyArray(), SKIP_BARRIER);
788     obj->SetProperties(thread_, EmptyArray(), SKIP_BARRIER);
789     return obj;
790 }
791 
NewJSPrimitiveRef(const JSHandle<JSHClass> & hclass,const JSHandle<JSTaggedValue> & object)792 JSHandle<JSPrimitiveRef> ObjectFactory::NewJSPrimitiveRef(const JSHandle<JSHClass> &hclass,
793                                                           const JSHandle<JSTaggedValue> &object)
794 {
795     JSHandle<JSPrimitiveRef> obj = JSHandle<JSPrimitiveRef>::Cast(NewJSObject(hclass));
796     obj->SetValue(thread_, object);
797     return obj;
798 }
799 
NewJSArray()800 JSHandle<JSArray> ObjectFactory::NewJSArray()
801 {
802     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
803     JSHandle<JSFunction> function(env->GetArrayFunction());
804     return JSHandle<JSArray>(NewJSObjectByConstructor(function));
805 }
806 
NewJSArray(size_t length,JSHandle<JSHClass> & hclass)807 JSHandle<JSArray> ObjectFactory::NewJSArray(size_t length, JSHandle<JSHClass> &hclass)
808 {
809     JSHandle<JSObject> obj = NewJSObject(hclass);
810     JSArray::Cast(*obj)->SetLength(length);
811     JSArray::Cast(*obj)->SetTrackInfo(thread_, JSTaggedValue::Undefined());
812     auto accessor = thread_->GlobalConstants()->GetArrayLengthAccessor();
813     JSArray::Cast(*obj)->SetPropertyInlinedProps(thread_, JSArray::LENGTH_INLINE_PROPERTY_INDEX, accessor);
814     return JSHandle<JSArray>(obj);
815 }
816 
NewJsonFixedArray(size_t start,size_t length,const std::vector<JSHandle<JSTaggedValue>> & vec)817 JSHandle<TaggedArray> ObjectFactory::NewJsonFixedArray(size_t start, size_t length,
818                                                        const std::vector<JSHandle<JSTaggedValue>> &vec)
819 {
820     if (length == 0) {
821         return EmptyArray();
822     }
823 
824     MemSpaceType spaceType = length < LENGTH_THRESHOLD ? MemSpaceType::SEMI_SPACE : MemSpaceType::OLD_SPACE;
825     JSHandle<TaggedArray> array = NewTaggedArrayWithoutInit(length, spaceType);
826     array->SetExtraLength(0);
827     for (size_t i = 0; i < length; i++) {
828         array->Set(thread_, i, vec[start + i]);
829     }
830     return array;
831 }
832 
NewJSForinIterator(const JSHandle<JSTaggedValue> & obj,const JSHandle<JSTaggedValue> keys,const JSHandle<JSTaggedValue> cachedHclass)833 JSHandle<JSForInIterator> ObjectFactory::NewJSForinIterator(const JSHandle<JSTaggedValue> &obj,
834                                                             const JSHandle<JSTaggedValue> keys,
835                                                             const JSHandle<JSTaggedValue> cachedHclass)
836 {
837     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
838     JSHandle<JSHClass> hclass(env->GetForinIteratorClass());
839 
840     JSHandle<JSForInIterator> it = JSHandle<JSForInIterator>::Cast(NewJSObject(hclass));
841     it->SetObject(thread_, obj);
842     it->SetCachedHclass(thread_, cachedHclass);
843     it->SetKeys(thread_, keys);
844     it->SetIndex(EnumCache::ENUM_CACHE_HEADER_SIZE);
845     uint32_t enumLength = JSHandle<TaggedArray>::Cast(keys)->GetLength();
846     it->SetLength(enumLength);
847     return it;
848 }
849 
CreateJSRegExpInstanceClass(JSHandle<JSTaggedValue> proto)850 JSHandle<JSHClass> ObjectFactory::CreateJSRegExpInstanceClass(JSHandle<JSTaggedValue> proto)
851 {
852     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
853     JSHandle<JSHClass> regexpClass = NewEcmaHClass(JSRegExp::SIZE, JSType::JS_REG_EXP, proto);
854 
855     uint32_t fieldOrder = 0;
856     JSHandle<LayoutInfo> layoutInfoHandle = CreateLayoutInfo(1);
857     {
858         PropertyAttributes attributes = PropertyAttributes::Default(true, false, false);
859         attributes.SetIsInlinedProps(true);
860         attributes.SetRepresentation(Representation::TAGGED);
861         attributes.SetOffset(fieldOrder++);
862         layoutInfoHandle->AddKey(thread_, 0, globalConst->GetLastIndexString(), attributes);
863     }
864 
865     {
866         regexpClass->SetLayout(thread_, layoutInfoHandle);
867         regexpClass->SetNumberOfProps(fieldOrder);
868     }
869 
870     return regexpClass;
871 }
872 
CreateJSArrayInstanceClass(JSHandle<JSTaggedValue> proto,uint32_t inlinedProps)873 JSHandle<JSHClass> ObjectFactory::CreateJSArrayInstanceClass(JSHandle<JSTaggedValue> proto, uint32_t inlinedProps)
874 {
875     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
876     JSHandle<JSHClass> arrayClass = NewEcmaHClass(JSArray::SIZE, inlinedProps, JSType::JS_ARRAY, proto);
877 
878     uint32_t fieldOrder = 0;
879     ASSERT(JSArray::LENGTH_INLINE_PROPERTY_INDEX == fieldOrder);
880     JSHandle<LayoutInfo> layoutInfoHandle = CreateLayoutInfo(1);
881     {
882         PropertyAttributes attributes = PropertyAttributes::DefaultAccessor(true, false, false);
883         attributes.SetIsInlinedProps(true);
884         attributes.SetRepresentation(Representation::TAGGED);
885         attributes.SetOffset(fieldOrder++);
886         layoutInfoHandle->AddKey(thread_, 0, globalConst->GetLengthString(), attributes);
887     }
888 
889     {
890         arrayClass->SetLayout(thread_, layoutInfoHandle);
891         arrayClass->SetNumberOfProps(fieldOrder);
892     }
893     arrayClass->SetIsStableElements(true);
894     arrayClass->SetHasConstructor(false);
895 
896     return arrayClass;
897 }
898 
CreateJSArguments(const JSHandle<GlobalEnv> & env)899 JSHandle<JSHClass> ObjectFactory::CreateJSArguments(const JSHandle<GlobalEnv> &env)
900 {
901     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
902     JSHandle<JSTaggedValue> proto = env->GetObjectFunctionPrototype();
903 
904     JSHandle<JSHClass> argumentsClass = NewEcmaHClass(JSArguments::SIZE, JSType::JS_ARGUMENTS, proto);
905 
906     uint32_t fieldOrder = 0;
907     ASSERT(JSArguments::LENGTH_INLINE_PROPERTY_INDEX == fieldOrder);
908     JSHandle<LayoutInfo> layoutInfoHandle = CreateLayoutInfo(JSArguments::LENGTH_OF_INLINE_PROPERTIES);
909     {
910         PropertyAttributes attributes = PropertyAttributes::Default(true, false, true);
911         attributes.SetIsInlinedProps(true);
912         attributes.SetRepresentation(Representation::TAGGED);
913         attributes.SetOffset(fieldOrder++);
914         layoutInfoHandle->AddKey(thread_, JSArguments::LENGTH_INLINE_PROPERTY_INDEX, globalConst->GetLengthString(),
915                                  attributes);
916     }
917 
918     ASSERT(JSArguments::ITERATOR_INLINE_PROPERTY_INDEX == fieldOrder);
919     {
920         PropertyAttributes attributes = PropertyAttributes::Default(true, false, true);
921         attributes.SetIsInlinedProps(true);
922         attributes.SetRepresentation(Representation::TAGGED);
923         attributes.SetOffset(fieldOrder++);
924         layoutInfoHandle->AddKey(thread_, JSArguments::ITERATOR_INLINE_PROPERTY_INDEX,
925                                  env->GetIteratorSymbol().GetTaggedValue(), attributes);
926     }
927 
928     {
929         ASSERT(JSArguments::CALLER_INLINE_PROPERTY_INDEX == fieldOrder);
930         PropertyAttributes attributes = PropertyAttributes::Default(false, false, false);
931         attributes.SetIsInlinedProps(true);
932         attributes.SetIsAccessor(true);
933         attributes.SetRepresentation(Representation::TAGGED);
934         attributes.SetOffset(fieldOrder++);
935         layoutInfoHandle->AddKey(thread_, JSArguments::CALLER_INLINE_PROPERTY_INDEX,
936                                  thread_->GlobalConstants()->GetHandledCallerString().GetTaggedValue(), attributes);
937     }
938 
939     {
940         ASSERT(JSArguments::CALLEE_INLINE_PROPERTY_INDEX == fieldOrder);
941         PropertyAttributes attributes = PropertyAttributes::Default(false, false, false);
942         attributes.SetIsInlinedProps(true);
943         attributes.SetIsAccessor(true);
944         attributes.SetRepresentation(Representation::TAGGED);
945         attributes.SetOffset(fieldOrder++);
946         layoutInfoHandle->AddKey(thread_, JSArguments::CALLEE_INLINE_PROPERTY_INDEX,
947                                  thread_->GlobalConstants()->GetHandledCalleeString().GetTaggedValue(), attributes);
948     }
949 
950     {
951         argumentsClass->SetLayout(thread_, layoutInfoHandle);
952         argumentsClass->SetNumberOfProps(fieldOrder);
953     }
954     argumentsClass->SetIsStableElements(true);
955     return argumentsClass;
956 }
957 
NewJSArguments()958 JSHandle<JSArguments> ObjectFactory::NewJSArguments()
959 {
960     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
961     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetArgumentsClass());
962     JSHandle<JSArguments> obj = JSHandle<JSArguments>::Cast(NewJSObject(hclass));
963     return obj;
964 }
965 
GetJSError(const ErrorType & errorType,const char * data,StackCheck needCheckStack)966 JSHandle<JSObject> ObjectFactory::GetJSError(const ErrorType &errorType, const char *data, StackCheck needCheckStack)
967 {
968     ASSERT_PRINT(errorType == ErrorType::ERROR || errorType == ErrorType::EVAL_ERROR ||
969                      errorType == ErrorType::RANGE_ERROR || errorType == ErrorType::REFERENCE_ERROR ||
970                      errorType == ErrorType::SYNTAX_ERROR || errorType == ErrorType::TYPE_ERROR ||
971                      errorType == ErrorType::URI_ERROR || errorType == ErrorType::OOM_ERROR ||
972                      errorType == ErrorType::TERMINATION_ERROR,
973                  "The error type is not in the valid range.");
974     if (data != nullptr) {
975         JSHandle<EcmaString> handleMsg = NewFromUtf8(data);
976         return NewJSError(errorType, handleMsg, needCheckStack);
977     }
978     JSHandle<EcmaString> emptyString(thread_->GlobalConstants()->GetHandledEmptyString());
979     return NewJSError(errorType, emptyString, needCheckStack);
980 }
981 
NewJSError(const ErrorType & errorType,const JSHandle<EcmaString> & message,StackCheck needCheckStack)982 JSHandle<JSObject> ObjectFactory::NewJSError(const ErrorType &errorType, const JSHandle<EcmaString> &message,
983     StackCheck needCheckStack)
984 {
985     // if there have exception in thread, then return current exception, no need to new js error.
986     if (thread_->HasPendingException()) {
987         JSHandle<JSObject> obj(thread_, thread_->GetException());
988         return obj;
989     }
990 
991     // current frame may be entry frame, exception happened in JSFunction::Call and JSFunction::Construct,
992     // in this case sp = the prev frame (interpreter frame).
993     if (!thread_->IsAsmInterpreter()) {
994         FrameHandler frameHandler(thread_);
995         if (frameHandler.IsInterpretedEntryFrame()) {
996             thread_->SetCurrentSPFrame(frameHandler.GetPrevJSFrame());
997         }
998     }
999 
1000     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
1001     JSHandle<JSTaggedValue> nativeConstructor;
1002     switch (errorType) {
1003         case ErrorType::RANGE_ERROR:
1004             nativeConstructor = env->GetRangeErrorFunction();
1005             break;
1006         case ErrorType::EVAL_ERROR:
1007             nativeConstructor = env->GetEvalErrorFunction();
1008             break;
1009         case ErrorType::REFERENCE_ERROR:
1010             nativeConstructor = env->GetReferenceErrorFunction();
1011             break;
1012         case ErrorType::TYPE_ERROR:
1013             nativeConstructor = env->GetTypeErrorFunction();
1014             break;
1015         case ErrorType::URI_ERROR:
1016             nativeConstructor = env->GetURIErrorFunction();
1017             break;
1018         case ErrorType::SYNTAX_ERROR:
1019             nativeConstructor = env->GetSyntaxErrorFunction();
1020             break;
1021         case ErrorType::OOM_ERROR:
1022             nativeConstructor = env->GetOOMErrorFunction();
1023             break;
1024         case ErrorType::TERMINATION_ERROR:
1025             nativeConstructor = env->GetTerminationErrorFunction();
1026             break;
1027         default:
1028             nativeConstructor = env->GetErrorFunction();
1029             break;
1030     }
1031     JSHandle<JSFunction> nativeFunc = JSHandle<JSFunction>::Cast(nativeConstructor);
1032     JSHandle<JSTaggedValue> nativePrototype(thread_, nativeFunc->GetFunctionPrototype());
1033     JSHandle<JSTaggedValue> undefined = thread_->GlobalConstants()->GetHandledUndefined();
1034     EcmaRuntimeCallInfo *info =
1035         EcmaInterpreter::NewRuntimeCallInfo(thread_, nativeConstructor, nativePrototype, undefined, 1, needCheckStack);
1036     RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread_);
1037     info->SetCallArg(message.GetTaggedValue());
1038     Method *method = JSHandle<ECMAObject>::Cast(nativeConstructor)->GetCallTarget();
1039     JSTaggedValue obj = reinterpret_cast<EcmaEntrypoint>(const_cast<void *>(method->GetNativePointer()))(info);
1040     RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread_);
1041     JSHandle<JSObject> handleNativeInstanceObj(thread_, obj);
1042     auto sp = const_cast<JSTaggedType *>(thread_->GetCurrentSPFrame());
1043     ASSERT(FrameHandler::GetFrameType(sp) == FrameType::INTERPRETER_ENTRY_FRAME);
1044     auto prevEntry = InterpretedEntryFrame::GetFrameFromSp(sp)->GetPrevFrameFp();
1045     thread_->SetCurrentSPFrame(prevEntry);
1046     return handleNativeInstanceObj;
1047 }
1048 
NewJSAggregateError()1049 JSHandle<JSObject> ObjectFactory::NewJSAggregateError()
1050 {
1051     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
1052     JSHandle<JSFunction> constructor(env->GetAggregateErrorFunction());
1053     return NewJSObjectByConstructor(constructor);
1054 }
1055 
NewJSObjectByConstructor(JSHandle<GlobalEnv> env,const JSHandle<JSFunction> & constructor,uint32_t inlinedProps)1056 JSHandle<JSObject> ObjectFactory::NewJSObjectByConstructor(JSHandle<GlobalEnv> env,
1057     const JSHandle<JSFunction> &constructor, uint32_t inlinedProps)
1058 {
1059     if (!constructor->HasFunctionPrototype() ||
1060         (constructor->GetProtoOrHClass().IsHeapObject() && constructor->GetFunctionPrototype().IsECMAObject())) {
1061         JSHandle<JSHClass> jshclass;
1062         if (LIKELY(inlinedProps == JSHClass::DEFAULT_CAPACITY_OF_IN_OBJECTS)) {
1063             jshclass = JSHandle<JSHClass>(thread_, JSFunction::GetOrCreateInitialJSHClass(thread_, constructor));
1064         } else {
1065             jshclass = NewEcmaHClass(JSObject::SIZE, inlinedProps, JSType::JS_OBJECT,
1066                                      env->GetObjectFunctionPrototype());
1067         }
1068         JSHandle<JSObject> obj;
1069         if (jshclass->IsJSSharedObject()) {
1070             obj = NewSharedOldSpaceJSObject(jshclass);
1071             if (jshclass->IsDictionaryMode()) {
1072                 auto fieldLayout = jshclass->GetLayout();
1073                 ASSERT(fieldLayout.IsDictionary());
1074                 auto dict = JSHandle<TaggedArray>(thread_, fieldLayout);
1075                 auto properties = NewAndCopySNameDictionary(dict, dict->GetLength());
1076                 obj->SetProperties(thread_, properties);
1077             }
1078         } else {
1079             obj = NewJSObjectWithInit(jshclass);
1080         }
1081         return obj;
1082     }
1083     JSHandle<JSObject> result =
1084         NewJSObjectByConstructor(JSHandle<JSFunction>(env->GetObjectFunction()), JSHandle<JSTaggedValue>(constructor));
1085     if (thread_->HasPendingException()) {
1086         LOG_FULL(FATAL) << "NewJSObjectByConstructor should not throw Exception! ";
1087     }
1088     return result;
1089 }
1090 
NewJSObjectByConstructor(const JSHandle<JSFunction> & constructor,uint32_t inlinedProps)1091 JSHandle<JSObject> ObjectFactory::NewJSObjectByConstructor(const JSHandle<JSFunction> &constructor,
1092                                                            uint32_t inlinedProps)
1093 {
1094     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
1095     if (!constructor->HasFunctionPrototype() ||
1096         (constructor->GetProtoOrHClass().IsHeapObject() && constructor->GetFunctionPrototype().IsECMAObject())) {
1097         JSHandle<JSHClass> jshclass;
1098         if (LIKELY(inlinedProps == JSHClass::DEFAULT_CAPACITY_OF_IN_OBJECTS)) {
1099             jshclass = JSHandle<JSHClass>(thread_, JSFunction::GetOrCreateInitialJSHClass(thread_, constructor));
1100         } else {
1101             jshclass = NewEcmaHClass(JSObject::SIZE, inlinedProps, JSType::JS_OBJECT,
1102                                      env->GetObjectFunctionPrototype());
1103         }
1104         JSHandle<JSObject> obj;
1105         if (jshclass->IsJSShared()) {
1106             obj = NewSharedOldSpaceJSObject(jshclass);
1107             if (jshclass->IsDictionaryMode()) {
1108                 auto fieldLayout = jshclass->GetLayout();
1109                 ASSERT(fieldLayout.IsDictionary());
1110                 auto dict = JSHandle<TaggedArray>(thread_, fieldLayout);
1111                 auto properties = NewAndCopySNameDictionary(dict, dict->GetLength());
1112                 obj->SetProperties(thread_, properties);
1113             }
1114             InitializeJSObject(obj, jshclass);
1115         } else {
1116             obj = NewJSObjectWithInit(jshclass);
1117         }
1118         return obj;
1119     }
1120     JSHandle<JSObject> result =
1121         NewJSObjectByConstructor(JSHandle<JSFunction>(env->GetObjectFunction()), JSHandle<JSTaggedValue>(constructor));
1122     if (thread_->HasPendingException()) {
1123         LOG_FULL(FATAL) << "NewJSObjectByConstructor should not throw Exception! ";
1124     }
1125     return result;
1126 }
1127 
NewJSObjectByConstructor(const JSHandle<JSFunction> & constructor,const JSHandle<JSTaggedValue> & newTarget)1128 JSHandle<JSObject> ObjectFactory::NewJSObjectByConstructor(const JSHandle<JSFunction> &constructor,
1129                                                            const JSHandle<JSTaggedValue> &newTarget)
1130 {
1131     if (constructor->IsJSShared() && !newTarget->IsJSShared()) {
1132         THROW_TYPE_ERROR_AND_RETURN(thread_, "shared ctor cannot assign unshared newTarget",
1133                                     JSHandle<JSObject>(thread_, JSTaggedValue::Undefined()));
1134     }
1135     JSHandle<JSHClass> jshclass;
1136     if (!constructor->HasFunctionPrototype() ||
1137         (constructor->GetProtoOrHClass().IsHeapObject() && constructor->GetFunctionPrototype().IsECMAObject())) {
1138         jshclass = JSFunction::GetInstanceJSHClass(thread_, constructor, newTarget);
1139     } else {
1140         JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
1141         jshclass = JSFunction::GetInstanceJSHClass(thread_, JSHandle<JSFunction>(env->GetObjectFunction()), newTarget);
1142     }
1143     // Check this exception elsewhere
1144     RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSObject, thread_);
1145     JSHandle<JSObject> obj;
1146     if (jshclass->IsJSShared()) {
1147         obj = NewSharedOldSpaceJSObject(jshclass);
1148         if (jshclass->IsDictionaryMode()) {
1149             auto fieldLayout = jshclass->GetLayout();
1150             ASSERT(fieldLayout.IsDictionary());
1151             auto dict = JSHandle<TaggedArray>(thread_, fieldLayout);
1152             auto properties = NewAndCopySNameDictionary(dict, dict->GetLength());
1153             obj->SetProperties(thread_, properties);
1154         }
1155         InitializeJSObject(obj, jshclass);
1156     } else {
1157         obj = NewJSObjectWithInit(jshclass);
1158     }
1159     return obj;
1160 }
1161 
NewJSObjectWithInit(const JSHandle<JSHClass> & jshclass)1162 JSHandle<JSObject> ObjectFactory::NewJSObjectWithInit(const JSHandle<JSHClass> &jshclass)
1163 {
1164     JSHandle<JSObject> obj = NewJSObject(jshclass);
1165     InitializeJSObject(obj, jshclass);
1166     return obj;
1167 }
1168 
InitializeJSObject(const JSHandle<JSObject> & obj,const JSHandle<JSHClass> & jshclass)1169 void ObjectFactory::InitializeJSObject(const JSHandle<JSObject> &obj, const JSHandle<JSHClass> &jshclass)
1170 {
1171     JSType type = jshclass->GetObjectType();
1172     switch (type) {
1173         case JSType::JS_OBJECT:
1174         case JSType::JS_ERROR:
1175         case JSType::JS_EVAL_ERROR:
1176         case JSType::JS_RANGE_ERROR:
1177         case JSType::JS_REFERENCE_ERROR:
1178         case JSType::JS_TYPE_ERROR:
1179         case JSType::JS_AGGREGATE_ERROR:
1180         case JSType::JS_URI_ERROR:
1181         case JSType::JS_SYNTAX_ERROR:
1182         case JSType::JS_OOM_ERROR:
1183         case JSType::JS_TERMINATION_ERROR:
1184         case JSType::JS_ASYNCITERATOR:
1185         case JSType::JS_SHARED_OBJECT:
1186         case JSType::JS_SHARED_FUNCTION:
1187         case JSType::JS_ITERATOR: {
1188             break;
1189         }
1190 #ifdef ARK_SUPPORT_INTL
1191         case JSType::JS_INTL: {
1192             JSIntl::Cast(*obj)->SetFallbackSymbol(thread_, JSTaggedValue::Undefined());
1193             JSHandle<JSSymbol> jsSymbol = NewPublicSymbolWithChar("IntlLegacyConstructedSymbol");
1194             JSIntl::Cast(*obj)->SetFallbackSymbol(thread_, jsSymbol);
1195             break;
1196         }
1197         case JSType::JS_LOCALE: {
1198             JSLocale::Cast(*obj)->SetIcuField(thread_, JSTaggedValue::Undefined());
1199             break;
1200         }
1201         case JSType::JS_DATE_TIME_FORMAT: {
1202             JSDateTimeFormat::Cast(*obj)->SetLocale(thread_, JSTaggedValue::Undefined());
1203             JSDateTimeFormat::Cast(*obj)->SetCalendar(thread_, JSTaggedValue::Undefined());
1204             JSDateTimeFormat::Cast(*obj)->SetNumberingSystem(thread_, JSTaggedValue::Undefined());
1205             JSDateTimeFormat::Cast(*obj)->SetTimeZone(thread_, JSTaggedValue::Undefined());
1206             JSDateTimeFormat::Cast(*obj)->SetLocaleIcu(thread_, JSTaggedValue::Undefined());
1207             JSDateTimeFormat::Cast(*obj)->SetSimpleDateTimeFormatIcu(thread_, JSTaggedValue::Undefined());
1208             JSDateTimeFormat::Cast(*obj)->SetIso8601(thread_, JSTaggedValue::Undefined());
1209             JSDateTimeFormat::Cast(*obj)->SetBoundFormat(thread_, JSTaggedValue::Undefined());
1210             JSDateTimeFormat::Cast(*obj)->SetHourCycle(HourCycleOption::EXCEPTION);
1211             JSDateTimeFormat::Cast(*obj)->SetDateStyle(DateTimeStyleOption::EXCEPTION);
1212             JSDateTimeFormat::Cast(*obj)->SetTimeStyle(DateTimeStyleOption::EXCEPTION);
1213             break;
1214         }
1215         case JSType::JS_NUMBER_FORMAT: {
1216             JSNumberFormat::Cast(*obj)->SetLocale(thread_, JSTaggedValue::Undefined());
1217             JSNumberFormat::Cast(*obj)->SetNumberingSystem(thread_, JSTaggedValue::Undefined());
1218             JSNumberFormat::Cast(*obj)->SetCurrency(thread_, JSTaggedValue::Undefined());
1219             JSNumberFormat::Cast(*obj)->SetUnit(thread_, JSTaggedValue::Undefined());
1220             JSNumberFormat::Cast(*obj)->SetMinimumIntegerDigits(thread_, JSTaggedValue::Undefined());
1221             JSNumberFormat::Cast(*obj)->SetMinimumFractionDigits(thread_, JSTaggedValue::Undefined());
1222             JSNumberFormat::Cast(*obj)->SetMaximumFractionDigits(thread_, JSTaggedValue::Undefined());
1223             JSNumberFormat::Cast(*obj)->SetMinimumSignificantDigits(thread_, JSTaggedValue::Undefined());
1224             JSNumberFormat::Cast(*obj)->SetMaximumSignificantDigits(thread_, JSTaggedValue::Undefined());
1225             JSNumberFormat::Cast(*obj)->SetUseGrouping(thread_, JSTaggedValue::Undefined());
1226             JSNumberFormat::Cast(*obj)->SetBoundFormat(thread_, JSTaggedValue::Undefined());
1227             JSNumberFormat::Cast(*obj)->SetIcuField(thread_, JSTaggedValue::Undefined());
1228             JSNumberFormat::Cast(*obj)->SetStyle(StyleOption::EXCEPTION);
1229             JSNumberFormat::Cast(*obj)->SetCurrencySign(CurrencySignOption::EXCEPTION);
1230             JSNumberFormat::Cast(*obj)->SetCurrencyDisplay(CurrencyDisplayOption::EXCEPTION);
1231             JSNumberFormat::Cast(*obj)->SetUnitDisplay(UnitDisplayOption::EXCEPTION);
1232             JSNumberFormat::Cast(*obj)->SetSignDisplay(SignDisplayOption::EXCEPTION);
1233             JSNumberFormat::Cast(*obj)->SetCompactDisplay(CompactDisplayOption::EXCEPTION);
1234             JSNumberFormat::Cast(*obj)->SetNotation(NotationOption::EXCEPTION);
1235             JSNumberFormat::Cast(*obj)->SetRoundingType(RoundingType::EXCEPTION);
1236             break;
1237         }
1238         case JSType::JS_RELATIVE_TIME_FORMAT: {
1239             JSRelativeTimeFormat::Cast(*obj)->SetLocale(thread_, JSTaggedValue::Undefined());
1240             JSRelativeTimeFormat::Cast(*obj)->SetNumberingSystem(thread_, JSTaggedValue::Undefined());
1241             JSRelativeTimeFormat::Cast(*obj)->SetIcuField(thread_, JSTaggedValue::Undefined());
1242             JSRelativeTimeFormat::Cast(*obj)->SetStyle(RelativeStyleOption::EXCEPTION);
1243             JSRelativeTimeFormat::Cast(*obj)->SetNumeric(NumericOption::EXCEPTION);
1244             break;
1245         }
1246         case JSType::JS_COLLATOR: {
1247             JSCollator::Cast(*obj)->SetIcuField(thread_, JSTaggedValue::Undefined());
1248             JSCollator::Cast(*obj)->SetLocale(thread_, JSTaggedValue::Undefined());
1249             JSCollator::Cast(*obj)->SetCollation(thread_, JSTaggedValue::Undefined());
1250             JSCollator::Cast(*obj)->SetBoundCompare(thread_, JSTaggedValue::Undefined());
1251             JSCollator::Cast(*obj)->SetUsage(UsageOption::EXCEPTION);
1252             JSCollator::Cast(*obj)->SetCaseFirst(CaseFirstOption::EXCEPTION);
1253             JSCollator::Cast(*obj)->SetSensitivity(SensitivityOption::EXCEPTION);
1254             JSCollator::Cast(*obj)->SetIgnorePunctuation(false);
1255             JSCollator::Cast(*obj)->SetNumeric(false);
1256             break;
1257         }
1258         case JSType::JS_PLURAL_RULES: {
1259             JSPluralRules::Cast(*obj)->SetLocale(thread_, JSTaggedValue::Undefined());
1260             JSPluralRules::Cast(*obj)->SetMinimumIntegerDigits(thread_, JSTaggedValue::Undefined());
1261             JSPluralRules::Cast(*obj)->SetMinimumFractionDigits(thread_, JSTaggedValue::Undefined());
1262             JSPluralRules::Cast(*obj)->SetMaximumFractionDigits(thread_, JSTaggedValue::Undefined());
1263             JSPluralRules::Cast(*obj)->SetMinimumSignificantDigits(thread_, JSTaggedValue::Undefined());
1264             JSPluralRules::Cast(*obj)->SetMaximumSignificantDigits(thread_, JSTaggedValue::Undefined());
1265             JSPluralRules::Cast(*obj)->SetIcuPR(thread_, JSTaggedValue::Undefined());
1266             JSPluralRules::Cast(*obj)->SetIcuNF(thread_, JSTaggedValue::Undefined());
1267             JSPluralRules::Cast(*obj)->SetRoundingType(RoundingType::EXCEPTION);
1268             JSPluralRules::Cast(*obj)->SetType(TypeOption::EXCEPTION);
1269             break;
1270         }
1271         case JSType::JS_DISPLAYNAMES: {
1272             JSDisplayNames::Cast(*obj)->SetLocale(thread_, JSTaggedValue::Undefined());
1273             JSDisplayNames::Cast(*obj)->SetType(TypednsOption::EXCEPTION);
1274             JSDisplayNames::Cast(*obj)->SetStyle(StyOption::EXCEPTION);
1275             JSDisplayNames::Cast(*obj)->SetFallback(FallbackOption::EXCEPTION);
1276             JSDisplayNames::Cast(*obj)->SetIcuLDN(thread_, JSTaggedValue::Undefined());
1277             break;
1278         }
1279         case JSType::JS_SEGMENTER: {
1280             JSSegmenter::Cast(*obj)->SetLocale(thread_, JSTaggedValue::Undefined());
1281             JSSegmenter::Cast(*obj)->SetGranularity(GranularityOption::EXCEPTION);
1282             JSSegmenter::Cast(*obj)->SetIcuField(thread_, JSTaggedValue::Undefined());
1283             break;
1284         }
1285         case JSType::JS_SEGMENTS: {
1286             JSSegments::Cast(*obj)->SetIcuField(thread_, JSTaggedValue::Undefined());
1287             JSSegments::Cast(*obj)->SetSegmentsString(thread_, JSTaggedValue::Undefined());
1288             JSSegments::Cast(*obj)->SetUnicodeString(thread_, JSTaggedValue::Undefined());
1289             JSSegments::Cast(*obj)->SetGranularity(GranularityOption::EXCEPTION);
1290             break;
1291         }
1292         case JSType::JS_SEGMENT_ITERATOR: {
1293             JSSegmentIterator::Cast(*obj)->SetIcuField(thread_, JSTaggedValue::Undefined());
1294             JSSegmentIterator::Cast(*obj)->SetIteratedString(thread_, JSTaggedValue::Undefined());
1295             JSSegmentIterator::Cast(*obj)->SetUnicodeString(thread_, JSTaggedValue::Undefined());
1296             JSSegmentIterator::Cast(*obj)->SetGranularity(GranularityOption::EXCEPTION);
1297             break;
1298         }
1299         case JSType::JS_LIST_FORMAT: {
1300             JSListFormat::Cast(*obj)->SetLocale(thread_, JSTaggedValue::Undefined());
1301             JSListFormat::Cast(*obj)->SetType(ListTypeOption::EXCEPTION);
1302             JSListFormat::Cast(*obj)->SetStyle(ListStyleOption::EXCEPTION);
1303             JSListFormat::Cast(*obj)->SetIcuLF(thread_, JSTaggedValue::Undefined());
1304             break;
1305         }
1306 #else
1307         case JSType::JS_INTL:
1308         case JSType::JS_LOCALE:
1309         case JSType::JS_DATE_TIME_FORMAT:
1310         case JSType::JS_NUMBER_FORMAT:
1311         case JSType::JS_RELATIVE_TIME_FORMAT:
1312         case JSType::JS_COLLATOR:
1313         case JSType::JS_PLURAL_RULES:
1314         case JSType::JS_DISPLAYNAMES:
1315         case JSType::JS_SEGMENTER:
1316         case JSType::JS_SEGMENTS:
1317         case JSType::JS_SEGMENT_ITERATOR:
1318         case JSType::JS_LIST_FORMAT: {
1319             break;
1320         }
1321 #endif
1322         case JSType::JS_ARRAY: {
1323             JSArray::Cast(*obj)->SetLength(0);
1324             JSArray::Cast(*obj)->SetTrackInfo(thread_, JSTaggedValue::Undefined());
1325             ASSERT(!obj->GetJSHClass()->IsDictionaryMode());
1326             auto accessor = thread_->GlobalConstants()->GetArrayLengthAccessor();
1327             JSArray::Cast(*obj)->SetPropertyInlinedProps(thread_, JSArray::LENGTH_INLINE_PROPERTY_INDEX, accessor);
1328             break;
1329         }
1330         case JSType::JS_SHARED_ARRAY: {
1331             JSSharedArray::Cast(*obj)->SetLength(0);
1332             JSSharedArray::Cast(*obj)->SetTrackInfo(thread_, JSTaggedValue::Undefined());
1333             ASSERT(!obj->GetJSHClass()->IsDictionaryMode());
1334             JSSharedArray::Cast(*obj)->SetModRecord(0);
1335             auto accessor = thread_->GlobalConstants()->GetSharedArrayLengthAccessor();
1336             JSSharedArray::Cast(*obj)->SetPropertyInlinedProps(thread_, JSArray::LENGTH_INLINE_PROPERTY_INDEX,
1337                                                                accessor);
1338             break;
1339         }
1340         case JSType::JS_DATE:
1341             JSDate::Cast(*obj)->SetTimeValue(thread_, JSTaggedValue(0.0));
1342             JSDate::Cast(*obj)->SetLocalOffset(thread_, JSTaggedValue(JSDate::MAX_DOUBLE));
1343             break;
1344         case JSType::JS_TYPED_ARRAY:
1345         case JSType::JS_INT8_ARRAY:
1346         case JSType::JS_UINT8_ARRAY:
1347         case JSType::JS_UINT8_CLAMPED_ARRAY:
1348         case JSType::JS_INT16_ARRAY:
1349         case JSType::JS_UINT16_ARRAY:
1350         case JSType::JS_INT32_ARRAY:
1351         case JSType::JS_UINT32_ARRAY:
1352         case JSType::JS_FLOAT32_ARRAY:
1353         case JSType::JS_FLOAT64_ARRAY:
1354         case JSType::JS_BIGINT64_ARRAY:
1355         case JSType::JS_BIGUINT64_ARRAY:
1356             JSTypedArray::Cast(*obj)->SetViewedArrayBufferOrByteArray(thread_, JSTaggedValue::Undefined());
1357             JSTypedArray::Cast(*obj)->SetTypedArrayName(thread_, JSTaggedValue::Undefined());
1358             JSTypedArray::Cast(*obj)->SetByteLength(0);
1359             JSTypedArray::Cast(*obj)->SetByteOffset(0);
1360             JSTypedArray::Cast(*obj)->SetArrayLength(0);
1361             JSTypedArray::Cast(*obj)->SetContentType(ContentType::None);
1362             break;
1363         case JSType::JS_SHARED_TYPED_ARRAY:
1364         case JSType::JS_SHARED_INT8_ARRAY:
1365         case JSType::JS_SHARED_UINT8_ARRAY:
1366         case JSType::JS_SHARED_UINT8_CLAMPED_ARRAY:
1367         case JSType::JS_SHARED_INT16_ARRAY:
1368         case JSType::JS_SHARED_UINT16_ARRAY:
1369         case JSType::JS_SHARED_INT32_ARRAY:
1370         case JSType::JS_SHARED_UINT32_ARRAY:
1371         case JSType::JS_SHARED_FLOAT32_ARRAY:
1372         case JSType::JS_SHARED_FLOAT64_ARRAY:
1373         case JSType::JS_SHARED_BIGINT64_ARRAY:
1374         case JSType::JS_SHARED_BIGUINT64_ARRAY:
1375             JSSharedTypedArray::Cast(*obj)->SetViewedArrayBufferOrByteArray(thread_, JSTaggedValue::Undefined());
1376             JSSharedTypedArray::Cast(*obj)->SetTypedArrayName(thread_, JSTaggedValue::Undefined());
1377             JSSharedTypedArray::Cast(*obj)->SetByteLength(0);
1378             JSSharedTypedArray::Cast(*obj)->SetByteOffset(0);
1379             JSSharedTypedArray::Cast(*obj)->SetArrayLength(0);
1380             JSSharedTypedArray::Cast(*obj)->SetContentType(ContentType::None);
1381             JSSharedTypedArray::Cast(*obj)->SetModRecord(0);
1382             break;
1383         case JSType::JS_REG_EXP:
1384             JSRegExp::Cast(*obj)->SetByteCodeBuffer(thread_, JSTaggedValue::Undefined());
1385             JSRegExp::Cast(*obj)->SetOriginalSource(thread_, JSTaggedValue::Undefined());
1386             JSRegExp::Cast(*obj)->SetOriginalFlags(thread_, JSTaggedValue(0));
1387             JSRegExp::Cast(*obj)->SetGroupName(thread_, JSTaggedValue::Undefined());
1388             JSRegExp::Cast(*obj)->SetLength(0);
1389             break;
1390         case JSType::JS_PRIMITIVE_REF:
1391             JSPrimitiveRef::Cast(*obj)->SetValue(thread_, JSTaggedValue::Undefined());
1392             break;
1393         case JSType::JS_SET:
1394             JSSet::Cast(*obj)->SetLinkedSet(thread_, JSTaggedValue::Undefined());
1395             break;
1396         case JSType::JS_SHARED_SET:
1397             JSSharedSet::Cast(*obj)->SetLinkedSet(thread_, JSTaggedValue::Undefined());
1398             JSSharedSet::Cast(*obj)->SetModRecord(0);
1399             break;
1400         case JSType::JS_MAP:
1401             JSMap::Cast(*obj)->SetLinkedMap(thread_, JSTaggedValue::Undefined());
1402             break;
1403         case JSType::JS_SHARED_MAP:
1404             JSSharedMap::Cast(*obj)->SetLinkedMap(thread_, JSTaggedValue::Undefined());
1405             JSSharedMap::Cast(*obj)->SetModRecord(0);
1406             break;
1407         case JSType::JS_WEAK_MAP:
1408             JSWeakMap::Cast(*obj)->SetLinkedMap(thread_, JSTaggedValue::Undefined());
1409             break;
1410         case JSType::JS_WEAK_SET:
1411             JSWeakSet::Cast(*obj)->SetLinkedSet(thread_, JSTaggedValue::Undefined());
1412             break;
1413         case JSType::JS_WEAK_REF:
1414             JSWeakRef::Cast(*obj)->SetWeakObject(thread_, JSTaggedValue::Undefined());
1415             break;
1416         case JSType::JS_FINALIZATION_REGISTRY:
1417             JSFinalizationRegistry::Cast(*obj)->SetCleanupCallback(thread_, JSTaggedValue::Undefined());
1418             JSFinalizationRegistry::Cast(*obj)->SetNoUnregister(thread_, JSTaggedValue::Undefined());
1419             JSFinalizationRegistry::Cast(*obj)->SetMaybeUnregister(thread_, JSTaggedValue::Undefined());
1420             JSFinalizationRegistry::Cast(*obj)->SetNext(thread_, JSTaggedValue::Null());
1421             JSFinalizationRegistry::Cast(*obj)->SetPrev(thread_, JSTaggedValue::Null());
1422             break;
1423         case JSType::JS_GENERATOR_OBJECT:
1424             JSGeneratorObject::Cast(*obj)->SetGeneratorContext(thread_, JSTaggedValue::Undefined());
1425             JSGeneratorObject::Cast(*obj)->SetResumeResult(thread_, JSTaggedValue::Undefined());
1426             JSGeneratorObject::Cast(*obj)->SetGeneratorState(JSGeneratorState::UNDEFINED);
1427             JSGeneratorObject::Cast(*obj)->SetResumeMode(GeneratorResumeMode::UNDEFINED);
1428             break;
1429         case JSType::JS_ASYNC_GENERATOR_OBJECT:
1430             JSAsyncGeneratorObject::Cast(*obj)->SetGeneratorContext(thread_, JSTaggedValue::Undefined());
1431             JSAsyncGeneratorObject::Cast(*obj)->SetAsyncGeneratorQueue(thread_, GetEmptyTaggedQueue().GetTaggedValue());
1432             JSAsyncGeneratorObject::Cast(*obj)->SetGeneratorBrand(thread_, JSTaggedValue::Undefined());
1433             JSAsyncGeneratorObject::Cast(*obj)->SetResumeResult(thread_, JSTaggedValue::Undefined());
1434             JSAsyncGeneratorObject::Cast(*obj)->SetAsyncGeneratorState(JSAsyncGeneratorState::UNDEFINED);
1435             JSAsyncGeneratorObject::Cast(*obj)->SetResumeMode(AsyncGeneratorResumeMode::UNDEFINED);
1436             break;
1437         case JSType::JS_STRING_ITERATOR:
1438             JSStringIterator::Cast(*obj)->SetStringIteratorNextIndex(0);
1439             JSStringIterator::Cast(*obj)->SetIteratedString(thread_, JSTaggedValue::Undefined());
1440             break;
1441         case JSType::JS_ASYNC_FROM_SYNC_ITERATOR:
1442             JSAsyncFromSyncIterator::Cast(*obj)->SetSyncIteratorRecord(thread_, JSTaggedValue::Undefined());
1443             break;
1444         case JSType::JS_ASYNC_FROM_SYNC_ITER_UNWARP_FUNCTION:
1445             JSAsyncFromSyncIterUnwarpFunction::Cast(*obj)->SetDone(thread_, JSTaggedValue::Undefined());
1446             break;
1447         case JSType::JS_ARRAY_BUFFER:
1448             JSArrayBuffer::Cast(*obj)->SetArrayBufferData(thread_, JSTaggedValue::Undefined());
1449             JSArrayBuffer::Cast(*obj)->SetArrayBufferByteLength(0);
1450             JSArrayBuffer::Cast(*obj)->ClearBitField();
1451             break;
1452         case JSType::JS_SHARED_ARRAY_BUFFER:
1453             JSArrayBuffer::Cast(*obj)->SetArrayBufferData(thread_, JSTaggedValue::Undefined());
1454             JSArrayBuffer::Cast(*obj)->SetArrayBufferByteLength(0);
1455             JSArrayBuffer::Cast(*obj)->SetShared(true);
1456             break;
1457         case JSType::JS_SENDABLE_ARRAY_BUFFER:
1458             JSSendableArrayBuffer::Cast(*obj)->SetArrayBufferData(thread_, JSTaggedValue::Undefined());
1459             JSSendableArrayBuffer::Cast(*obj)->SetArrayBufferByteLength(0);
1460             break;
1461         case JSType::JS_PROMISE:
1462             JSPromise::Cast(*obj)->SetPromiseState(PromiseState::PENDING);
1463             JSPromise::Cast(*obj)->SetPromiseResult(thread_, JSTaggedValue::Undefined());
1464             JSPromise::Cast(*obj)->SetPromiseRejectReactions(thread_, GetEmptyTaggedQueue().GetTaggedValue());
1465             JSPromise::Cast(*obj)->SetPromiseFulfillReactions(thread_, GetEmptyTaggedQueue().GetTaggedValue());
1466 
1467             JSPromise::Cast(*obj)->SetPromiseIsHandled(false);
1468             break;
1469         case JSType::JS_DATA_VIEW:
1470             JSDataView::Cast(*obj)->SetDataView(thread_, JSTaggedValue(false));
1471             JSDataView::Cast(*obj)->SetViewedArrayBuffer(thread_, JSTaggedValue::Undefined());
1472             JSDataView::Cast(*obj)->SetByteLength(0);
1473             JSDataView::Cast(*obj)->SetByteOffset(0);
1474             break;
1475         // non ECMA standard jsapi container
1476         case JSType::JS_API_ARRAY_LIST: {
1477             JSAPIArrayList::Cast(*obj)->SetLength(thread_, JSTaggedValue(0));
1478             break;
1479         }
1480         case JSType::JS_API_HASH_MAP: {
1481             JSAPIHashMap::Cast(*obj)->SetSize(0);
1482             JSAPIHashMap::Cast(*obj)->SetTable(thread_, JSTaggedValue::Undefined());
1483             break;
1484         }
1485         case JSType::JS_API_HASH_SET: {
1486             JSAPIHashSet::Cast(*obj)->SetSize(0);
1487             JSAPIHashSet::Cast(*obj)->SetTable(thread_, JSTaggedValue::Undefined());
1488             break;
1489         }
1490         case JSType::JS_API_TREE_MAP: {
1491             JSAPITreeMap::Cast(*obj)->SetTreeMap(thread_, JSTaggedValue::Undefined());
1492             break;
1493         }
1494         case JSType::JS_API_TREE_SET: {
1495             JSAPITreeSet::Cast(*obj)->SetTreeSet(thread_, JSTaggedValue::Undefined());
1496             break;
1497         }
1498         case JSType::JS_API_QUEUE: {
1499             JSAPIQueue::Cast(*obj)->SetLength(thread_, JSTaggedValue(0));
1500             JSAPIQueue::Cast(*obj)->SetFront(0);
1501             JSAPIQueue::Cast(*obj)->SetTail(0);
1502             break;
1503         }
1504         case JSType::JS_API_PLAIN_ARRAY: {
1505             JSAPIPlainArray::Cast(*obj)->SetLength(0);
1506             JSAPIPlainArray::Cast(*obj)->SetValues(thread_, JSTaggedValue(0));
1507             JSAPIPlainArray::Cast(*obj)->SetKeys(thread_, JSTaggedValue(0));
1508             break;
1509         }
1510         case JSType::JS_API_STACK: {
1511             JSAPIStack::Cast(*obj)->SetTop(0);
1512             break;
1513         }
1514         case JSType::JS_API_DEQUE: {
1515             JSAPIDeque::Cast(*obj)->SetFirst(0);
1516             JSAPIDeque::Cast(*obj)->SetLast(0);
1517             break;
1518         }
1519         case JSType::JS_API_LIGHT_WEIGHT_MAP: {
1520             JSAPILightWeightMap::Cast(*obj)->SetLength(0);
1521             JSAPILightWeightMap::Cast(*obj)->SetHashes(thread_, JSTaggedValue::Undefined());
1522             JSAPILightWeightMap::Cast(*obj)->SetKeys(thread_, JSTaggedValue::Undefined());
1523             JSAPILightWeightMap::Cast(*obj)->SetValues(thread_, JSTaggedValue::Undefined());
1524             break;
1525         }
1526         case JSType::JS_API_LIGHT_WEIGHT_SET: {
1527             JSAPILightWeightSet::Cast(*obj)->SetLength(0);
1528             JSAPILightWeightSet::Cast(*obj)->SetHashes(thread_, JSTaggedValue::Undefined());
1529             JSAPILightWeightSet::Cast(*obj)->SetValues(thread_, JSTaggedValue::Undefined());
1530             break;
1531         }
1532         case JSType::JS_API_VECTOR: {
1533             JSAPIVector::Cast(*obj)->SetLength(0);
1534             break;
1535         }
1536         case JSType::JS_API_BITVECTOR: {
1537             JSAPIBitVector::Cast(*obj)->SetNativePointer(thread_, JSTaggedValue::Undefined());
1538             JSAPIBitVector::Cast(*obj)->SetLength(0);
1539             JSAPIBitVector::Cast(*obj)->SetModRecord(0);
1540             break;
1541         }
1542         case JSType::JS_API_LIST: {
1543             JSAPIList::Cast(*obj)->SetSingleList(thread_, JSTaggedValue::Undefined());
1544             JSAPIList::Cast(*obj)->SetBitField(0UL);
1545             break;
1546         }
1547         case JSType::JS_API_LINKED_LIST: {
1548             JSAPILinkedList::Cast(*obj)->SetDoubleList(thread_, JSTaggedValue::Undefined());
1549             break;
1550         }
1551         case JSType::JS_ASYNC_FUNC_OBJECT:
1552             JSAsyncFuncObject::Cast(*obj)->SetGeneratorContext(thread_, JSTaggedValue::Undefined());
1553             JSAsyncFuncObject::Cast(*obj)->SetResumeResult(thread_, JSTaggedValue::Undefined());
1554             JSAsyncFuncObject::Cast(*obj)->SetPromise(thread_, JSTaggedValue::Undefined());
1555             break;
1556         case JSType::JS_FUNCTION:
1557         case JSType::JS_GENERATOR_FUNCTION:
1558             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1559             break;
1560         case JSType::JS_ASYNC_GENERATOR_FUNCTION:
1561             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1562             break;
1563         case JSType::JS_PROXY_REVOC_FUNCTION:
1564             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1565             JSProxyRevocFunction::Cast(*obj)->SetRevocableProxy(thread_, JSTaggedValue::Undefined());
1566             break;
1567         case JSType::JS_PROMISE_REACTIONS_FUNCTION:
1568             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1569             JSPromiseReactionsFunction::Cast(*obj)->SetPromise(thread_, JSTaggedValue::Undefined());
1570             JSPromiseReactionsFunction::Cast(*obj)->SetAlreadyResolved(thread_, JSTaggedValue::Undefined());
1571             break;
1572         case JSType::JS_PROMISE_EXECUTOR_FUNCTION:
1573             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1574             JSPromiseExecutorFunction::Cast(*obj)->SetCapability(thread_, JSTaggedValue::Undefined());
1575             break;
1576         case JSType::JS_ASYNC_MODULE_FULFILLED_FUNCTION:
1577             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1578             JSAsyncModuleFulfilledFunction::Cast(*obj)->SetModule(thread_, JSTaggedValue::Undefined());
1579             break;
1580         case JSType::JS_ASYNC_MODULE_REJECTED_FUNCTION:
1581             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1582             JSAsyncModuleRejectedFunction::Cast(*obj)->SetModule(thread_, JSTaggedValue::Undefined());
1583             break;
1584         case JSType::JS_ASYNC_GENERATOR_RESUME_NEXT_RETURN_PROCESSOR_RST_FTN:
1585             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1586             JSAsyncGeneratorResNextRetProRstFtn::Cast(*obj)->SetAsyncGeneratorObject(thread_,
1587                                                                                      JSTaggedValue::Undefined());
1588             break;
1589         case JSType::JS_PROMISE_ALL_RESOLVE_ELEMENT_FUNCTION:
1590             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1591             JSPromiseAllResolveElementFunction::Cast(*obj)->SetIndex(thread_, JSTaggedValue::Undefined());
1592             JSPromiseAllResolveElementFunction::Cast(*obj)->SetValues(thread_, JSTaggedValue::Undefined());
1593             JSPromiseAllResolveElementFunction::Cast(*obj)->SetCapabilities(thread_, JSTaggedValue::Undefined());
1594             JSPromiseAllResolveElementFunction::Cast(*obj)->SetRemainingElements(thread_, JSTaggedValue::Undefined());
1595             JSPromiseAllResolveElementFunction::Cast(*obj)->SetAlreadyCalled(thread_, JSTaggedValue::Undefined());
1596             break;
1597         case JSType::JS_PROMISE_ANY_REJECT_ELEMENT_FUNCTION:
1598             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1599             JSPromiseAnyRejectElementFunction::Cast(*obj)->SetIndex(0);
1600             JSPromiseAnyRejectElementFunction::Cast(*obj)->SetErrors(thread_, JSTaggedValue::Undefined());
1601             JSPromiseAnyRejectElementFunction::Cast(*obj)->SetCapability(thread_, JSTaggedValue::Undefined());
1602             JSPromiseAnyRejectElementFunction::Cast(*obj)->SetRemainingElements(thread_, JSTaggedValue::Undefined());
1603             JSPromiseAnyRejectElementFunction::Cast(*obj)->SetAlreadyCalled(thread_, JSTaggedValue::Undefined());
1604             break;
1605         case JSType::JS_PROMISE_ALL_SETTLED_ELEMENT_FUNCTION:
1606             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1607             JSPromiseAllSettledElementFunction::Cast(*obj)->SetIndex(0);
1608             JSPromiseAllSettledElementFunction::Cast(*obj)->SetValues(thread_, JSTaggedValue::Undefined());
1609             JSPromiseAllSettledElementFunction::Cast(*obj)->SetCapability(thread_, JSTaggedValue::Undefined());
1610             JSPromiseAllSettledElementFunction::Cast(*obj)->SetRemainingElements(thread_, JSTaggedValue::Undefined());
1611             JSPromiseAllSettledElementFunction::Cast(*obj)->SetAlreadyCalled(thread_, JSTaggedValue::Undefined());
1612             break;
1613         case JSType::JS_PROMISE_FINALLY_FUNCTION:
1614             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1615             JSPromiseFinallyFunction::Cast(*obj)->SetOnFinally(thread_, JSTaggedValue::Undefined());
1616             JSPromiseFinallyFunction::Cast(*obj)->SetConstructor(thread_, JSTaggedValue::Undefined());
1617             break;
1618         case JSType::JS_PROMISE_VALUE_THUNK_OR_THROWER_FUNCTION:
1619             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1620             JSPromiseValueThunkOrThrowerFunction::Cast(*obj)->SetResult(thread_, JSTaggedValue::Undefined());
1621             break;
1622         case JSType::JS_INTL_BOUND_FUNCTION:
1623             JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>(obj));
1624             JSIntlBoundFunction::Cast(*obj)->SetNumberFormat(thread_, JSTaggedValue::Undefined());
1625             JSIntlBoundFunction::Cast(*obj)->SetDateTimeFormat(thread_, JSTaggedValue::Undefined());
1626             JSIntlBoundFunction::Cast(*obj)->SetCollator(thread_, JSTaggedValue::Undefined());
1627             break;
1628         case JSType::JS_BOUND_FUNCTION:
1629             JSBoundFunction::Cast(*obj)->SetMethod(thread_, JSTaggedValue::Undefined());
1630             JSBoundFunction::Cast(*obj)->SetBoundTarget(thread_, JSTaggedValue::Undefined());
1631             JSBoundFunction::Cast(*obj)->SetBoundThis(thread_, JSTaggedValue::Undefined());
1632             JSBoundFunction::Cast(*obj)->SetBoundArguments(thread_, JSTaggedValue::Undefined());
1633             break;
1634         case JSType::JS_ARGUMENTS:
1635             break;
1636         case JSType::JS_FORIN_ITERATOR:
1637         case JSType::JS_MAP_ITERATOR:
1638         case JSType::JS_SET_ITERATOR:
1639         case JSType::JS_REG_EXP_ITERATOR:
1640         case JSType::JS_API_ARRAYLIST_ITERATOR:
1641         case JSType::JS_API_TREEMAP_ITERATOR:
1642         case JSType::JS_API_TREESET_ITERATOR:
1643         case JSType::JS_API_QUEUE_ITERATOR:
1644         case JSType::JS_API_DEQUE_ITERATOR:
1645         case JSType::JS_API_LIGHT_WEIGHT_MAP_ITERATOR:
1646         case JSType::JS_API_LIGHT_WEIGHT_SET_ITERATOR:
1647         case JSType::JS_API_STACK_ITERATOR:
1648         case JSType::JS_API_VECTOR_ITERATOR:
1649         case JSType::JS_API_BITVECTOR_ITERATOR:
1650         case JSType::JS_API_HASHMAP_ITERATOR:
1651         case JSType::JS_API_HASHSET_ITERATOR:
1652         case JSType::JS_ARRAY_ITERATOR:
1653         case JSType::JS_API_PLAIN_ARRAY_ITERATOR:
1654             break;
1655         case JSType::JS_CJS_MODULE:
1656             CjsModule::Cast(*obj)->SetId(thread_, JSTaggedValue::Undefined());
1657             CjsModule::Cast(*obj)->SetExports(thread_, JSTaggedValue::Undefined());
1658             CjsModule::Cast(*obj)->SetPath(thread_, JSTaggedValue::Undefined());
1659             CjsModule::Cast(*obj)->SetFilename(thread_, JSTaggedValue::Undefined());
1660             CjsModule::Cast(*obj)->SetStatus(CjsModuleStatus::UNLOAD);
1661             break;
1662         case JSType::JS_CJS_EXPORTS:
1663             CjsExports::Cast(*obj)->SetExports(thread_, JSTaggedValue::Undefined());
1664             break;
1665         case JSType::JS_CJS_REQUIRE:
1666             CjsRequire::Cast(*obj)->SetCache(thread_, JSTaggedValue::Undefined());
1667             CjsRequire::Cast(*obj)->SetParent(thread_, JSTaggedValue::Undefined());
1668             break;
1669         default:
1670             LOG_ECMA(FATAL) << "this branch is unreachable";
1671             UNREACHABLE();
1672     }
1673 }
1674 
FillFreeObject(uintptr_t address,size_t size,RemoveSlots removeSlots,uintptr_t hugeObjectHead)1675 FreeObject *ObjectFactory::FillFreeObject(uintptr_t address, size_t size, RemoveSlots removeSlots,
1676                                           uintptr_t hugeObjectHead)
1677 {
1678     FreeObject *object = nullptr;
1679     const GlobalEnvConstants *globalConst = thread_->GetFirstGlobalConst();
1680     if (size >= FreeObject::SIZE_OFFSET && size < FreeObject::SIZE) {
1681         object = reinterpret_cast<FreeObject *>(address);
1682         object->SetClassWithoutBarrier(JSHClass::Cast(globalConst->GetFreeObjectWithOneFieldClass().GetTaggedObject()));
1683         object->SetNext(INVALID_OBJECT);
1684     } else if (size >= FreeObject::SIZE) {
1685         object = reinterpret_cast<FreeObject *>(address);
1686         object->SetClassWithoutBarrier(
1687             JSHClass::Cast(globalConst->GetFreeObjectWithTwoFieldClass().GetTaggedObject()));
1688         object->SetAvailable(size);
1689         object->SetNext(INVALID_OBJECT);
1690         if (UNLIKELY(heap_->ShouldVerifyHeap())) {
1691             FillFreeMemoryRange(address + FreeObject::SIZE, address + size);
1692         }
1693     } else if (size == FreeObject::NEXT_OFFSET) {
1694         object = reinterpret_cast<FreeObject *>(address);
1695         object->SetClassWithoutBarrier(
1696             JSHClass::Cast(globalConst->GetFreeObjectWithNoneFieldClass().GetTaggedObject()));
1697     } else {
1698         LOG_ECMA(DEBUG) << "Fill free object size is smaller";
1699     }
1700 
1701     if (removeSlots == RemoveSlots::YES) {
1702         // For huge object, the region of `object` might not be its 1st region. Use `hugeObjectHead` instead.
1703         Region *region = Region::ObjectAddressToRange(hugeObjectHead == 0 ? object :
1704                                                       reinterpret_cast<TaggedObject *>(hugeObjectHead));
1705         heap_->ClearSlotsRange(region, address, address + size);
1706     }
1707     return object;
1708 }
1709 
NewObject(const JSHandle<JSHClass> & hclass)1710 TaggedObject *ObjectFactory::NewObject(const JSHandle<JSHClass> &hclass)
1711 {
1712     NewObjectHook();
1713     TaggedObject *header = heap_->AllocateYoungOrHugeObject(*hclass);
1714     uint32_t inobjPropCount = hclass->GetInlinedProperties();
1715     if (inobjPropCount > 0) {
1716         InitializeExtraProperties(hclass, header, inobjPropCount);
1717     }
1718     return header;
1719 }
1720 
NewNonMovableObject(const JSHandle<JSHClass> & hclass,uint32_t inobjPropCount)1721 TaggedObject *ObjectFactory::NewNonMovableObject(const JSHandle<JSHClass> &hclass, uint32_t inobjPropCount)
1722 {
1723     NewObjectHook();
1724     TaggedObject *header = heap_->AllocateNonMovableOrHugeObject(*hclass);
1725     if (inobjPropCount > 0) {
1726         InitializeExtraProperties(hclass, header, inobjPropCount);
1727     }
1728     return header;
1729 }
1730 
InitializeExtraProperties(const JSHandle<JSHClass> & hclass,TaggedObject * obj,uint32_t inobjPropCount)1731 void ObjectFactory::InitializeExtraProperties(const JSHandle<JSHClass> &hclass,
1732                                               TaggedObject *obj, uint32_t inobjPropCount)
1733 {
1734     ASSERT(inobjPropCount * JSTaggedValue::TaggedTypeSize() < hclass->GetObjectSize());
1735     auto paddr = reinterpret_cast<uintptr_t>(obj) + hclass->GetObjectSize();
1736     // The object which created by AOT speculative hclass, should be initialized as hole, means does not exist,
1737     // to follow ECMA spec.
1738     JSTaggedType initVal = hclass->IsTS() ? JSTaggedValue::VALUE_HOLE : JSTaggedValue::VALUE_UNDEFINED;
1739     for (uint32_t i = 0; i < inobjPropCount; ++i) {
1740         paddr -= JSTaggedValue::TaggedTypeSize();
1741         *reinterpret_cast<JSTaggedType *>(paddr) = initVal;
1742     }
1743 }
1744 
OrdinaryNewJSObjectCreate(const JSHandle<JSTaggedValue> & proto)1745 JSHandle<JSObject> ObjectFactory::OrdinaryNewJSObjectCreate(const JSHandle<JSTaggedValue> &proto)
1746 {
1747     JSHandle<JSTaggedValue> protoValue(proto);
1748     JSHandle<JSHClass> hclass(thread_, thread_->GlobalConstants()->GetObjectClass().GetTaggedObject());
1749     JSHandle<JSHClass> newClass = JSHClass::TransProtoWithoutLayout(thread_, hclass, protoValue);
1750     JSHandle<JSObject> newObj = NewJSObject(newClass);
1751     newObj->GetJSHClass()->SetExtensible(true);
1752     return newObj;
1753 }
1754 
NewJSFunction(const JSHandle<GlobalEnv> & env,const void * nativeFunc,FunctionKind kind,kungfu::BuiltinsStubCSigns::ID builtinId,MemSpaceType methodSpaceType)1755 JSHandle<JSFunction> ObjectFactory::NewJSFunction(const JSHandle<GlobalEnv> &env, const void *nativeFunc,
1756                                                   FunctionKind kind, kungfu::BuiltinsStubCSigns::ID builtinId,
1757                                                   MemSpaceType methodSpaceType)
1758 {
1759     JSHandle<Method> target = NewMethodForNativeFunction(nativeFunc, kind, builtinId, methodSpaceType);
1760     return NewJSFunction(env, target);
1761 }
1762 
NewJSFunction(const JSHandle<GlobalEnv> & env,const JSHandle<Method> & method)1763 JSHandle<JSFunction> ObjectFactory::NewJSFunction(const JSHandle<GlobalEnv> &env,
1764                                                   const JSHandle<Method> &method)
1765 {
1766     FunctionKind kind = method->GetFunctionKind();
1767     JSHandle<JSHClass> hclass;
1768     if (kind == FunctionKind::BASE_CONSTRUCTOR) {
1769         hclass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithProto());
1770     } else if (JSFunction::IsConstructorKind(kind)) {
1771         hclass = JSHandle<JSHClass>::Cast(env->GetConstructorFunctionClass());
1772     } else if (kind == FunctionKind::CONCURRENT_FUNCTION) {
1773         hclass = JSHandle<JSHClass>::Cast(env->GetAsyncFunctionClass());
1774     } else {
1775         hclass = JSHandle<JSHClass>::Cast(env->GetNormalFunctionClass());
1776     }
1777 
1778     return NewJSFunctionByHClass(method, hclass);
1779 }
1780 
NewSFunction(const JSHandle<GlobalEnv> & env,const void * nativeFunc,FunctionKind kind,kungfu::BuiltinsStubCSigns::ID builtinId,MemSpaceType spaceType)1781 JSHandle<JSFunction> ObjectFactory::NewSFunction(const JSHandle<GlobalEnv> &env,
1782                                                  const void *nativeFunc,
1783                                                  FunctionKind kind,
1784                                                  kungfu::BuiltinsStubCSigns::ID builtinId,
1785                                                  MemSpaceType spaceType)
1786 {
1787     JSHandle<Method> method = NewSMethodForNativeFunction(nativeFunc, kind, builtinId, spaceType);
1788     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetSFunctionClassWithoutProto());
1789     JSHandle<JSFunction> sfunc = NewSFunctionByHClass(method, hclass);
1790     return sfunc;
1791 }
1792 
CreateFunctionClass(FunctionKind kind,uint32_t size,JSType type,const JSHandle<JSTaggedValue> & prototype)1793 JSHandle<JSHClass> ObjectFactory::CreateFunctionClass(FunctionKind kind, uint32_t size, JSType type,
1794                                                       const JSHandle<JSTaggedValue> &prototype)
1795 {
1796     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1797     JSHandle<JSHClass> functionClass = NewEcmaHClass(size, type, prototype);
1798     {
1799         functionClass->SetCallable(true);
1800         // FunctionKind = BASE_CONSTRUCTOR
1801         if (JSFunction::IsConstructorKind(kind)) {
1802             functionClass->SetConstructor(true);
1803         }
1804         functionClass->SetExtensible(true);
1805     }
1806 
1807     uint32_t fieldOrder = 0;
1808     ASSERT(JSFunction::LENGTH_INLINE_PROPERTY_INDEX == fieldOrder);
1809     JSHandle<LayoutInfo> layoutInfoHandle = CreateLayoutInfo(JSFunction::LENGTH_OF_INLINE_PROPERTIES);
1810     {
1811         PropertyAttributes attributes = PropertyAttributes::DefaultAccessor(false, false, true);
1812         attributes.SetIsInlinedProps(true);
1813         attributes.SetRepresentation(Representation::TAGGED);
1814         attributes.SetOffset(fieldOrder);
1815         layoutInfoHandle->AddKey(thread_, fieldOrder, globalConst->GetLengthString(), attributes);
1816         fieldOrder++;
1817     }
1818 
1819     ASSERT(JSFunction::NAME_INLINE_PROPERTY_INDEX == fieldOrder);
1820     // not set name in-object property on class which may have a name() method
1821     if (!JSFunction::IsClassConstructor(kind)) {
1822         PropertyAttributes attributes = PropertyAttributes::DefaultAccessor(false, false, true);
1823         attributes.SetIsInlinedProps(true);
1824         attributes.SetRepresentation(Representation::TAGGED);
1825         attributes.SetOffset(fieldOrder);
1826         layoutInfoHandle->AddKey(thread_, fieldOrder,
1827                                  thread_->GlobalConstants()->GetHandledNameString().GetTaggedValue(), attributes);
1828         fieldOrder++;
1829     }
1830 
1831     if (JSFunction::HasPrototype(kind) && !JSFunction::IsClassConstructor(kind)) {
1832         ASSERT(JSFunction::PROTOTYPE_INLINE_PROPERTY_INDEX == fieldOrder);
1833         PropertyAttributes attributes = PropertyAttributes::DefaultAccessor(true, false, false);
1834         attributes.SetIsInlinedProps(true);
1835         attributes.SetRepresentation(Representation::TAGGED);
1836         attributes.SetOffset(fieldOrder);
1837         layoutInfoHandle->AddKey(thread_, fieldOrder, globalConst->GetPrototypeString(), attributes);
1838         fieldOrder++;
1839     } else if (JSFunction::IsClassConstructor(kind)) {
1840         ASSERT(JSFunction::CLASS_PROTOTYPE_INLINE_PROPERTY_INDEX == fieldOrder);
1841         PropertyAttributes attributes = PropertyAttributes::DefaultAccessor(false, false, false);
1842         attributes.SetIsInlinedProps(true);
1843         attributes.SetRepresentation(Representation::TAGGED);
1844         attributes.SetOffset(fieldOrder);
1845         layoutInfoHandle->AddKey(thread_, fieldOrder, globalConst->GetPrototypeString(), attributes);
1846         fieldOrder++;
1847     }
1848 
1849     {
1850         functionClass->SetLayout(thread_, layoutInfoHandle);
1851         functionClass->SetNumberOfProps(fieldOrder);
1852     }
1853     return functionClass;
1854 }
1855 
CreateBoundFunctionClass()1856 JSHandle<JSHClass> ObjectFactory::CreateBoundFunctionClass()
1857 {
1858     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
1859     JSHandle<JSTaggedValue> proto = env->GetFunctionPrototype();
1860     JSHandle<JSHClass> hclass = NewEcmaHClass(JSBoundFunction::SIZE, JSType::JS_BOUND_FUNCTION, proto);
1861     hclass->SetCallable(true);
1862 
1863     // set hclass layout
1864     uint32_t fieldOrder = 0;
1865     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
1866     ASSERT(JSFunction::LENGTH_INLINE_PROPERTY_INDEX == fieldOrder);
1867     JSHandle<LayoutInfo> layoutInfoHandle = CreateLayoutInfo(JSFunction::LENGTH_OF_INLINE_PROPERTIES);
1868     {
1869         PropertyAttributes attributes = PropertyAttributes::DefaultAccessor(false, false, true);
1870         attributes.SetIsInlinedProps(true);
1871         attributes.SetRepresentation(Representation::TAGGED);
1872         attributes.SetOffset(fieldOrder);
1873         layoutInfoHandle->AddKey(thread_, fieldOrder, globalConst->GetLengthString(), attributes);
1874         fieldOrder++;
1875     }
1876 
1877     ASSERT(JSFunction::NAME_INLINE_PROPERTY_INDEX == fieldOrder);
1878     // not set name in-object property on class which may have a name() method
1879     {
1880         PropertyAttributes attributes = PropertyAttributes::DefaultAccessor(false, false, true);
1881         attributes.SetIsInlinedProps(true);
1882         attributes.SetRepresentation(Representation::TAGGED);
1883         attributes.SetOffset(fieldOrder);
1884         layoutInfoHandle->AddKey(thread_, fieldOrder,
1885                                  globalConst->GetHandledNameString().GetTaggedValue(), attributes);
1886         fieldOrder++;
1887     }
1888 
1889     {
1890         hclass->SetLayout(thread_, layoutInfoHandle);
1891         hclass->SetNumberOfProps(fieldOrder);
1892     }
1893     return hclass;
1894 }
1895 
CreateDefaultClassPrototypeHClass(JSHClass * hclass)1896 JSHandle<JSHClass> ObjectFactory::CreateDefaultClassPrototypeHClass(JSHClass *hclass)
1897 {
1898     uint32_t size = ClassInfoExtractor::NON_STATIC_RESERVED_LENGTH;
1899     JSHandle<LayoutInfo> layout = CreateLayoutInfo(size, MemSpaceType::OLD_SPACE, GrowMode::KEEP);
1900     PropertyAttributes attributes = PropertyAttributes::Default(true, false, true);  // non-enumerable
1901 
1902     attributes.SetIsInlinedProps(true);
1903     attributes.SetRepresentation(Representation::TAGGED);
1904     attributes.SetOffset(ClassInfoExtractor::CONSTRUCTOR_INDEX);
1905     layout->AddKey(thread_, ClassInfoExtractor::CONSTRUCTOR_INDEX,
1906         thread_->GlobalConstants()->GetConstructorString(), attributes);
1907 
1908     JSHandle<JSHClass> defaultHclass = NewEcmaHClass(hclass, JSObject::SIZE, JSType::JS_OBJECT, size);
1909     defaultHclass->SetLayout(thread_, layout);
1910     defaultHclass->SetNumberOfProps(size);
1911     defaultHclass->SetClassPrototype(true);
1912     defaultHclass->SetIsPrototype(true);
1913     return defaultHclass;
1914 }
1915 
CreateDefaultClassConstructorHClass(JSHClass * hclass)1916 JSHandle<JSHClass> ObjectFactory::CreateDefaultClassConstructorHClass(JSHClass *hclass)
1917 {
1918     uint32_t size = ClassInfoExtractor::STATIC_RESERVED_LENGTH;
1919     JSHandle<LayoutInfo> layout = CreateLayoutInfo(size, MemSpaceType::OLD_SPACE, GrowMode::KEEP);
1920 
1921     JSHandle<TaggedArray> array = NewTaggedArray(size);
1922     array->Set(thread_, ClassInfoExtractor::LENGTH_INDEX, thread_->GlobalConstants()->GetLengthString());
1923     array->Set(thread_, ClassInfoExtractor::NAME_INDEX, thread_->GlobalConstants()->GetNameString());
1924     array->Set(thread_, ClassInfoExtractor::PROTOTYPE_INDEX, thread_->GlobalConstants()->GetPrototypeString());
1925     for (uint32_t index = ClassInfoExtractor::LENGTH_INDEX; index < size; index++) {
1926         PropertyAttributes attributes;
1927         if (index == ClassInfoExtractor::PROTOTYPE_INDEX) {
1928             attributes = PropertyAttributes::DefaultAccessor(false, false, false);
1929         } else {
1930             attributes = PropertyAttributes::Default(false, false, true);
1931         }
1932         attributes.SetIsInlinedProps(true);
1933         attributes.SetRepresentation(Representation::TAGGED);
1934         attributes.SetOffset(index);
1935         layout->AddKey(thread_, index, array->Get(index), attributes);
1936     }
1937 
1938     JSHandle<JSHClass> defaultHclass = NewEcmaHClass(hclass, JSFunction::SIZE, JSType::JS_FUNCTION, size);
1939     defaultHclass->SetLayout(thread_, layout);
1940     defaultHclass->SetNumberOfProps(size);
1941     defaultHclass->SetClassConstructor(true);
1942     defaultHclass->SetConstructor(true);
1943     return defaultHclass;
1944 }
1945 
SetCodeEntryToFunctionFromMethod(const JSHandle<JSFunction> & func,const JSHandle<Method> & mothed)1946 void ObjectFactory::SetCodeEntryToFunctionFromMethod(const JSHandle<JSFunction> &func, const JSHandle<Method> &mothed)
1947 {
1948     uintptr_t entry = mothed->GetCodeEntryOrLiteral();
1949     func->SetCodeEntry(entry);
1950 }
1951 
NewJSFunctionByHClass(const JSHandle<Method> & method,const JSHandle<JSHClass> & clazz,MemSpaceType type)1952 JSHandle<JSFunction> ObjectFactory::NewJSFunctionByHClass(const JSHandle<Method> &method,
1953                                                           const JSHandle<JSHClass> &clazz,
1954                                                           MemSpaceType type)
1955 {
1956     JSHandle<JSFunction> function;
1957     switch (type) {
1958         case MemSpaceType::SEMI_SPACE:
1959             function = JSHandle<JSFunction>::Cast(NewJSObject(clazz));
1960             break;
1961         case MemSpaceType::OLD_SPACE:
1962             function = JSHandle<JSFunction>::Cast(NewOldSpaceJSObject(clazz));
1963             break;
1964         case MemSpaceType::NON_MOVABLE:
1965             function = JSHandle<JSFunction>::Cast(NewNonMovableJSObject(clazz));
1966             break;
1967         default:
1968             LOG_ECMA(FATAL) << "this branch is unreachable";
1969             UNREACHABLE();
1970     }
1971     clazz->SetCallable(true);
1972     clazz->SetExtensible(true);
1973     JSFunction::InitializeJSFunction(thread_, function, method->GetFunctionKind());
1974     function->SetMethod(thread_, method);
1975     function->SetTaskConcurrentFuncFlag(0); // 0 : default value
1976     if (method->IsAotWithCallField()) {
1977         thread_->GetEcmaVM()->GetAOTFileManager()->
1978             SetAOTFuncEntry(method->GetJSPandaFile(), *function, *method);
1979     } else {
1980         SetCodeEntryToFunctionFromMethod(function, method);
1981     }
1982     return function;
1983 }
1984 
NewJSFunctionByHClass(const void * func,const JSHandle<JSHClass> & clazz,FunctionKind kind)1985 JSHandle<JSFunction> ObjectFactory::NewJSFunctionByHClass(const void *func, const JSHandle<JSHClass> &clazz,
1986                                                           FunctionKind kind)
1987 {
1988     JSHandle<Method> method = NewMethodForNativeFunction(func, kind);
1989     JSHandle<JSFunction> function = JSHandle<JSFunction>::Cast(NewJSObject(clazz));
1990     clazz->SetCallable(true);
1991     clazz->SetExtensible(true);
1992     JSFunction::InitializeJSFunction(thread_, function, kind);
1993     function->SetMethod(thread_, method);
1994     return function;
1995 }
1996 
1997 // new function with name/length accessor
NewJSFunctionByHClassWithoutAccessor(const void * func,const JSHandle<JSHClass> & clazz,FunctionKind kind)1998 JSHandle<JSFunction> ObjectFactory::NewJSFunctionByHClassWithoutAccessor(const void *func,
1999     const JSHandle<JSHClass> &clazz, FunctionKind kind)
2000 {
2001     JSHandle<Method> method = NewMethodForNativeFunction(func, kind);
2002     JSHandle<JSFunction> function = JSHandle<JSFunction>::Cast(NewJSObject(clazz));
2003     clazz->SetCallable(true);
2004     clazz->SetExtensible(true);
2005     JSFunction::InitializeWithDefaultValue(thread_, function);
2006     function->SetMethod(thread_, method);
2007     return function;
2008 }
2009 
InitializeMethod(const MethodLiteral * methodLiteral,JSHandle<Method> & method)2010 void ObjectFactory::InitializeMethod(const MethodLiteral *methodLiteral, JSHandle<Method> &method)
2011 {
2012     if (methodLiteral != nullptr) {
2013         method->SetCallField(methodLiteral->GetCallField());
2014         method->SetLiteralInfo(methodLiteral->GetLiteralInfo());
2015         method->SetNativePointerOrBytecodeArray(const_cast<void *>(methodLiteral->GetNativePointer()));
2016         method->SetExtraLiteralInfo(methodLiteral->GetExtraLiteralInfo());
2017     } else {
2018         method->SetCallField(0ULL);
2019         method->SetLiteralInfo(0ULL);
2020         method->SetNativePointerOrBytecodeArray(nullptr);
2021         method->SetExtraLiteralInfo(0ULL);
2022     }
2023     method->SetCodeEntryOrLiteral(reinterpret_cast<uintptr_t>(methodLiteral));
2024     method->SetConstantPool(thread_, JSTaggedValue::Undefined());
2025     method->SetFpDelta(0);
2026 }
2027 
NewMethod(const MethodLiteral * methodLiteral,MemSpaceType spaceType)2028 JSHandle<Method> ObjectFactory::NewMethod(const MethodLiteral *methodLiteral, MemSpaceType spaceType)
2029 {
2030     NewObjectHook();
2031     TaggedObject *header = nullptr;
2032     if (spaceType == NON_MOVABLE) {
2033         header = heap_->AllocateNonMovableOrHugeObject(
2034             JSHClass::Cast(thread_->GlobalConstants()->GetMethodClass().GetTaggedObject()));
2035     } else {
2036         header = heap_->AllocateOldOrHugeObject(
2037             JSHClass::Cast(thread_->GlobalConstants()->GetMethodClass().GetTaggedObject()));
2038     }
2039     JSHandle<Method> method(thread_, header);
2040     InitializeMethod(methodLiteral, method);
2041     return method;
2042 }
2043 
NewMethod(const JSPandaFile * jsPandaFile,MethodLiteral * methodLiteral,JSHandle<ConstantPool> constpool,uint32_t entryIndex,bool needSetAotFlag,bool * canFastCall)2044 JSHandle<Method> ObjectFactory::NewMethod(const JSPandaFile *jsPandaFile, MethodLiteral *methodLiteral,
2045                                           JSHandle<ConstantPool> constpool, uint32_t entryIndex,
2046                                           bool needSetAotFlag, bool *canFastCall)
2047 {
2048     JSHandle<Method> method;
2049     if (jsPandaFile->IsNewVersion()) {
2050         method = Method::Create(thread_, jsPandaFile, methodLiteral);
2051     } else {
2052         method = NewMethod(methodLiteral);
2053         method->SetConstantPool(thread_, constpool);
2054     }
2055     if (needSetAotFlag) {
2056         thread_->GetEcmaVM()->GetAOTFileManager()->
2057             SetAOTFuncEntry(jsPandaFile, nullptr, *method, entryIndex, canFastCall);
2058     } else {
2059         method->InitInterpreterStatusForCompiledMethod(thread_);
2060     }
2061     return method;
2062 }
2063 
NewJSNativeErrorFunction(const JSHandle<GlobalEnv> & env,const void * nativeFunc)2064 JSHandle<JSFunction> ObjectFactory::NewJSNativeErrorFunction(const JSHandle<GlobalEnv> &env, const void *nativeFunc)
2065 {
2066     JSHandle<Method> target = NewMethodForNativeFunction(nativeFunc, FunctionKind::BUILTIN_CONSTRUCTOR);
2067     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetNativeErrorFunctionClass());
2068     return NewJSFunctionByHClass(target, hclass);
2069 }
2070 
NewSpecificTypedArrayFunction(const JSHandle<GlobalEnv> & env,const void * nativeFunc,kungfu::BuiltinsStubCSigns::ID builtinId)2071 JSHandle<JSFunction> ObjectFactory::NewSpecificTypedArrayFunction(const JSHandle<GlobalEnv> &env,
2072                                                                   const void *nativeFunc,
2073                                                                   kungfu::BuiltinsStubCSigns::ID builtinId)
2074 {
2075     JSHandle<Method> target = NewMethodForNativeFunction(nativeFunc, FunctionKind::BUILTIN_CONSTRUCTOR, builtinId);
2076     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetSpecificTypedArrayFunctionClass());
2077     return NewJSFunctionByHClass(target, hclass);
2078 }
2079 
NewAotFunction(uint32_t numArgs,uintptr_t codeEntry)2080 JSHandle<JSFunction> ObjectFactory::NewAotFunction(uint32_t numArgs, uintptr_t codeEntry)
2081 {
2082     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2083     JSHandle<Method> method = NewMethodForNativeFunction(reinterpret_cast<void *>(codeEntry));
2084     method->SetAotCodeBit(true);
2085     method->SetNativeBit(false);
2086     method->SetNumArgsWithCallField(numArgs);
2087     method->SetCodeEntryOrLiteral(codeEntry);
2088     JSHandle<JSFunction> jsfunc = NewJSFunction(env, method);
2089     return jsfunc;
2090 }
2091 
NewJSBoundFunction(const JSHandle<JSTaggedValue> & target,const JSHandle<JSTaggedValue> & boundThis,const JSHandle<TaggedArray> & args)2092 JSHandle<JSBoundFunction> ObjectFactory::NewJSBoundFunction(const JSHandle<JSTaggedValue> &target,
2093                                                             const JSHandle<JSTaggedValue> &boundThis,
2094                                                             const JSHandle<TaggedArray> &args)
2095 {
2096     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2097     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
2098 
2099     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetBoundFunctionClass());
2100     JSHandle<JSBoundFunction> bundleFunction = JSHandle<JSBoundFunction>::Cast(NewJSObject(hclass));
2101     // set properties
2102     JSHandle<JSTaggedValue> accessor = globalConst->GetHandledFunctionNameAccessor();
2103     bundleFunction->SetPropertyInlinedProps(thread_, JSFunction::NAME_INLINE_PROPERTY_INDEX,
2104                                             accessor.GetTaggedValue());
2105     accessor = globalConst->GetHandledFunctionLengthAccessor();
2106     bundleFunction->SetPropertyInlinedProps(thread_, JSFunction::LENGTH_INLINE_PROPERTY_INDEX,
2107                                             accessor.GetTaggedValue());
2108 
2109     bundleFunction->SetBoundTarget(thread_, target);
2110     bundleFunction->SetBoundThis(thread_, boundThis);
2111     bundleFunction->SetBoundArguments(thread_, args);
2112 
2113     if (target.GetTaggedValue().IsConstructor()) {
2114         bundleFunction->SetConstructor(true);
2115     }
2116     bundleFunction->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_GLOBAL_CALL_JS_BOUND_FUNCTION));
2117     return bundleFunction;
2118 }
2119 
NewJSIntlBoundFunction(MethodIndex idx,int functionLength)2120 JSHandle<JSIntlBoundFunction> ObjectFactory::NewJSIntlBoundFunction(MethodIndex idx, int functionLength)
2121 {
2122     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2123     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetJSIntlBoundFunctionClass());
2124 
2125     JSHandle<JSIntlBoundFunction> intlBoundFunc = JSHandle<JSIntlBoundFunction>::Cast(NewJSObject(hclass));
2126     intlBoundFunc->SetNumberFormat(thread_, JSTaggedValue::Undefined());
2127     intlBoundFunc->SetDateTimeFormat(thread_, JSTaggedValue::Undefined());
2128     intlBoundFunc->SetCollator(thread_, JSTaggedValue::Undefined());
2129     JSHandle<JSFunction> function = JSHandle<JSFunction>::Cast(intlBoundFunc);
2130     JSFunction::InitializeJSFunction(thread_, function);
2131     function->SetMethod(thread_, vm_->GetMethodByIndex(idx));
2132     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(functionLength));
2133     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
2134     JSHandle<JSTaggedValue> emptyString = globalConst->GetHandledEmptyString();
2135     JSHandle<JSTaggedValue> nameKey = globalConst->GetHandledNameString();
2136     PropertyDescriptor nameDesc(thread_, emptyString, false, false, true);
2137     JSTaggedValue::DefinePropertyOrThrow(thread_, JSHandle<JSTaggedValue>::Cast(function), nameKey, nameDesc);
2138     RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSIntlBoundFunction, thread_);
2139     return intlBoundFunc;
2140 }
2141 
NewJSProxyRevocFunction(const JSHandle<JSProxy> & proxy)2142 JSHandle<JSProxyRevocFunction> ObjectFactory::NewJSProxyRevocFunction(const JSHandle<JSProxy> &proxy)
2143 {
2144     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2145     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
2146     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetProxyRevocFunctionClass());
2147 
2148     JSHandle<JSProxyRevocFunction> revocFunction = JSHandle<JSProxyRevocFunction>::Cast(NewJSObject(hclass));
2149     revocFunction->SetRevocableProxy(thread_, JSTaggedValue::Undefined());
2150     revocFunction->SetRevocableProxy(thread_, proxy);
2151     JSHandle<JSFunction> function = JSHandle<JSFunction>::Cast(revocFunction);
2152     JSFunction::InitializeJSFunction(thread_, function);
2153     function->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROXY_INVALIDATE_PROXY_FUNCTION));
2154     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(0));
2155     JSHandle<JSTaggedValue> emptyString = globalConst->GetHandledEmptyString();
2156     JSHandle<JSTaggedValue> nameKey = globalConst->GetHandledNameString();
2157     PropertyDescriptor nameDesc(thread_, emptyString, false, false, true);
2158     JSTaggedValue::DefinePropertyOrThrow(thread_, JSHandle<JSTaggedValue>::Cast(function), nameKey, nameDesc);
2159     RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSProxyRevocFunction, thread_);
2160     return revocFunction;
2161 }
2162 
NewJSAsyncAwaitStatusFunction(MethodIndex idx)2163 JSHandle<JSAsyncAwaitStatusFunction> ObjectFactory::NewJSAsyncAwaitStatusFunction(MethodIndex idx)
2164 {
2165     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2166     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetAsyncAwaitStatusFunctionClass());
2167 
2168     JSHandle<JSAsyncAwaitStatusFunction> awaitFunction =
2169         JSHandle<JSAsyncAwaitStatusFunction>::Cast(NewJSObject(hclass));
2170     awaitFunction->SetAsyncContext(thread_, JSTaggedValue::Undefined());
2171     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(awaitFunction));
2172     awaitFunction->SetMethod(thread_, vm_->GetMethodByIndex(idx));
2173     return awaitFunction;
2174 }
2175 
NewJSGeneratorObject(JSHandle<JSTaggedValue> generatorFunction)2176 JSHandle<JSGeneratorObject> ObjectFactory::NewJSGeneratorObject(JSHandle<JSTaggedValue> generatorFunction)
2177 {
2178     JSHandle<JSTaggedValue> proto(thread_, JSHandle<JSFunction>::Cast(generatorFunction)->GetProtoOrHClass());
2179     if (!proto->IsECMAObject()) {
2180         JSHandle<GlobalEnv> realmHandle = JSObject::GetFunctionRealm(thread_, generatorFunction);
2181         RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSGeneratorObject, thread_);
2182         proto = realmHandle->GetGeneratorPrototype();
2183     }
2184     JSHandle<JSHClass> hclass = NewEcmaHClass(JSGeneratorObject::SIZE, JSType::JS_GENERATOR_OBJECT, proto);
2185     JSHandle<JSGeneratorObject> generatorObject = JSHandle<JSGeneratorObject>::Cast(NewJSObjectWithInit(hclass));
2186     generatorObject->SetGeneratorContext(thread_, JSTaggedValue::Undefined());
2187     generatorObject->SetResumeResult(thread_, JSTaggedValue::Undefined());
2188     return generatorObject;
2189 }
2190 
NewJSAsyncGeneratorObject(JSHandle<JSTaggedValue> generatorFunction)2191 JSHandle<JSAsyncGeneratorObject> ObjectFactory::NewJSAsyncGeneratorObject(JSHandle<JSTaggedValue> generatorFunction)
2192 {
2193     JSHandle<JSTaggedValue> proto(thread_, JSHandle<JSFunction>::Cast(generatorFunction)->GetProtoOrHClass());
2194     if (!proto->IsECMAObject()) {
2195         JSHandle<GlobalEnv> realmHandle = JSObject::GetFunctionRealm(thread_, generatorFunction);
2196         RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSAsyncGeneratorObject, thread_);
2197         proto = realmHandle->GetAsyncGeneratorPrototype();
2198     }
2199     JSHandle<JSHClass> hclass = NewEcmaHClass(JSAsyncGeneratorObject::SIZE,
2200                                               JSType::JS_ASYNC_GENERATOR_OBJECT, proto);
2201     JSHandle<JSAsyncGeneratorObject> generatorObject =
2202         JSHandle<JSAsyncGeneratorObject>::Cast(NewJSObjectWithInit(hclass));
2203     return generatorObject;
2204 }
2205 
NewJSAsyncFuncObject()2206 JSHandle<JSAsyncFuncObject> ObjectFactory::NewJSAsyncFuncObject()
2207 {
2208     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2209     JSHandle<JSTaggedValue> proto = env->GetInitialGenerator();
2210     JSHandle<JSHClass> hclass = NewEcmaHClass(JSAsyncFuncObject::SIZE, JSType::JS_ASYNC_FUNC_OBJECT, proto);
2211     JSHandle<JSAsyncFuncObject> asyncFuncObject = JSHandle<JSAsyncFuncObject>::Cast(NewJSObjectWithInit(hclass));
2212     return asyncFuncObject;
2213 }
2214 
NewCompletionRecord(CompletionRecordType type,JSHandle<JSTaggedValue> value)2215 JSHandle<CompletionRecord> ObjectFactory::NewCompletionRecord(CompletionRecordType type, JSHandle<JSTaggedValue> value)
2216 {
2217     NewObjectHook();
2218     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2219         JSHClass::Cast(thread_->GlobalConstants()->GetCompletionRecordClass().GetTaggedObject()));
2220     JSHandle<CompletionRecord> obj(thread_, header);
2221     obj->SetType(type);
2222     obj->SetValue(thread_, value);
2223     return obj;
2224 }
2225 
NewGeneratorContext()2226 JSHandle<GeneratorContext> ObjectFactory::NewGeneratorContext()
2227 {
2228     NewObjectHook();
2229     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2230         JSHClass::Cast(thread_->GlobalConstants()->GetGeneratorContextClass().GetTaggedObject()));
2231     JSHandle<GeneratorContext> obj(thread_, header);
2232     obj->SetRegsArray(thread_, JSTaggedValue::Undefined());
2233     obj->SetMethod(thread_, JSTaggedValue::Undefined());
2234     obj->SetThis(thread_, JSTaggedValue::Undefined());
2235     obj->SetAcc(thread_, JSTaggedValue::Undefined());
2236     obj->SetGeneratorObject(thread_, JSTaggedValue::Undefined());
2237     obj->SetLexicalEnv(thread_, JSTaggedValue::Undefined());
2238     obj->SetNRegs(0);
2239     obj->SetBCOffset(0);
2240     return obj;
2241 }
2242 
NewJSPrimitiveRef(const JSHandle<JSFunction> & function,const JSHandle<JSTaggedValue> & object)2243 JSHandle<JSPrimitiveRef> ObjectFactory::NewJSPrimitiveRef(const JSHandle<JSFunction> &function,
2244                                                           const JSHandle<JSTaggedValue> &object)
2245 {
2246     JSHandle<JSPrimitiveRef> obj(NewJSObjectByConstructor(function));
2247     obj->SetValue(thread_, object);
2248 
2249     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2250     if (function.GetTaggedValue() == env->GetStringFunction().GetTaggedValue()) {
2251         JSHandle<JSTaggedValue> lengthStr = thread_->GlobalConstants()->GetHandledLengthString();
2252         uint32_t length = EcmaStringAccessor(object.GetTaggedValue()).GetLength();
2253         PropertyDescriptor desc(thread_, JSHandle<JSTaggedValue>(thread_, JSTaggedValue(length)), false, false, false);
2254         JSTaggedValue::DefinePropertyOrThrow(thread_, JSHandle<JSTaggedValue>(obj), lengthStr, desc);
2255         RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSPrimitiveRef, thread_);
2256     }
2257 
2258     return obj;
2259 }
2260 
NewJSPrimitiveRef(PrimitiveType type,const JSHandle<JSTaggedValue> & object)2261 JSHandle<JSPrimitiveRef> ObjectFactory::NewJSPrimitiveRef(PrimitiveType type, const JSHandle<JSTaggedValue> &object)
2262 {
2263     ObjectFactory *factory = vm_->GetFactory();
2264     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2265     JSHandle<JSTaggedValue> function;
2266     switch (type) {
2267         case PrimitiveType::PRIMITIVE_NUMBER:
2268             function = env->GetNumberFunction();
2269             break;
2270         case PrimitiveType::PRIMITIVE_STRING:
2271             function = env->GetStringFunction();
2272             break;
2273         case PrimitiveType::PRIMITIVE_SYMBOL:
2274             function = env->GetSymbolFunction();
2275             break;
2276         case PrimitiveType::PRIMITIVE_BOOLEAN:
2277             function = env->GetBooleanFunction();
2278             break;
2279         case PrimitiveType::PRIMITIVE_BIGINT:
2280             function = env->GetBigIntFunction();
2281             break;
2282         default:
2283             break;
2284     }
2285     JSHandle<JSFunction> funcHandle(function);
2286     return factory->NewJSPrimitiveRef(funcHandle, object);
2287 }
2288 
NewJSString(const JSHandle<JSTaggedValue> & str,const JSHandle<JSTaggedValue> & newTarget)2289 JSHandle<JSPrimitiveRef> ObjectFactory::NewJSString(const JSHandle<JSTaggedValue> &str,
2290                                                     const JSHandle<JSTaggedValue> &newTarget)
2291 {
2292     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2293     JSHandle<JSFunction> stringFunc(env->GetStringFunction());
2294     JSHandle<JSPrimitiveRef> obj;
2295     if (newTarget->IsUndefined()) {
2296         obj = JSHandle<JSPrimitiveRef>::Cast(NewJSObjectByConstructor(stringFunc));
2297     } else {
2298         JSHandle<JSObject> newObject = NewJSObjectByConstructor(stringFunc, newTarget);
2299         RETURN_HANDLE_IF_ABRUPT_COMPLETION(JSPrimitiveRef, thread_);
2300         obj = JSHandle<JSPrimitiveRef>::Cast(newObject);
2301     }
2302     obj->SetValue(thread_, str);
2303     return obj;
2304 }
2305 
NewGlobalEnv(JSHClass * globalEnvClass)2306 JSHandle<GlobalEnv> ObjectFactory::NewGlobalEnv(JSHClass *globalEnvClass)
2307 {
2308     NewObjectHook();
2309     // Note: Global env must be allocated in non-movable heap, since its getters will directly return
2310     //       the offsets of the properties as the address of Handles.
2311     TaggedObject *header = heap_->AllocateNonMovableOrHugeObject(globalEnvClass);
2312     InitObjectFields(header);
2313     return JSHandle<GlobalEnv>(thread_, GlobalEnv::Cast(header));
2314 }
2315 
NewLexicalEnv(int numSlots)2316 JSHandle<LexicalEnv> ObjectFactory::NewLexicalEnv(int numSlots)
2317 {
2318     NewObjectHook();
2319     size_t size = LexicalEnv::ComputeSize(numSlots);
2320     auto header = heap_->AllocateYoungOrHugeObject(
2321         JSHClass::Cast(thread_->GlobalConstants()->GetEnvClass().GetTaggedObject()), size);
2322     JSHandle<LexicalEnv> array(thread_, header);
2323     array->InitializeWithSpecialValue(JSTaggedValue::Hole(), numSlots + LexicalEnv::RESERVED_ENV_LENGTH);
2324     return array;
2325 }
2326 
NewEmptySymbol()2327 JSHandle<JSSymbol> ObjectFactory::NewEmptySymbol()
2328 {
2329     NewObjectHook();
2330     TaggedObject *header = heap_->AllocateNonMovableOrHugeObject(
2331         JSHClass::Cast(thread_->GlobalConstants()->GetSymbolClass().GetTaggedObject()));
2332     JSHandle<JSSymbol> obj(thread_, JSSymbol::Cast(header));
2333     obj->SetDescription(thread_, JSTaggedValue::Undefined());
2334     obj->SetFlags(0);
2335     obj->SetHashField(0);
2336     return obj;
2337 }
2338 
NewJSSymbol()2339 JSHandle<JSSymbol> ObjectFactory::NewJSSymbol()
2340 {
2341     NewObjectHook();
2342     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2343         JSHClass::Cast(thread_->GlobalConstants()->GetSymbolClass().GetTaggedObject()));
2344     JSHandle<JSSymbol> obj(thread_, JSSymbol::Cast(header));
2345     obj->SetDescription(thread_, JSTaggedValue::Undefined());
2346     obj->SetFlags(0);
2347     obj->SetHashField(SymbolTable::Hash(obj.GetTaggedValue()));
2348     return obj;
2349 }
2350 
NewPrivateSymbol()2351 JSHandle<JSSymbol> ObjectFactory::NewPrivateSymbol()
2352 {
2353     JSHandle<JSSymbol> obj = NewJSSymbol();
2354     obj->SetPrivate();
2355     return obj;
2356 }
2357 
NewPrivateNameSymbol(const JSHandle<JSTaggedValue> & name)2358 JSHandle<JSSymbol> ObjectFactory::NewPrivateNameSymbol(const JSHandle<JSTaggedValue> &name)
2359 {
2360     NewObjectHook();
2361     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2362         JSHClass::Cast(thread_->GlobalConstants()->GetSymbolClass().GetTaggedObject()));
2363     JSHandle<JSSymbol> obj(thread_, JSSymbol::Cast(header));
2364     obj->SetFlags(0);
2365     obj->SetPrivateNameSymbol();
2366     obj->SetDescription(thread_, name);
2367     obj->SetHashField(SymbolTable::Hash(name.GetTaggedValue()));
2368     return obj;
2369 }
2370 
NewWellKnownSymbol(const JSHandle<JSTaggedValue> & name)2371 JSHandle<JSSymbol> ObjectFactory::NewWellKnownSymbol(const JSHandle<JSTaggedValue> &name)
2372 {
2373     NewObjectHook();
2374     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2375         JSHClass::Cast(thread_->GlobalConstants()->GetSymbolClass().GetTaggedObject()));
2376     JSHandle<JSSymbol> obj(thread_, JSSymbol::Cast(header));
2377     obj->SetFlags(0);
2378     obj->SetWellKnownSymbol();
2379     obj->SetDescription(thread_, name);
2380     obj->SetHashField(SymbolTable::Hash(name.GetTaggedValue()));
2381     return obj;
2382 }
2383 
NewPublicSymbol(const JSHandle<JSTaggedValue> & name)2384 JSHandle<JSSymbol> ObjectFactory::NewPublicSymbol(const JSHandle<JSTaggedValue> &name)
2385 {
2386     NewObjectHook();
2387     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2388         JSHClass::Cast(thread_->GlobalConstants()->GetSymbolClass().GetTaggedObject()));
2389     JSHandle<JSSymbol> obj(thread_, JSSymbol::Cast(header));
2390     obj->SetFlags(0);
2391     obj->SetDescription(thread_, name);
2392     obj->SetHashField(SymbolTable::Hash(name.GetTaggedValue()));
2393     return obj;
2394 }
2395 
NewSymbolWithTable(const JSHandle<JSTaggedValue> & name)2396 JSHandle<JSSymbol> ObjectFactory::NewSymbolWithTable(const JSHandle<JSTaggedValue> &name)
2397 {
2398     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
2399     JSHandle<SymbolTable> tableHandle(env->GetRegisterSymbols());
2400     if (tableHandle->ContainsKey(name.GetTaggedValue())) {
2401         JSTaggedValue objValue = tableHandle->GetSymbol(name.GetTaggedValue());
2402         return JSHandle<JSSymbol>(thread_, objValue);
2403     }
2404 
2405     JSHandle<JSSymbol> obj = NewPublicSymbol(name);
2406     JSHandle<JSTaggedValue> valueHandle(obj);
2407     JSHandle<JSTaggedValue> keyHandle(name);
2408     JSHandle<SymbolTable> table = SymbolTable::Insert(thread_, tableHandle, keyHandle, valueHandle);
2409     env->SetRegisterSymbols(thread_, table);
2410     return obj;
2411 }
2412 
NewPrivateNameSymbolWithChar(std::string_view description)2413 JSHandle<JSSymbol> ObjectFactory::NewPrivateNameSymbolWithChar(std::string_view description)
2414 {
2415     JSHandle<EcmaString> string = NewFromUtf8(description);
2416     return NewPrivateNameSymbol(JSHandle<JSTaggedValue>(string));
2417 }
2418 
NewWellKnownSymbolWithChar(std::string_view description)2419 JSHandle<JSSymbol> ObjectFactory::NewWellKnownSymbolWithChar(std::string_view description)
2420 {
2421     JSHandle<EcmaString> string = NewFromUtf8(description);
2422     return NewWellKnownSymbol(JSHandle<JSTaggedValue>(string));
2423 }
2424 
NewPublicSymbolWithChar(std::string_view description)2425 JSHandle<JSSymbol> ObjectFactory::NewPublicSymbolWithChar(std::string_view description)
2426 {
2427     JSHandle<EcmaString> string = NewFromUtf8(description);
2428     return NewPublicSymbol(JSHandle<JSTaggedValue>(string));
2429 }
2430 
NewSymbolWithTableWithChar(std::string_view description)2431 JSHandle<JSSymbol> ObjectFactory::NewSymbolWithTableWithChar(std::string_view description)
2432 {
2433     JSHandle<EcmaString> string = NewFromUtf8(description);
2434     return NewSymbolWithTable(JSHandle<JSTaggedValue>(string));
2435 }
2436 
NewAccessorData()2437 JSHandle<AccessorData> ObjectFactory::NewAccessorData()
2438 {
2439     NewObjectHook();
2440     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2441         JSHClass::Cast(thread_->GlobalConstants()->GetAccessorDataClass().GetTaggedObject()));
2442     JSHandle<AccessorData> acc(thread_, AccessorData::Cast(header));
2443     acc->SetGetter(thread_, JSTaggedValue::Undefined());
2444     acc->SetSetter(thread_, JSTaggedValue::Undefined());
2445     return acc;
2446 }
2447 
NewInternalAccessor(void * setter,void * getter)2448 JSHandle<AccessorData> ObjectFactory::NewInternalAccessor(void *setter, void *getter)
2449 {
2450     NewObjectHook();
2451     TaggedObject *header = heap_->AllocateNonMovableOrHugeObject(
2452         JSHClass::Cast(thread_->GlobalConstants()->GetInternalAccessorClass().GetTaggedObject()));
2453     JSHandle<InternalAccessor> obj(thread_, InternalAccessor::Cast(header));
2454 
2455     obj->SetSetter(reinterpret_cast<InternalAccessor::InternalSetFunc>(setter));
2456     obj->SetGetter(reinterpret_cast<InternalAccessor::InternalGetFunc>(getter));
2457     return JSHandle<AccessorData>::Cast(obj);
2458 }
2459 
NewPromiseCapability()2460 JSHandle<PromiseCapability> ObjectFactory::NewPromiseCapability()
2461 {
2462     NewObjectHook();
2463     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2464         JSHClass::Cast(thread_->GlobalConstants()->GetCapabilityRecordClass().GetTaggedObject()));
2465     JSHandle<PromiseCapability> obj(thread_, header);
2466     obj->SetPromise(thread_, JSTaggedValue::Undefined());
2467     obj->SetResolve(thread_, JSTaggedValue::Undefined());
2468     obj->SetReject(thread_, JSTaggedValue::Undefined());
2469     return obj;
2470 }
2471 
NewPromiseReaction()2472 JSHandle<PromiseReaction> ObjectFactory::NewPromiseReaction()
2473 {
2474     NewObjectHook();
2475     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2476         JSHClass::Cast(thread_->GlobalConstants()->GetReactionsRecordClass().GetTaggedObject()));
2477     JSHandle<PromiseReaction> obj(thread_, header);
2478     obj->SetPromiseCapability(thread_, JSTaggedValue::Undefined());
2479     obj->SetHandler(thread_, JSTaggedValue::Undefined());
2480     obj->SetType(PromiseType::RESOLVE);
2481     return obj;
2482 }
2483 
NewPromiseIteratorRecord(const JSHandle<JSTaggedValue> & itor,bool done)2484 JSHandle<PromiseIteratorRecord> ObjectFactory::NewPromiseIteratorRecord(const JSHandle<JSTaggedValue> &itor, bool done)
2485 {
2486     NewObjectHook();
2487     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2488         JSHClass::Cast(thread_->GlobalConstants()->GetPromiseIteratorRecordClass().GetTaggedObject()));
2489     JSHandle<PromiseIteratorRecord> obj(thread_, header);
2490     obj->SetIterator(thread_, itor.GetTaggedValue());
2491     obj->SetDone(done);
2492     return obj;
2493 }
2494 
NewMicroJobQueue()2495 JSHandle<job::MicroJobQueue> ObjectFactory::NewMicroJobQueue()
2496 {
2497     NewObjectHook();
2498     TaggedObject *header = heap_->AllocateNonMovableOrHugeObject(
2499         JSHClass::Cast(thread_->GlobalConstants()->GetMicroJobQueueClass().GetTaggedObject()));
2500     JSHandle<job::MicroJobQueue> obj(thread_, header);
2501     obj->SetPromiseJobQueue(thread_, GetEmptyTaggedQueue().GetTaggedValue());
2502     obj->SetScriptJobQueue(thread_, GetEmptyTaggedQueue().GetTaggedValue());
2503     return obj;
2504 }
2505 
NewPendingJob(const JSHandle<JSFunction> & func,const JSHandle<TaggedArray> & argv)2506 JSHandle<job::PendingJob> ObjectFactory::NewPendingJob(const JSHandle<JSFunction> &func,
2507                                                        const JSHandle<TaggedArray> &argv)
2508 {
2509     NewObjectHook();
2510     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
2511         JSHClass::Cast(thread_->GlobalConstants()->GetPendingJobClass().GetTaggedObject()));
2512     JSHandle<job::PendingJob> obj(thread_, header);
2513     obj->SetJob(thread_, func.GetTaggedValue());
2514     obj->SetArguments(thread_, argv.GetTaggedValue());
2515 #if defined(ENABLE_HITRACE)
2516     obj->SetChainId(0);
2517     obj->SetSpanId(0);
2518     obj->SetParentSpanId(0);
2519     obj->SetFlags(0);
2520     obj->SetJobId(0);
2521 #endif
2522     return obj;
2523 }
2524 
NewJSProxy(const JSHandle<JSTaggedValue> & target,const JSHandle<JSTaggedValue> & handler)2525 JSHandle<JSProxy> ObjectFactory::NewJSProxy(const JSHandle<JSTaggedValue> &target,
2526                                             const JSHandle<JSTaggedValue> &handler)
2527 {
2528     NewObjectHook();
2529     TaggedObject *header = nullptr;
2530     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
2531     JSHandle<JSObject> emptyObject = OrdinaryNewJSObjectCreate(vm_->GetGlobalEnv()->GetObjectFunctionPrototype());
2532 
2533     if (target->IsCallable()) {
2534         auto jsProxyCallableClass = JSHClass::Cast(globalConst->GetJSProxyCallableClass().GetTaggedObject());
2535         auto jsProxyConstructClass = JSHClass::Cast(globalConst->GetJSProxyConstructClass().GetTaggedObject());
2536         header = target->IsConstructor() ? heap_->AllocateYoungOrHugeObject(jsProxyConstructClass)
2537                                          : heap_->AllocateYoungOrHugeObject(jsProxyCallableClass);
2538     } else {
2539         header = heap_->AllocateYoungOrHugeObject(
2540             JSHClass::Cast(thread_->GlobalConstants()->GetJSProxyOrdinaryClass().GetTaggedObject()));
2541     }
2542 
2543     JSHandle<JSProxy> proxy(thread_, header);
2544     proxy->InitializeHash();
2545     proxy->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_GLOBAL_CALL_JS_PROXY));
2546     proxy->SetTarget(thread_, target.GetTaggedValue());
2547     proxy->SetHandler(thread_, handler.GetTaggedValue());
2548     proxy->SetPrivateField(thread_, emptyObject.GetTaggedValue());
2549     proxy->SetIsRevoked(false);
2550     return proxy;
2551 }
2552 
NewJSRealm()2553 JSHandle<JSRealm> ObjectFactory::NewJSRealm()
2554 {
2555     JSHandle<JSHClass> hClassHandle = NewEcmaHClassClass(nullptr, JSHClass::SIZE, JSType::HCLASS);
2556     JSHClass *hclass = reinterpret_cast<JSHClass *>(hClassHandle.GetTaggedValue().GetTaggedObject());
2557     hclass->SetClass(thread_, hclass);
2558     JSHandle<JSHClass> realmEnvClass = NewEcmaHClass(*hClassHandle, GlobalEnv::SIZE, JSType::GLOBAL_ENV);
2559     JSHandle<GlobalEnv> realmEnvHandle = NewGlobalEnv(*realmEnvClass);
2560 
2561     auto result = TemplateMap::Create(thread_);
2562     realmEnvHandle->SetTemplateMap(thread_, result);
2563     realmEnvHandle->SetJSThread(thread_);
2564     Builtins builtins;
2565     builtins.Initialize(realmEnvHandle, thread_, false, true);
2566     JSHandle<JSTaggedValue> protoValue = thread_->GlobalConstants()->GetHandledJSRealmClass();
2567     JSHandle<JSHClass> hclassHandle = NewEcmaHClass(JSRealm::SIZE, JSType::JS_REALM, protoValue);
2568     JSHandle<JSRealm> realm(NewJSObject(hclassHandle));
2569     realm->SetGlobalEnv(thread_, realmEnvHandle.GetTaggedValue());
2570     realm->SetValue(thread_, JSTaggedValue::Undefined());
2571 
2572     JSHandle<JSTaggedValue> realmObj = realmEnvHandle->GetJSGlobalObject();
2573     JSHandle<JSTaggedValue> realmkey(thread_->GlobalConstants()->GetHandledGlobalString());
2574     PropertyDescriptor realmDesc(thread_, JSHandle<JSTaggedValue>::Cast(realmObj), true, false, true);
2575     [[maybe_unused]] bool status =
2576         JSObject::DefineOwnProperty(thread_, JSHandle<JSObject>::Cast(realm), realmkey, realmDesc);
2577     ASSERT_PRINT(status == true, "Realm defineOwnProperty failed");
2578 
2579     return realm;
2580 }
2581 
NewTaggedArray(uint32_t length,JSTaggedValue initVal,bool nonMovable)2582 JSHandle<TaggedArray> ObjectFactory::NewTaggedArray(uint32_t length, JSTaggedValue initVal, bool nonMovable)
2583 {
2584     if (nonMovable) {
2585         return NewTaggedArray(length, initVal, MemSpaceType::NON_MOVABLE);
2586     }
2587     return NewTaggedArray(length, initVal, MemSpaceType::SEMI_SPACE);
2588 }
2589 
NewTaggedArray(uint32_t length,JSTaggedValue initVal,MemSpaceType spaceType)2590 JSHandle<TaggedArray> ObjectFactory::NewTaggedArray(uint32_t length, JSTaggedValue initVal, MemSpaceType spaceType)
2591 {
2592     NewObjectHook();
2593     if (length == 0) {
2594         return EmptyArray();
2595     }
2596 
2597     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2598     TaggedObject *header = nullptr;
2599     JSHClass *arrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject());
2600     switch (spaceType) {
2601         case MemSpaceType::SEMI_SPACE:
2602             header = heap_->AllocateYoungOrHugeObject(arrayClass, size);
2603             break;
2604         case MemSpaceType::OLD_SPACE:
2605             header = heap_->AllocateOldOrHugeObject(arrayClass, size);
2606             break;
2607         case MemSpaceType::NON_MOVABLE:
2608             header = heap_->AllocateNonMovableOrHugeObject(arrayClass, size);
2609             break;
2610         case MemSpaceType::SHARED_OLD_SPACE:
2611             header = sHeap_->AllocateOldOrHugeObject(thread_, arrayClass, size);
2612             break;
2613         case MemSpaceType::SHARED_NON_MOVABLE:
2614             header = sHeap_->AllocateNonMovableOrHugeObject(thread_, arrayClass, size);
2615             break;
2616         default:
2617             LOG_ECMA(FATAL) << "this branch is unreachable";
2618             UNREACHABLE();
2619     }
2620 
2621     JSHandle<TaggedArray> array(thread_, header);
2622     array->InitializeWithSpecialValue(initVal, length);
2623     return array;
2624 }
2625 
NewAndCopyTaggedArray(JSHandle<TaggedArray> & srcElements,uint32_t newLength,uint32_t oldLength,uint32_t k)2626 JSHandle<TaggedArray> ObjectFactory::NewAndCopyTaggedArray(JSHandle<TaggedArray> &srcElements, uint32_t newLength,
2627                                                            uint32_t oldLength, uint32_t k)
2628 {
2629     ASSERT(oldLength <= newLength);
2630     MemSpaceType spaceType = newLength < LENGTH_THRESHOLD ? MemSpaceType::SEMI_SPACE : MemSpaceType::OLD_SPACE;
2631     JSHandle<TaggedArray> dstElements = NewTaggedArrayWithoutInit(newLength, spaceType);
2632     dstElements->SetExtraLength(srcElements->GetExtraLength());
2633     if (newLength == 0) {
2634         return dstElements;
2635     }
2636     for (uint32_t i = 0; i < oldLength; i++) {
2637         dstElements->Set(thread_, i, srcElements->Get(i + k));
2638     }
2639     for (uint32_t i = oldLength; i < newLength; i++) {
2640         dstElements->Set(thread_, i, JSTaggedValue::Hole());
2641     }
2642     return dstElements;
2643 }
2644 
NewAndCopyTaggedArraySkipBarrier(JSHandle<TaggedArray> & srcElements,uint32_t newLength,uint32_t oldLength,uint32_t k)2645 JSHandle<TaggedArray> ObjectFactory::NewAndCopyTaggedArraySkipBarrier(JSHandle<TaggedArray> &srcElements,
2646     uint32_t newLength, uint32_t oldLength, uint32_t k)
2647 {
2648     ASSERT(oldLength <= newLength);
2649     MemSpaceType spaceType = newLength < LENGTH_THRESHOLD ? MemSpaceType::SEMI_SPACE : MemSpaceType::OLD_SPACE;
2650     JSHandle<TaggedArray> dstElements = NewTaggedArrayWithoutInit(newLength, spaceType);
2651     if (newLength == 0) {
2652         return dstElements;
2653     }
2654     for (uint32_t i = 0; i < oldLength; i++) {
2655         dstElements->Set<false>(thread_, i, srcElements->Get(i + k));
2656     }
2657     for (uint32_t i = oldLength; i < newLength; i++) {
2658         dstElements->Set(thread_, i, JSTaggedValue::Hole());
2659     }
2660     return dstElements;
2661 }
2662 
NewAndCopySNameDictionary(JSHandle<TaggedArray> & srcElements,uint32_t length)2663 JSHandle<TaggedArray> ObjectFactory::NewAndCopySNameDictionary(JSHandle<TaggedArray> &srcElements, uint32_t length)
2664 {
2665     JSHandle<TaggedArray> dstElements = NewSDictionaryArray(length);
2666     if (length == 0) {
2667         return dstElements;
2668     }
2669     for (uint32_t i = 0; i < length; i++) {
2670         dstElements->Set(thread_, i, srcElements->Get(i));
2671     }
2672     return dstElements;
2673 }
2674 
NewAndCopyJSArrayObject(JSHandle<JSObject> thisObjHandle,uint32_t newLength,uint32_t oldLength,uint32_t k)2675 JSHandle<JSObject> ObjectFactory::NewAndCopyJSArrayObject(JSHandle<JSObject> thisObjHandle, uint32_t newLength,
2676                                                           uint32_t oldLength, uint32_t k)
2677 {
2678     ASSERT(oldLength <= newLength);
2679     JSHandle<TaggedArray> dstElements(NewTaggedArray(newLength));
2680     JSHandle<JSTaggedValue> holeHandle(thread_, JSTaggedValue::Hole());
2681     JSHandle<JSObject> arrayObj = JSHandle<JSObject>(NewJSStableArrayWithElements(dstElements));
2682     if (newLength == 0) {
2683         return JSHandle<JSObject>(arrayObj);
2684     }
2685     for (uint32_t i = 0; i < oldLength; i++) {
2686         JSHandle<JSTaggedValue> value(thread_, ElementAccessor::Get(thisObjHandle, i + k));
2687         ElementAccessor::Set(thread_, arrayObj, i, value, true);
2688     }
2689     for (uint32_t i = oldLength; i < newLength; i++) {
2690         ElementAccessor::Set(thread_, arrayObj, i, holeHandle, true);
2691     }
2692     return arrayObj;
2693 }
2694 
NewAndCopyTaggedArrayByObject(JSHandle<JSObject> thisObjHandle,uint32_t newLength,uint32_t oldLength,uint32_t k)2695 JSHandle<TaggedArray> ObjectFactory::NewAndCopyTaggedArrayByObject(JSHandle<JSObject> thisObjHandle, uint32_t newLength,
2696                                                                    uint32_t oldLength, uint32_t k)
2697 {
2698     ASSERT(oldLength <= newLength);
2699     MemSpaceType spaceType = newLength < LENGTH_THRESHOLD ? MemSpaceType::SEMI_SPACE : MemSpaceType::OLD_SPACE;
2700     JSHandle<TaggedArray> dstElements(NewTaggedArrayWithoutInit(newLength, spaceType));
2701     TaggedArray *srcElements = TaggedArray::Cast(thisObjHandle->GetElements().GetTaggedObject());
2702     dstElements->SetExtraLength(srcElements->GetExtraLength());
2703     if (newLength == 0) {
2704         return dstElements;
2705     }
2706 
2707     for (uint32_t i = 0; i < oldLength; i++) {
2708         dstElements->Set(thread_, i, ElementAccessor::Get(thisObjHandle, i + k));
2709     }
2710     for (uint32_t i = oldLength; i < newLength; i++) {
2711         dstElements->Set(thread_, i, JSTaggedValue::Hole());
2712     }
2713     return dstElements;
2714 }
2715 
NewAndCopyMutantTaggedArrayByObject(JSHandle<JSObject> thisObjHandle,uint32_t newLength,uint32_t oldLength,uint32_t k)2716 JSHandle<MutantTaggedArray> ObjectFactory::NewAndCopyMutantTaggedArrayByObject(JSHandle<JSObject> thisObjHandle,
2717                                                                                uint32_t newLength, uint32_t oldLength,
2718                                                                                uint32_t k)
2719 {
2720     ASSERT(oldLength <= newLength);
2721     MemSpaceType spaceType = newLength < LENGTH_THRESHOLD ? MemSpaceType::SEMI_SPACE : MemSpaceType::OLD_SPACE;
2722     JSHandle<MutantTaggedArray> dstElements(NewMutantTaggedArrayWithoutInit(newLength, spaceType));
2723     MutantTaggedArray *srcElements = MutantTaggedArray::Cast(thisObjHandle->GetElements().GetTaggedObject());
2724     dstElements->SetExtraLength(srcElements->GetExtraLength());
2725     if (newLength == 0) {
2726         return dstElements;
2727     }
2728     for (uint32_t i = 0; i < oldLength; i++) {
2729         ElementsKind kind = thisObjHandle->GetClass()->GetElementsKind();
2730         JSTaggedValue value = JSTaggedValue(ElementAccessor::ConvertTaggedValueWithElementsKind(
2731             ElementAccessor::Get(thisObjHandle, i + k), kind));
2732         dstElements->Set<false>(thread_, i, value);
2733     }
2734     for (uint32_t i = oldLength; i < newLength; i++) {
2735         ElementsKind kind = thisObjHandle->GetClass()->GetElementsKind();
2736         JSTaggedValue value = JSTaggedValue(ElementAccessor::ConvertTaggedValueWithElementsKind(JSTaggedValue::Hole(),
2737                                                                                                 kind));
2738         dstElements->Set<false>(thread_, i, value);
2739     }
2740     return dstElements;
2741 }
2742 
2743 // private
NewTaggedArrayWithoutInit(uint32_t length,MemSpaceType spaceType)2744 JSHandle<TaggedArray> ObjectFactory::NewTaggedArrayWithoutInit(uint32_t length, MemSpaceType spaceType)
2745 {
2746     NewObjectHook();
2747     if (length == 0) {
2748         return EmptyArray();
2749     }
2750 
2751     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2752     TaggedObject *header = nullptr;
2753     auto arrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject());
2754     switch (spaceType) {
2755         case MemSpaceType::SEMI_SPACE:
2756             header = heap_->AllocateYoungOrHugeObject(arrayClass, size);
2757             break;
2758         case MemSpaceType::OLD_SPACE:
2759             header = heap_->AllocateOldOrHugeObject(arrayClass, size);
2760             break;
2761         case MemSpaceType::SHARED_OLD_SPACE:
2762             header = sHeap_->AllocateOldOrHugeObject(thread_, arrayClass, size);
2763             break;
2764         default:
2765             LOG_ECMA(FATAL) << "this branch is unreachable";
2766             UNREACHABLE();
2767     }
2768     JSHandle<TaggedArray> array(thread_, header);
2769     array->SetLength(length);
2770     return array;
2771 }
2772 
2773 // private
NewMutantTaggedArrayWithoutInit(uint32_t length,MemSpaceType spaceType)2774 JSHandle<MutantTaggedArray> ObjectFactory::NewMutantTaggedArrayWithoutInit(uint32_t length, MemSpaceType spaceType)
2775 {
2776     NewObjectHook();
2777     if (length == 0) {
2778         return EmptyMutantArray();
2779     }
2780 
2781     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2782     TaggedObject *header = nullptr;
2783     auto arrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetMutantTaggedArrayClass().GetTaggedObject());
2784     switch (spaceType) {
2785         case MemSpaceType::SEMI_SPACE:
2786             header = heap_->AllocateYoungOrHugeObject(arrayClass, size);
2787             break;
2788         case MemSpaceType::OLD_SPACE:
2789             header = heap_->AllocateOldOrHugeObject(arrayClass, size);
2790             break;
2791         default:
2792             LOG_ECMA(FATAL) << "this branch is unreachable";
2793             UNREACHABLE();
2794     }
2795     JSHandle<MutantTaggedArray> array(thread_, header);
2796     array->SetLength(length);
2797     return array;
2798 }
2799 
NewTaggedArray(uint32_t length,JSTaggedValue initVal)2800 JSHandle<TaggedArray> ObjectFactory::NewTaggedArray(uint32_t length, JSTaggedValue initVal)
2801 {
2802     NewObjectHook();
2803     if (length == 0) {
2804         return EmptyArray();
2805     }
2806     MemSpaceType spaceType = length < LENGTH_THRESHOLD ? MemSpaceType::SEMI_SPACE : MemSpaceType::OLD_SPACE;
2807     JSHandle<TaggedArray> array = NewTaggedArrayWithoutInit(length, spaceType);
2808     array->InitializeWithSpecialValue(initVal, length);
2809     return array;
2810 }
2811 
NewCOWTaggedArray(uint32_t length,JSTaggedValue initVal)2812 JSHandle<COWTaggedArray> ObjectFactory::NewCOWTaggedArray(uint32_t length, JSTaggedValue initVal)
2813 {
2814     NewObjectHook();
2815     ASSERT(length > 0);
2816 
2817     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2818     auto header = heap_->AllocateNonMovableOrHugeObject(
2819         JSHClass::Cast(thread_->GlobalConstants()->GetCOWArrayClass().GetTaggedObject()), size);
2820     JSHandle<COWTaggedArray> cowArray(thread_, header);
2821     cowArray->InitializeWithSpecialValue(initVal, length);
2822     return cowArray;
2823 }
2824 
NewCOWMutantTaggedArray(uint32_t length,JSTaggedType initVal)2825 JSHandle<COWMutantTaggedArray> ObjectFactory::NewCOWMutantTaggedArray(uint32_t length, JSTaggedType initVal)
2826 {
2827     NewObjectHook();
2828     ASSERT(length > 0);
2829 
2830     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2831     auto header = heap_->AllocateNonMovableOrHugeObject(
2832         JSHClass::Cast(thread_->GlobalConstants()->GetCOWMutantTaggedArrayClass().GetTaggedObject()), size);
2833     JSHandle<COWMutantTaggedArray> cowMutantTaggedArray(thread_, header);
2834     cowMutantTaggedArray->InitializeWithSpecialValue(initVal, length);
2835     return cowMutantTaggedArray;
2836 }
2837 
NewMutantTaggedArray(uint32_t length,JSTaggedType initVal)2838 JSHandle<MutantTaggedArray> ObjectFactory::NewMutantTaggedArray(uint32_t length, JSTaggedType initVal)
2839 {
2840     NewObjectHook();
2841     ASSERT(length > 0);
2842 
2843     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2844     auto header = heap_->AllocateYoungOrHugeObject(
2845         JSHClass::Cast(thread_->GlobalConstants()->GetMutantTaggedArrayClass().GetTaggedObject()), size);
2846     JSHandle<MutantTaggedArray> mutantTaggedArray(thread_, header);
2847     mutantTaggedArray->InitializeWithSpecialValue(initVal, length);
2848     return mutantTaggedArray;
2849 }
2850 
NewTaggedHashArray(uint32_t length)2851 JSHandle<TaggedHashArray> ObjectFactory::NewTaggedHashArray(uint32_t length)
2852 {
2853     if (length == 0) {
2854         return JSHandle<TaggedHashArray>::Cast(EmptyArray());
2855     }
2856 
2857     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2858     auto header = heap_->AllocateYoungOrHugeObject(
2859         JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject()), size);
2860     JSHandle<TaggedHashArray> array(thread_, header);
2861     array->InitializeWithSpecialValue(JSTaggedValue::Hole(), length);
2862     return array;
2863 }
2864 
NewByteArray(uint32_t length,uint32_t size,void * srcData,MemSpaceType spaceType)2865 JSHandle<ByteArray> ObjectFactory::NewByteArray(uint32_t length, uint32_t size, void *srcData,
2866                                                 MemSpaceType spaceType)
2867 {
2868     size_t byteSize = ByteArray::ComputeSize(size, length);
2869     JSHClass *arrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetByteArrayClass().GetTaggedObject());
2870     TaggedObject *header = AllocObjectWithSpaceType(byteSize, arrayClass, spaceType);
2871     JSHandle<ByteArray> array(thread_, header);
2872 
2873     void *data = array->GetData();
2874 
2875     if (srcData != nullptr) {
2876         if (memcpy_s(data, length * size, srcData, length * size) != EOK) {
2877             LOG_FULL(FATAL) << "memcpy_s failed";
2878             UNREACHABLE();
2879         }
2880     } else {
2881         if (memset_s(data, length * size, 0, length * size) != EOK) {
2882             LOG_FULL(FATAL) << "memset_s failed";
2883             UNREACHABLE();
2884         }
2885     }
2886 
2887     array->SetArrayLength(length);
2888     array->SetByteLength(size);
2889     return array;
2890 }
2891 
NewLinkedNode(int hash,const JSHandle<JSTaggedValue> & key,const JSHandle<JSTaggedValue> & value,const JSHandle<LinkedNode> & next)2892 JSHandle<LinkedNode> ObjectFactory::NewLinkedNode(int hash, const JSHandle<JSTaggedValue> &key,
2893                                                   const JSHandle<JSTaggedValue> &value,
2894                                                   const JSHandle<LinkedNode> &next)
2895 {
2896     NewObjectHook();
2897     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
2898     auto header = heap_->AllocateYoungOrHugeObject(
2899         JSHClass::Cast(globalConst->GetLinkedNode().GetTaggedObject()), LinkedNode::SIZE);
2900     JSHandle<LinkedNode> node(thread_, header);
2901     node->InitLinkedNode(thread_, hash, key, value, next);
2902 
2903     return node;
2904 }
2905 
NewTreeNode(int hash,const JSHandle<JSTaggedValue> & key,const JSHandle<JSTaggedValue> & value)2906 JSHandle<RBTreeNode> ObjectFactory::NewTreeNode(int hash, const JSHandle<JSTaggedValue> &key,
2907                                                 const JSHandle<JSTaggedValue> &value)
2908 {
2909     NewObjectHook();
2910     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
2911     auto header = heap_->AllocateYoungOrHugeObject(
2912         JSHClass::Cast(globalConst->GetRBTreeNode().GetTaggedObject()), RBTreeNode::SIZE);
2913     JSHandle<RBTreeNode> treenode(thread_, header);
2914     treenode->InitRBTreeNode(thread_, hash, key, value, 1);
2915     return treenode;
2916 }
2917 
NewDictionaryArray(uint32_t length)2918 JSHandle<TaggedArray> ObjectFactory::NewDictionaryArray(uint32_t length)
2919 {
2920     NewObjectHook();
2921     ASSERT(length > 0);
2922 
2923     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2924     auto header = heap_->AllocateYoungOrHugeObject(
2925         JSHClass::Cast(thread_->GlobalConstants()->GetDictionaryClass().GetTaggedObject()), size);
2926     JSHandle<TaggedArray> array(thread_, header);
2927     array->InitializeWithSpecialValue(JSTaggedValue::Undefined(), length);
2928 
2929     return array;
2930 }
2931 
ExtendArray(const JSHandle<TaggedArray> & old,uint32_t length,JSTaggedValue initVal,MemSpaceType type,ElementsKind kind)2932 JSHandle<TaggedArray> ObjectFactory::ExtendArray(const JSHandle<TaggedArray> &old, uint32_t length,
2933                                                  JSTaggedValue initVal, MemSpaceType type,
2934                                                  [[maybe_unused]] ElementsKind kind)
2935 {
2936     ASSERT(length >= old->GetLength());
2937     NewObjectHook();
2938     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length);
2939     JSHClass *arrayClass = nullptr;
2940     // If old element is Mutantarray, need conversion according to kind.
2941     if (old->GetClass()->IsMutantTaggedArray()) {
2942         arrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetMutantTaggedArrayClass().GetTaggedObject());
2943     } else {
2944         arrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject());
2945     }
2946     TaggedObject *header = AllocObjectWithSpaceType(size, arrayClass, type);
2947     JSHandle<TaggedArray> newArray(thread_, header);
2948     newArray->SetLength(length);
2949     newArray->SetExtraLength(old->GetExtraLength());
2950 
2951     uint32_t oldLength = old->GetLength();
2952     uint32_t index = 0;
2953     auto isMutantTaggedArray = old->GetClass()->IsMutantTaggedArray();
2954     for (; index < oldLength; ++index) {
2955         if (isMutantTaggedArray) {
2956             newArray->Set<false>(thread_, index, old->Get(index));
2957         } else {
2958             newArray->Set(thread_, index, old->Get(index));
2959         }
2960     }
2961     auto isSpecialHole = initVal.IsHole() && isMutantTaggedArray;
2962     JSTaggedValue specialHole = JSTaggedValue(base::SPECIAL_HOLE);
2963     for (; index < length; ++index) {
2964         if (isSpecialHole) {
2965             newArray->Set<false>(thread_, index, specialHole);
2966         } else {
2967             newArray->Set(thread_, index, initVal);
2968         }
2969     }
2970 
2971     return newArray;
2972 }
2973 
CopyPartArray(const JSHandle<TaggedArray> & old,uint32_t start,uint32_t end)2974 JSHandle<TaggedArray> ObjectFactory::CopyPartArray(const JSHandle<TaggedArray> &old, uint32_t start,
2975                                                    uint32_t end)
2976 {
2977     ASSERT(start <= end);
2978     ASSERT(end <= old->GetLength());
2979 
2980     uint32_t newLength = end - start;
2981     if (newLength == 0) {
2982         return EmptyArray();
2983     }
2984 
2985     NewObjectHook();
2986     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), newLength);
2987     auto header = heap_->AllocateYoungOrHugeObject(
2988         JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject()), size);
2989     JSHandle<TaggedArray> newArray(thread_, header);
2990     newArray->InitializeWithSpecialValue(JSTaggedValue::Hole(), newLength, old->GetExtraLength());
2991 
2992     for (uint32_t i = 0; i < newLength; i++) {
2993         JSTaggedValue value = old->Get(i + start);
2994         if (value.IsHole()) {
2995             break;
2996         }
2997         newArray->Set(thread_, i, value);
2998     }
2999     return newArray;
3000 }
3001 
CopyArray(const JSHandle<TaggedArray> & old,uint32_t oldLength,uint32_t newLength,JSTaggedValue initVal,MemSpaceType type,ElementsKind kind)3002 JSHandle<TaggedArray> ObjectFactory::CopyArray(const JSHandle<TaggedArray> &old, uint32_t oldLength, uint32_t newLength,
3003                                                JSTaggedValue initVal, MemSpaceType type, ElementsKind kind)
3004 {
3005     if (newLength == 0) {
3006         return EmptyArray();
3007     }
3008     if (newLength > oldLength) {
3009         return ExtendArray(old, newLength, initVal, type, kind);
3010     }
3011     NewObjectHook();
3012     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), newLength);
3013     TaggedObject *header = nullptr;
3014     if (type == MemSpaceType::NON_MOVABLE) {
3015         // COW array is shared in nonmovable space.
3016         JSHClass *cowArrayClass = nullptr;
3017         if (old->GetClass()->IsMutantTaggedArray()) {
3018             cowArrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetCOWMutantTaggedArrayClass()
3019                                            .GetTaggedObject());
3020         } else {
3021             cowArrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetCOWArrayClass().GetTaggedObject());
3022         }
3023         header = AllocObjectWithSpaceType(size, cowArrayClass, type);
3024     } else {
3025         JSHClass *arrayClass = nullptr;
3026         if (old->GetClass()->IsMutantTaggedArray()) {
3027             arrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetMutantTaggedArrayClass().GetTaggedObject());
3028         } else {
3029             arrayClass = JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject());
3030         }
3031         header = AllocObjectWithSpaceType(size, arrayClass, type);
3032     }
3033 
3034     JSHandle<TaggedArray> newArray(thread_, header);
3035     newArray->SetLength(newLength);
3036     newArray->SetExtraLength(old->GetExtraLength());
3037 
3038     for (uint32_t i = 0; i < newLength; i++) {
3039         JSTaggedValue value = old->Get(i);
3040         if (old->GetClass()->IsMutantTaggedArray()) {
3041             newArray->Set<false>(thread_, i, value);
3042         } else {
3043             newArray->Set(thread_, i, value);
3044         }
3045     }
3046 
3047     return newArray;
3048 }
3049 
CopyFromEnumCache(const JSHandle<TaggedArray> & old)3050 JSHandle<TaggedArray> ObjectFactory::CopyFromEnumCache(const JSHandle<TaggedArray> &old)
3051 {
3052     NewObjectHook();
3053     uint32_t oldLength = old->GetLength();
3054     uint32_t newLength = oldLength - EnumCache::ENUM_CACHE_HEADER_SIZE;
3055     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), newLength);
3056     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
3057         JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject()), size);
3058     JSHandle<TaggedArray> newArray(thread_, header);
3059     newArray->SetLength(newLength);
3060     newArray->SetExtraLength(old->GetExtraLength());
3061 
3062     for (uint32_t i = 0; i < newLength; i++) {
3063         JSTaggedValue value = old->Get(i + EnumCache::ENUM_CACHE_HEADER_SIZE);
3064         newArray->Set(thread_, i, value);
3065     }
3066     return newArray;
3067 }
3068 
CreateLayoutInfo(int properties,MemSpaceType type,GrowMode mode)3069 JSHandle<LayoutInfo> ObjectFactory::CreateLayoutInfo(int properties, MemSpaceType type, GrowMode mode)
3070 {
3071     int growLength =
3072         mode == GrowMode::GROW ? static_cast<int>(LayoutInfo::ComputeGrowCapacity(properties)) : properties;
3073     uint32_t arrayLength = LayoutInfo::ComputeArrayLength(growLength);
3074     JSHandle<LayoutInfo> layoutInfoHandle = JSHandle<LayoutInfo>::Cast(NewTaggedArrayWithoutInit(arrayLength, type));
3075     layoutInfoHandle->Initialize(thread_);
3076     return layoutInfoHandle;
3077 }
3078 
ExtendLayoutInfo(const JSHandle<LayoutInfo> & old,int properties)3079 JSHandle<LayoutInfo> ObjectFactory::ExtendLayoutInfo(const JSHandle<LayoutInfo> &old, int properties)
3080 {
3081     ASSERT(properties >= old->NumberOfElements());
3082     uint32_t arrayLength = LayoutInfo::ComputeArrayLength(LayoutInfo::ComputeGrowCapacity(properties));
3083     ASSERT(arrayLength > old->GetLength());
3084 
3085     auto oldArray = JSHandle<TaggedArray>(old);
3086     auto newArray = NewTaggedArrayWithoutInit(arrayLength, MemSpaceType::SEMI_SPACE);
3087     JSHandle<LayoutInfo>::Cast(newArray)->Initialize(thread_, oldArray->GetExtraLength());
3088 
3089     uint32_t oldLength = old->GetLength();
3090     for (uint32_t i = 0; i < oldLength; i++) {
3091         JSTaggedValue value = oldArray->Get(i);
3092         newArray->Set(thread_, i, value);
3093     }
3094     return JSHandle<LayoutInfo>::Cast(newArray);
3095 }
3096 
CopyLayoutInfo(const JSHandle<LayoutInfo> & old)3097 JSHandle<LayoutInfo> ObjectFactory::CopyLayoutInfo(const JSHandle<LayoutInfo> &old)
3098 {
3099     uint32_t newLength = old->GetLength();
3100     return JSHandle<LayoutInfo>(CopyArray(JSHandle<TaggedArray>::Cast(old), newLength, newLength));
3101 }
3102 
CopyAndReSort(const JSHandle<LayoutInfo> & old,int end,int capacity)3103 JSHandle<LayoutInfo> ObjectFactory::CopyAndReSort(const JSHandle<LayoutInfo> &old, int end, int capacity)
3104 {
3105     ASSERT(capacity >= end);
3106     JSHandle<LayoutInfo> newArr = CreateLayoutInfo(capacity);
3107     Span<struct Properties> sp(old->GetProperties(), end);
3108     for (int i = 0; i < end; i++) {
3109         newArr->AddKey(thread_, i, sp[i].key_, PropertyAttributes(sp[i].attr_));
3110     }
3111 
3112     return newArr;
3113 }
3114 
NewConstantPool(uint32_t capacity)3115 JSHandle<ConstantPool> ObjectFactory::NewConstantPool(uint32_t capacity)
3116 {
3117     NewObjectHook();
3118     size_t size = ConstantPool::ComputeSize(capacity);
3119     auto header = heap_->AllocateOldOrHugeObject(
3120         JSHClass::Cast(thread_->GlobalConstants()->GetConstantPoolClass().GetTaggedObject()), size);
3121     JSHandle<ConstantPool> array(thread_, header);
3122     array->InitializeWithSpecialValue(thread_, JSTaggedValue::Hole(), capacity);
3123     return array;
3124 }
3125 
NewProgram()3126 JSHandle<Program> ObjectFactory::NewProgram()
3127 {
3128     NewObjectHook();
3129     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
3130         JSHClass::Cast(thread_->GlobalConstants()->GetProgramClass().GetTaggedObject()));
3131     JSHandle<Program> p(thread_, header);
3132     p->InitializeHash();
3133     p->SetMainFunction(thread_, JSTaggedValue::Undefined());
3134     return p;
3135 }
3136 
NewModuleNamespace()3137 JSHandle<ModuleNamespace> ObjectFactory::NewModuleNamespace()
3138 {
3139     NewObjectHook();
3140     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3141     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetModuleNamespaceClass());
3142     JSHandle<JSObject> obj = NewJSObject(hclass);
3143 
3144     JSHandle<ModuleNamespace> moduleNamespace = JSHandle<ModuleNamespace>::Cast(obj);
3145     moduleNamespace->SetModule(thread_, JSTaggedValue::Undefined());
3146     moduleNamespace->SetExports(thread_, JSTaggedValue::Undefined());
3147     moduleNamespace->SetDeregisterProcession(thread_, JSTaggedValue::Undefined());
3148     return moduleNamespace;
3149 }
3150 
NewNativeModuleFailureInfo()3151 JSHandle<NativeModuleFailureInfo> ObjectFactory::NewNativeModuleFailureInfo()
3152 {
3153     NewObjectHook();
3154     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3155     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetNativeModuleFailureInfoClass());
3156     JSHandle<JSObject> obj = NewJSObject(hclass);
3157 
3158     JSHandle<NativeModuleFailureInfo> nativeModuleFailureInfo = JSHandle<NativeModuleFailureInfo>::Cast(obj);
3159     nativeModuleFailureInfo->SetArkNativeModuleFailureInfo(thread_, JSTaggedValue::Undefined());
3160     return nativeModuleFailureInfo;
3161 }
3162 
NewCjsModule()3163 JSHandle<CjsModule> ObjectFactory::NewCjsModule()
3164 {
3165     NewObjectHook();
3166     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3167     JSHandle<JSFunction> moduleObj(env->GetCjsModuleFunction());
3168     JSHandle<CjsModule> cjsModule = JSHandle<CjsModule>(NewJSObjectByConstructor(moduleObj));
3169     return cjsModule;
3170 }
3171 
NewCjsExports()3172 JSHandle<CjsExports> ObjectFactory::NewCjsExports()
3173 {
3174     NewObjectHook();
3175     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3176     JSHandle<JSFunction> exportsObj(env->GetCjsExportsFunction());
3177     JSHandle<CjsExports> cjsExports = JSHandle<CjsExports>(NewJSObjectByConstructor(exportsObj));
3178     return cjsExports;
3179 }
3180 
NewCjsRequire()3181 JSHandle<CjsRequire> ObjectFactory::NewCjsRequire()
3182 {
3183     NewObjectHook();
3184     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3185     JSHandle<JSFunction> requireObj(env->GetCjsRequireFunction());
3186     JSHandle<CjsRequire> cjsRequire = JSHandle<CjsRequire>(NewJSObjectByConstructor(requireObj));
3187     return cjsRequire;
3188 }
3189 
GetEmptyString() const3190 JSHandle<EcmaString> ObjectFactory::GetEmptyString() const
3191 {
3192     return JSHandle<EcmaString>(thread_->GlobalConstants()->GetHandledEmptyString());
3193 }
3194 
EmptyArray() const3195 JSHandle<TaggedArray> ObjectFactory::EmptyArray() const
3196 {
3197     return JSHandle<TaggedArray>(thread_->GlobalConstants()->GetHandledEmptyArray());
3198 }
3199 
EmptyMutantArray() const3200 JSHandle<MutantTaggedArray> ObjectFactory::EmptyMutantArray() const
3201 {
3202     return JSHandle<MutantTaggedArray>(thread_->GlobalConstants()->GetHandledEmptyArray());
3203 }
3204 
GetStringFromStringTable(const uint8_t * utf8Data,uint32_t utf8Len,bool canBeCompress) const3205 JSHandle<EcmaString> ObjectFactory::GetStringFromStringTable(const uint8_t *utf8Data, uint32_t utf8Len,
3206                                                              bool canBeCompress) const
3207 {
3208     NewObjectHook();
3209     if (utf8Len == 0) {
3210         return GetEmptyString();
3211     }
3212     auto stringTable = vm_->GetEcmaStringTable();
3213     return JSHandle<EcmaString>(thread_, stringTable->GetOrInternString(vm_, utf8Data, utf8Len, canBeCompress));
3214 }
3215 
GetCompressedSubStringFromStringTable(const JSHandle<EcmaString> & string,uint32_t offset,uint32_t utf8Len) const3216 JSHandle<EcmaString> ObjectFactory::GetCompressedSubStringFromStringTable(const JSHandle<EcmaString> &string,
3217                                                                           uint32_t offset, uint32_t utf8Len) const
3218 {
3219     NewObjectHook();
3220     if (UNLIKELY(utf8Len == 0)) {
3221         return GetEmptyString();
3222     }
3223     auto *stringTable = vm_->GetEcmaStringTable();
3224     return JSHandle<EcmaString>(thread_, stringTable->GetOrInternCompressedSubString(vm_, string, offset, utf8Len));
3225 }
3226 
GetStringFromStringTableNonMovable(const uint8_t * utf8Data,uint32_t utf8Len) const3227 JSHandle<EcmaString> ObjectFactory::GetStringFromStringTableNonMovable(const uint8_t *utf8Data, uint32_t utf8Len) const
3228 {
3229     NewObjectHook();
3230     if (utf8Len == 0) {
3231         return GetEmptyString();
3232     }
3233     auto stringTable = vm_->GetEcmaStringTable();
3234     return JSHandle<EcmaString>(thread_, stringTable->CreateAndInternStringNonMovable(vm_, utf8Data, utf8Len));
3235 }
3236 
GetStringFromStringTableReadOnly(const uint8_t * utf8Data,uint32_t utf8Len,bool canBeCompress) const3237 JSHandle<EcmaString> ObjectFactory::GetStringFromStringTableReadOnly(const uint8_t *utf8Data, uint32_t utf8Len,
3238                                                                      bool canBeCompress) const
3239 {
3240     NewObjectHook();
3241     if (utf8Len == 0) {
3242         return GetEmptyString();
3243     }
3244     auto stringTable = vm_->GetEcmaStringTable();
3245     return JSHandle<EcmaString>(thread_, stringTable->CreateAndInternStringReadOnly(vm_, utf8Data, utf8Len,
3246                                                                                     canBeCompress));
3247 }
3248 
GetStringFromStringTable(const uint16_t * utf16Data,uint32_t utf16Len,bool canBeCompress) const3249 JSHandle<EcmaString> ObjectFactory::GetStringFromStringTable(const uint16_t *utf16Data, uint32_t utf16Len,
3250                                                              bool canBeCompress) const
3251 {
3252     NewObjectHook();
3253     if (utf16Len == 0) {
3254         return GetEmptyString();
3255     }
3256     auto stringTable = vm_->GetEcmaStringTable();
3257     return JSHandle<EcmaString>(thread_, stringTable->GetOrInternString(vm_, utf16Data, utf16Len, canBeCompress));
3258 }
3259 
GetStringFromStringTable(EcmaString * string) const3260 JSHandle<EcmaString> ObjectFactory::GetStringFromStringTable(EcmaString *string) const
3261 {
3262     ASSERT(string != nullptr);
3263     if (EcmaStringAccessor(string).GetLength() == 0) {
3264         return GetEmptyString();
3265     }
3266     auto stringTable = vm_->GetEcmaStringTable();
3267     return JSHandle<EcmaString>(thread_, stringTable->GetOrInternString(vm_, string));
3268 }
3269 
3270 // NB! don't do special case for C0 80, it means '\u0000', so don't convert to UTF-8
GetRawStringFromStringTable(StringData sd,MemSpaceType type,bool isConstantString,uint32_t idOffset) const3271 EcmaString *ObjectFactory::GetRawStringFromStringTable(StringData sd, MemSpaceType type, bool isConstantString,
3272     uint32_t idOffset) const
3273 {
3274     NewObjectHook();
3275     uint32_t utf16Len = sd.utf16_length;
3276     if (UNLIKELY(utf16Len == 0)) {
3277         return *GetEmptyString();
3278     }
3279 
3280     bool canBeCompressed = sd.is_ascii;
3281     const uint8_t *mutf8Data = sd.data;
3282     if (canBeCompressed) {
3283         // This branch will use constant string, which has a pointer at the string in the pandafile.
3284         return vm_->GetEcmaStringTable()->GetOrInternStringWithSpaceType(vm_, mutf8Data, utf16Len, true, type,
3285                                                                          isConstantString, idOffset);
3286     }
3287     return vm_->GetEcmaStringTable()->GetOrInternStringWithSpaceType(vm_, mutf8Data, utf16Len, type);
3288 }
3289 
3290 // used in jit thread, which unsupport create jshandle
GetRawStringFromStringTableWithoutJSHandle(StringData sd,MemSpaceType type,bool isConstantString,uint32_t idOffset) const3291 EcmaString *ObjectFactory::GetRawStringFromStringTableWithoutJSHandle(StringData sd, MemSpaceType type,
3292     bool isConstantString, uint32_t idOffset) const
3293 {
3294     NewObjectHook();
3295     uint32_t utf16Len = sd.utf16_length;
3296     if (UNLIKELY(utf16Len == 0)) {
3297         return *GetEmptyString();
3298     }
3299 
3300     bool canBeCompressed = sd.is_ascii;
3301     const uint8_t *mutf8Data = sd.data;
3302     if (canBeCompressed) {
3303         // This branch will use constant string, which has a pointer at the string in the pandafile.
3304         return vm_->GetEcmaStringTable()->GetOrInternStringWithSpaceType(vm_, mutf8Data, utf16Len, true, type,
3305                                                                          isConstantString, idOffset);
3306     }
3307     return vm_->GetEcmaStringTable()->GetOrInternStringWithSpaceTypeWithoutJSHandle(vm_, mutf8Data, utf16Len, type);
3308 }
3309 
NewPropertyBox(const JSHandle<JSTaggedValue> & value)3310 JSHandle<PropertyBox> ObjectFactory::NewPropertyBox(const JSHandle<JSTaggedValue> &value)
3311 {
3312     NewObjectHook();
3313     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
3314         JSHClass::Cast(thread_->GlobalConstants()->GetPropertyBoxClass().GetTaggedObject()));
3315     JSHandle<PropertyBox> box(thread_, header);
3316     box->SetValue(thread_, value);
3317     return box;
3318 }
3319 
NewProtoChangeMarker()3320 JSHandle<ProtoChangeMarker> ObjectFactory::NewProtoChangeMarker()
3321 {
3322     NewObjectHook();
3323     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
3324         JSHClass::Cast(thread_->GlobalConstants()->GetProtoChangeMarkerClass().GetTaggedObject()));
3325     JSHandle<ProtoChangeMarker> marker(thread_, header);
3326     marker->ClearBitField();
3327     return marker;
3328 }
3329 
NewMarkerCell()3330 JSHandle<MarkerCell> ObjectFactory::NewMarkerCell()
3331 {
3332     NewObjectHook();
3333     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
3334         JSHClass::Cast(thread_->GlobalConstants()->GetMarkerCellClass().GetTaggedObject()));
3335     JSHandle<MarkerCell> marker(thread_, header);
3336     marker->ClearBitField();
3337     return marker;
3338 }
3339 
NewProtoChangeDetails()3340 JSHandle<ProtoChangeDetails> ObjectFactory::NewProtoChangeDetails()
3341 {
3342     NewObjectHook();
3343     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
3344         JSHClass::Cast(thread_->GlobalConstants()->GetProtoChangeDetailsClass().GetTaggedObject()));
3345     JSHandle<ProtoChangeDetails> protoInfo(thread_, header);
3346     protoInfo->SetChangeListener(thread_, JSTaggedValue::Undefined());
3347     protoInfo->SetRegisterIndex(ProtoChangeDetails::UNREGISTERED);
3348     return protoInfo;
3349 }
3350 
NewProfileTypeInfo(uint32_t icSlotSize)3351 JSHandle<ProfileTypeInfo> ObjectFactory::NewProfileTypeInfo(uint32_t icSlotSize)
3352 {
3353     NewObjectHook();
3354     ASSERT(icSlotSize > 0);
3355     size_t size = ProfileTypeInfo::ComputeSize(icSlotSize);
3356     auto header = heap_->AllocateYoungOrHugeObject(
3357         JSHClass::Cast(thread_->GlobalConstants()->GetProfileTypeInfoClass().GetTaggedObject()), size);
3358     JSHandle<ProfileTypeInfo> array(thread_, header);
3359     array->InitializeWithSpecialValue(JSTaggedValue::Undefined(), icSlotSize);
3360     if (vm_->IsEnableFastJit()) {
3361         uint16_t threshold = vm_->GetJSOptions().GetJitHotnessThreshold();
3362         ASSERT(threshold != ProfileTypeInfo::JIT_DISABLE_FLAG);
3363         array->SetJitHotnessThreshold(threshold);
3364         threshold = vm_->GetJSOptions().GetOsrHotnessThreshold();
3365         array->SetOsrHotnessThreshold(threshold);
3366         uint8_t jitCallThreshold = vm_->GetJSOptions().GetJitCallThreshold();
3367         array->SetJitCallThreshold(jitCallThreshold);
3368     }
3369     if (vm_->IsEnableBaselineJit()) {
3370         uint16_t threshold = vm_->GetJSOptions().GetBaselineJitHotnessThreshold();
3371         array->SetBaselineJitHotnessThreshold(threshold);
3372     }
3373     return array;
3374 }
3375 
NewBigInt(uint32_t length)3376 JSHandle<BigInt> ObjectFactory::NewBigInt(uint32_t length)
3377 {
3378     NewObjectHook();
3379     ASSERT(length > 0);
3380     size_t size = BigInt::ComputeSize(length);
3381     auto header = sHeap_->AllocateNonMovableOrHugeObject(thread_,
3382         JSHClass::Cast(thread_->GlobalConstants()->GetBigIntClass().GetTaggedObject()), size);
3383     JSHandle<BigInt> bigint(thread_, header);
3384     bigint->SetLength(length);
3385     bigint->SetSign(false);
3386     bigint->InitializationZero();
3387     return bigint;
3388 }
3389 
3390 // static
NewObjectHook() const3391 void ObjectFactory::NewObjectHook() const
3392 {
3393     CHECK_NO_HEAP_ALLOC;
3394 #ifndef NDEBUG
3395     if (vm_->GetJSOptions().EnableForceGC() && vm_->IsInitialized() && thread_->IsAllContextsInitialized()
3396         && !heap_->InSensitiveStatus()) {
3397         if (vm_->GetJSOptions().ForceFullGC()) {
3398             vm_->CollectGarbage(TriggerGCType::YOUNG_GC);
3399             vm_->CollectGarbage(TriggerGCType::OLD_GC);
3400             vm_->CollectGarbage(TriggerGCType::FULL_GC);
3401         } else {
3402             vm_->CollectGarbage(TriggerGCType::YOUNG_GC);
3403             vm_->CollectGarbage(TriggerGCType::OLD_GC);
3404         }
3405     }
3406 #endif
3407 }
3408 
NewTaggedQueue(uint32_t length)3409 JSHandle<TaggedQueue> ObjectFactory::NewTaggedQueue(uint32_t length)
3410 {
3411     uint32_t queueLength = TaggedQueue::QueueToArrayIndex(length);
3412     auto queue = JSHandle<TaggedQueue>::Cast(NewTaggedArray(queueLength, JSTaggedValue::Hole()));
3413     queue->SetStart(thread_, JSTaggedValue(0));  // equal to 0 when add 1.
3414     queue->SetEnd(thread_, JSTaggedValue(0));
3415     queue->SetCapacity(thread_, JSTaggedValue(length));
3416 
3417     return queue;
3418 }
3419 
GetEmptyTaggedQueue() const3420 JSHandle<TaggedQueue> ObjectFactory::GetEmptyTaggedQueue() const
3421 {
3422     return JSHandle<TaggedQueue>(thread_->GlobalConstants()->GetHandledEmptyTaggedQueue());
3423 }
3424 
NewJSSetIterator(const JSHandle<JSSharedSet> & set,IterationKind kind)3425 JSHandle<JSSharedSetIterator> ObjectFactory::NewJSSetIterator(const JSHandle<JSSharedSet> &set, IterationKind kind)
3426 {
3427     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3428     JSHandle<JSTaggedValue> protoValue = env->GetSharedSetIteratorPrototype();
3429     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3430     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSSharedSetIteratorClass());
3431     hclassHandle->SetPrototype(thread_, protoValue);
3432     JSHandle<JSSharedSetIterator> iter(NewJSObject(hclassHandle));
3433     iter->GetJSHClass()->SetExtensible(true);
3434     iter->SetIteratedSet(thread_, set.GetTaggedValue());
3435     iter->SetNextIndex(0);
3436     iter->SetIterationKind(kind);
3437     ASSERT(iter.GetTaggedValue().IsJSSharedSetIterator());
3438     return iter;
3439 }
3440 
NewJSSetIterator(const JSHandle<JSSet> & set,IterationKind kind)3441 JSHandle<JSSetIterator> ObjectFactory::NewJSSetIterator(const JSHandle<JSSet> &set, IterationKind kind)
3442 {
3443     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3444     JSHandle<JSTaggedValue> protoValue = env->GetSetIteratorPrototype();
3445     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3446     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSSetIteratorClass());
3447     hclassHandle->SetPrototype(thread_, protoValue);
3448     JSHandle<JSSetIterator> iter(NewJSObject(hclassHandle));
3449     iter->GetJSHClass()->SetExtensible(true);
3450     iter->SetIteratedSet(thread_, set->GetLinkedSet());
3451     iter->SetNextIndex(0);
3452     iter->SetIterationKind(kind);
3453     return iter;
3454 }
3455 
NewJSRegExpIterator(const JSHandle<JSTaggedValue> & matcher,const JSHandle<EcmaString> & inputStr,bool global,bool fullUnicode)3456 JSHandle<JSRegExpIterator> ObjectFactory::NewJSRegExpIterator(const JSHandle<JSTaggedValue> &matcher,
3457                                                               const JSHandle<EcmaString> &inputStr, bool global,
3458                                                               bool fullUnicode)
3459 {
3460     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3461     JSHandle<JSTaggedValue> protoValue = env->GetRegExpIteratorPrototype();
3462     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3463     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSRegExpIteratorClass());
3464     hclassHandle->SetPrototype(thread_, protoValue);
3465     JSHandle<JSRegExpIterator> iter(NewJSObject(hclassHandle));
3466     iter->GetJSHClass()->SetExtensible(true);
3467     iter->SetIteratingRegExp(thread_, matcher.GetTaggedValue());
3468     iter->SetIteratedString(thread_, inputStr.GetTaggedValue());
3469     iter->SetGlobal(global);
3470     iter->SetUnicode(fullUnicode);
3471     iter->SetDone(false);
3472     return iter;
3473 }
3474 
NewJSMapIterator(const JSHandle<JSMap> & map,IterationKind kind)3475 JSHandle<JSMapIterator> ObjectFactory::NewJSMapIterator(const JSHandle<JSMap> &map, IterationKind kind)
3476 {
3477     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3478     JSHandle<JSTaggedValue> protoValue = env->GetMapIteratorPrototype();
3479     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3480     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSMapIteratorClass());
3481     hclassHandle->SetPrototype(thread_, protoValue);
3482     JSHandle<JSMapIterator> iter(NewJSObject(hclassHandle));
3483     iter->GetJSHClass()->SetExtensible(true);
3484     iter->SetIteratedMap(thread_, map->GetLinkedMap());
3485     iter->SetNextIndex(0);
3486     iter->SetIterationKind(kind);
3487     return iter;
3488 }
3489 
NewJSMapIterator(const JSHandle<JSSharedMap> & map,IterationKind kind)3490 JSHandle<JSSharedMapIterator> ObjectFactory::NewJSMapIterator(const JSHandle<JSSharedMap> &map, IterationKind kind)
3491 {
3492     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3493     JSHandle<JSTaggedValue> protoValue = env->GetSharedMapIteratorPrototype();
3494     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3495     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSSharedMapIteratorClass());
3496     hclassHandle->SetPrototype(thread_, protoValue);
3497     JSHandle<JSSharedMapIterator> iter(NewJSObject(hclassHandle));
3498     iter->GetJSHClass()->SetExtensible(true);
3499     iter->SetIteratedMap(thread_, map.GetTaggedValue());
3500     iter->SetNextIndex(0);
3501     iter->SetIterationKind(kind);
3502     ASSERT(iter.GetTaggedValue().IsJSSharedMapIterator());
3503     return iter;
3504 }
3505 
NewJSAPIHashMapIterator(const JSHandle<JSAPIHashMap> & hashMap,IterationKind kind)3506 JSHandle<JSAPIHashMapIterator> ObjectFactory::NewJSAPIHashMapIterator(const JSHandle<JSAPIHashMap> &hashMap,
3507                                                                       IterationKind kind)
3508 {
3509     NewObjectHook();
3510     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3511     JSHandle<JSTaggedValue> undefinedHandle = globalConst->GetHandledUndefined();
3512     JSHandle<JSTaggedValue> proto(thread_, globalConst->GetHashMapIteratorPrototype());
3513     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIHashMapIteratorClass());
3514     hclassHandle->SetPrototype(thread_, proto);
3515     JSHandle<JSAPIHashMapIterator> iter(NewJSObject(hclassHandle));
3516     iter->GetJSHClass()->SetExtensible(true);
3517     iter->SetCurrentNodeResult(thread_, undefinedHandle);
3518     iter->SetIteratedHashMap(thread_, hashMap);
3519     iter->SetNextIndex(0);
3520     iter->SetTaggedQueue(thread_, JSTaggedValue::Undefined());
3521     JSHandle<TaggedQueue> queue = NewTaggedQueue(0);
3522     iter->SetTaggedQueue(thread_, queue);
3523     iter->SetIterationKind(kind);
3524     return iter;
3525 }
3526 
NewJSAPIHashSetIterator(const JSHandle<JSAPIHashSet> & hashSet,IterationKind kind)3527 JSHandle<JSAPIHashSetIterator> ObjectFactory::NewJSAPIHashSetIterator(const JSHandle<JSAPIHashSet> &hashSet,
3528                                                                       IterationKind kind)
3529 {
3530     NewObjectHook();
3531     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3532     JSHandle<JSTaggedValue> undefinedHandle = globalConst->GetHandledUndefined();
3533     JSHandle<JSTaggedValue> proto(thread_, globalConst->GetHashSetIteratorPrototype());
3534     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIHashSetIteratorClass());
3535     hclassHandle->SetPrototype(thread_, proto);
3536     JSHandle<JSAPIHashSetIterator> iter(NewJSObject(hclassHandle));
3537     iter->GetJSHClass()->SetExtensible(true);
3538     iter->SetCurrentNodeResult(thread_, undefinedHandle);
3539     iter->SetIteratedHashSet(thread_, hashSet);
3540     iter->SetNextIndex(0);
3541     iter->SetTableIndex(0);
3542     iter->SetTaggedQueue(thread_, JSTaggedValue::Undefined());
3543     JSHandle<TaggedQueue> queue = NewTaggedQueue(0);
3544     iter->SetTaggedQueue(thread_, queue);
3545     iter->SetIterationKind(kind);
3546     return iter;
3547 }
3548 
NewJSArrayIterator(const JSHandle<JSObject> & array,IterationKind kind)3549 JSHandle<JSArrayIterator> ObjectFactory::NewJSArrayIterator(const JSHandle<JSObject> &array, IterationKind kind)
3550 {
3551     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3552     JSHandle<JSTaggedValue> protoValue = env->GetArrayIteratorPrototype();
3553     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3554     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSArrayIteratorClass());
3555     hclassHandle->SetPrototype(thread_, protoValue);
3556     JSHandle<JSArrayIterator> iter(NewJSObject(hclassHandle));
3557     iter->GetJSHClass()->SetExtensible(true);
3558     iter->SetIteratedArray(thread_, array);
3559     iter->SetNextIndex(0);
3560     iter->SetIterationKind(kind);
3561     return iter;
3562 }
3563 
NewJSSharedArrayIterator(const JSHandle<JSObject> & array,IterationKind kind)3564 JSHandle<JSSharedArrayIterator> ObjectFactory::NewJSSharedArrayIterator(const JSHandle<JSObject> &array,
3565                                                                         IterationKind kind)
3566 {
3567     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3568     JSHandle<JSTaggedValue> protoValue = env->GetSharedArrayIteratorPrototype();
3569     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
3570     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSSharedArrayIteratorClass());
3571     hclassHandle->SetPrototype(thread_, protoValue);
3572     JSHandle<JSSharedArrayIterator> iter(NewJSObject(hclassHandle));
3573     iter->GetJSHClass()->SetExtensible(true);
3574     iter->SetIteratedArray(thread_, array);
3575     iter->SetNextIndex(0);
3576     iter->SetIterationKind(kind);
3577     return iter;
3578 }
3579 
CreateJSPromiseReactionsFunction(MethodIndex idx)3580 JSHandle<JSPromiseReactionsFunction> ObjectFactory::CreateJSPromiseReactionsFunction(MethodIndex idx)
3581 {
3582     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3583     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseReactionFunctionClass());
3584 
3585     JSHandle<JSPromiseReactionsFunction> reactionsFunction =
3586         JSHandle<JSPromiseReactionsFunction>::Cast(NewJSObject(hclass));
3587     reactionsFunction->SetPromise(thread_, JSTaggedValue::Hole());
3588     reactionsFunction->SetAlreadyResolved(thread_, JSTaggedValue::Hole());
3589     JSHandle<JSFunction> function = JSHandle<JSFunction>::Cast(reactionsFunction);
3590     JSFunction::InitializeJSFunction(thread_, function);
3591     reactionsFunction->SetMethod(thread_, vm_->GetMethodByIndex(idx));
3592     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(1));
3593     return reactionsFunction;
3594 }
3595 
CreateJSPromiseExecutorFunction()3596 JSHandle<JSPromiseExecutorFunction> ObjectFactory::CreateJSPromiseExecutorFunction()
3597 {
3598     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3599     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseExecutorFunctionClass());
3600     JSHandle<JSPromiseExecutorFunction> executorFunction =
3601         JSHandle<JSPromiseExecutorFunction>::Cast(NewJSObject(hclass));
3602     executorFunction->SetCapability(thread_, JSTaggedValue::Undefined());
3603     JSHandle<JSFunction> function = JSHandle<JSFunction>::Cast(executorFunction);
3604     JSFunction::InitializeJSFunction(thread_, function);
3605     executorFunction->SetMethod(
3606         thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_EXECUTOR));
3607     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(FunctionLength::TWO));
3608     return executorFunction;
3609 }
3610 
CreateJSAsyncModuleFulfilledFunction()3611 JSHandle<JSAsyncModuleFulfilledFunction> ObjectFactory::CreateJSAsyncModuleFulfilledFunction()
3612 {
3613     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3614     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetAsyncModuleFulfilledFunctionClass());
3615     JSHandle<JSAsyncModuleFulfilledFunction> fulfilledFunction =
3616         JSHandle<JSAsyncModuleFulfilledFunction>::Cast(NewJSObject(hclass));
3617     fulfilledFunction->SetModule(thread_, JSTaggedValue::Undefined());
3618     JSHandle<JSFunction> function = JSHandle<JSFunction>::Cast(fulfilledFunction);
3619     JSFunction::InitializeJSFunction(thread_, function);
3620     fulfilledFunction->SetMethod(
3621         thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_ASYNC_MODULE_FULFILLED_FUNCTION));
3622     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(FunctionLength::ONE));
3623     return fulfilledFunction;
3624 }
3625 
CreateJSAsyncModuleRejectedFunction()3626 JSHandle<JSAsyncModuleRejectedFunction> ObjectFactory::CreateJSAsyncModuleRejectedFunction()
3627 {
3628     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3629     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetAsyncModuleRejectedFunctionClass());
3630     JSHandle<JSAsyncModuleRejectedFunction> rejectedFunction =
3631         JSHandle<JSAsyncModuleRejectedFunction>::Cast(NewJSObject(hclass));
3632     rejectedFunction->SetModule(thread_, JSTaggedValue::Undefined());
3633     JSHandle<JSFunction> function = JSHandle<JSFunction>::Cast(rejectedFunction);
3634     JSFunction::InitializeJSFunction(thread_, function);
3635     rejectedFunction->SetMethod(
3636         thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_ASYNC_MODULE_REJECTED_FUNCTION));
3637     JSFunction::SetFunctionLength(thread_, function, JSTaggedValue(FunctionLength::ONE));
3638     return rejectedFunction;
3639 }
3640 
NewJSPromiseAllResolveElementFunction()3641 JSHandle<JSPromiseAllResolveElementFunction> ObjectFactory::NewJSPromiseAllResolveElementFunction()
3642 {
3643     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3644     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseAllResolveElementFunctionClass());
3645     JSHandle<JSPromiseAllResolveElementFunction> function =
3646         JSHandle<JSPromiseAllResolveElementFunction>::Cast(NewJSObject(hclass));
3647     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3648     function->SetMethod(
3649         thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_RESOLVE_ELEMENT_FUNCTION));
3650     function->SetIndex(thread_, JSTaggedValue::Undefined());
3651     function->SetValues(thread_, JSTaggedValue::Undefined());
3652     function->SetCapabilities(thread_, JSTaggedValue::Undefined());
3653     function->SetRemainingElements(thread_, JSTaggedValue::Undefined());
3654     function->SetAlreadyCalled(thread_, JSTaggedValue::Undefined());
3655     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3656     return function;
3657 }
3658 
NewJSPromiseAnyRejectElementFunction()3659 JSHandle<JSPromiseAnyRejectElementFunction> ObjectFactory::NewJSPromiseAnyRejectElementFunction()
3660 {
3661     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3662     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseAnyRejectElementFunctionClass());
3663     JSHandle<JSPromiseAnyRejectElementFunction> function =
3664         JSHandle<JSPromiseAnyRejectElementFunction>::Cast(NewJSObject(hclass));
3665     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3666     function->SetMethod(
3667         thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_ANY_REJECT_ELEMENT_FUNCTION));
3668     function->SetIndex(0);
3669     function->SetErrors(thread_, JSTaggedValue::Undefined());
3670     function->SetCapability(thread_, JSTaggedValue::Undefined());
3671     function->SetRemainingElements(thread_, JSTaggedValue::Undefined());
3672     function->SetAlreadyCalled(thread_, JSTaggedValue::Undefined());
3673     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3674     return function;
3675 }
3676 
NewJSPromiseAllSettledResolveElementFunction()3677 JSHandle<JSPromiseAllSettledElementFunction> ObjectFactory::NewJSPromiseAllSettledResolveElementFunction()
3678 {
3679     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3680     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseAllSettledElementFunctionClass());
3681     JSHandle<JSPromiseAllSettledElementFunction> function =
3682         JSHandle<JSPromiseAllSettledElementFunction>::Cast(NewJSObject(hclass));
3683     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3684     function->SetMethod(thread_,
3685         vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_ALL_SETTLED_RESOLVE_ELEMENT_FUNCTION));
3686     function->SetIndex(0);
3687     function->SetValues(thread_, JSTaggedValue::Undefined());
3688     function->SetCapability(thread_, JSTaggedValue::Undefined());
3689     function->SetRemainingElements(thread_, JSTaggedValue::Undefined());
3690     function->SetAlreadyCalled(thread_, JSTaggedValue::Undefined());
3691     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3692     return function;
3693 }
3694 
NewJSPromiseAllSettledRejectElementFunction()3695 JSHandle<JSPromiseAllSettledElementFunction> ObjectFactory::NewJSPromiseAllSettledRejectElementFunction()
3696 {
3697     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3698     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseAllSettledElementFunctionClass());
3699     JSHandle<JSPromiseAllSettledElementFunction> function =
3700         JSHandle<JSPromiseAllSettledElementFunction>::Cast(NewJSObject(hclass));
3701     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3702     function->SetMethod(thread_,
3703         vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_ALL_SETTLED_REJECT_ELEMENT_FUNCTION));
3704     function->SetIndex(0);
3705     function->SetValues(thread_, JSTaggedValue::Undefined());
3706     function->SetCapability(thread_, JSTaggedValue::Undefined());
3707     function->SetRemainingElements(thread_, JSTaggedValue::Undefined());
3708     function->SetAlreadyCalled(thread_, JSTaggedValue::Undefined());
3709     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3710     return function;
3711 }
3712 
NewJSPromiseThenFinallyFunction()3713 JSHandle<JSPromiseFinallyFunction> ObjectFactory::NewJSPromiseThenFinallyFunction()
3714 {
3715     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3716     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseFinallyFunctionClass());
3717     JSHandle<JSPromiseFinallyFunction> function =
3718         JSHandle<JSPromiseFinallyFunction>::Cast(NewJSObject(hclass));
3719     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3720     function->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_THEN_FINALLY_FUNCTION));
3721     function->SetConstructor(thread_, JSTaggedValue::Undefined());
3722     function->SetOnFinally(thread_, JSTaggedValue::Undefined());
3723     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3724     return function;
3725 }
3726 
NewJSPromiseCatchFinallyFunction()3727 JSHandle<JSPromiseFinallyFunction> ObjectFactory::NewJSPromiseCatchFinallyFunction()
3728 {
3729     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3730     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseFinallyFunctionClass());
3731     JSHandle<JSPromiseFinallyFunction> function =
3732         JSHandle<JSPromiseFinallyFunction>::Cast(NewJSObject(hclass));
3733     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3734     function->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_CATCH_FINALLY_FUNCTION));
3735     function->SetConstructor(thread_, JSTaggedValue::Undefined());
3736     function->SetOnFinally(thread_, JSTaggedValue::Undefined());
3737     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3738     return function;
3739 }
3740 
NewJSAsyGenResNextRetProRstFulfilledFtn()3741 JSHandle<JSAsyncGeneratorResNextRetProRstFtn> ObjectFactory::NewJSAsyGenResNextRetProRstFulfilledFtn()
3742 {
3743     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3744     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(
3745         env->GetAsyncGeneratorResNextRetProRstFtnClass());
3746     JSHandle<JSAsyncGeneratorResNextRetProRstFtn> function =
3747         JSHandle<JSAsyncGeneratorResNextRetProRstFtn>::Cast(NewJSObject(hclass));
3748     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3749     function->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_ASYNC_GENERATOR_NEXT_FULFILLED_FUNCTION));
3750     function->SetAsyncGeneratorObject(thread_, JSTaggedValue::Undefined());
3751     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3752     return function;
3753 }
3754 
NewJSAsyncFromSyncIterUnwarpFunction()3755 JSHandle<JSAsyncFromSyncIterUnwarpFunction> ObjectFactory::NewJSAsyncFromSyncIterUnwarpFunction()
3756 {
3757     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3758     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetAsyncFromSyncIterUnwarpClass());
3759     JSHandle<JSAsyncFromSyncIterUnwarpFunction> function =
3760         JSHandle<JSAsyncFromSyncIterUnwarpFunction>::Cast(NewJSObject(hclass));
3761     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3762     JSTaggedValue debugVaule =  vm_->GetMethodByIndex(MethodIndex::BUILTINS_ASYNC_FROM_SYNC_ITERATOR_FUNCTION);
3763     function->SetMethod(thread_, debugVaule);
3764     function->SetDone(thread_, JSTaggedValue::Undefined());
3765     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3766     return function;
3767 }
3768 
NewJSAsyGenResNextRetProRstRejectedFtn()3769 JSHandle<JSAsyncGeneratorResNextRetProRstFtn> ObjectFactory::NewJSAsyGenResNextRetProRstRejectedFtn()
3770 {
3771     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3772     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(
3773         env->GetAsyncGeneratorResNextRetProRstFtnClass());
3774     JSHandle<JSAsyncGeneratorResNextRetProRstFtn> function =
3775         JSHandle<JSAsyncGeneratorResNextRetProRstFtn>::Cast(NewJSObject(hclass));
3776     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3777     function->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_ASYNC_GENERATOR_NEXT_REJECTED_FUNCTION));
3778     function->SetAsyncGeneratorObject(thread_, JSTaggedValue::Undefined());
3779     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(1));
3780     return function;
3781 }
3782 
NewJSPromiseValueThunkFunction()3783 JSHandle<JSPromiseValueThunkOrThrowerFunction> ObjectFactory::NewJSPromiseValueThunkFunction()
3784 {
3785     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3786     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseValueThunkOrThrowerFunctionClass());
3787     JSHandle<JSPromiseValueThunkOrThrowerFunction> function =
3788         JSHandle<JSPromiseValueThunkOrThrowerFunction>::Cast(NewJSObject(hclass));
3789     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3790     function->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_VALUE_THUNK_FUNCTION));
3791     function->SetResult(thread_, JSTaggedValue::Undefined());
3792     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(0));
3793     return function;
3794 }
3795 
NewJSPromiseThrowerFunction()3796 JSHandle<JSPromiseValueThunkOrThrowerFunction> ObjectFactory::NewJSPromiseThrowerFunction()
3797 {
3798     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3799     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetPromiseValueThunkOrThrowerFunctionClass());
3800     JSHandle<JSPromiseValueThunkOrThrowerFunction> function =
3801         JSHandle<JSPromiseValueThunkOrThrowerFunction>::Cast(NewJSObject(hclass));
3802     JSFunction::InitializeJSFunction(thread_, JSHandle<JSFunction>::Cast(function));
3803     function->SetMethod(thread_, vm_->GetMethodByIndex(MethodIndex::BUILTINS_PROMISE_HANDLER_THROWER_FUNCTION));
3804     function->SetResult(thread_, JSTaggedValue::Undefined());
3805     JSFunction::SetFunctionLength(thread_, JSHandle<JSFunction>::Cast(function), JSTaggedValue(0));
3806     return function;
3807 }
3808 
InternString(const JSHandle<JSTaggedValue> & key)3809 EcmaString *ObjectFactory::InternString(const JSHandle<JSTaggedValue> &key)
3810 {
3811     EcmaString *str = EcmaString::Cast(key->GetTaggedObject());
3812     if (EcmaStringAccessor(str).IsInternString()) {
3813         return str;
3814     }
3815 
3816     EcmaStringTable *stringTable = vm_->GetEcmaStringTable();
3817     return stringTable->GetOrInternString(vm_, str);
3818 }
3819 
NewTransitionHandler()3820 JSHandle<TransitionHandler> ObjectFactory::NewTransitionHandler()
3821 {
3822     NewObjectHook();
3823     TransitionHandler *handler =
3824         TransitionHandler::Cast(heap_->AllocateYoungOrHugeObject(
3825             JSHClass::Cast(thread_->GlobalConstants()->GetTransitionHandlerClass().GetTaggedObject())));
3826     handler->SetHandlerInfo(thread_, JSTaggedValue::Undefined());
3827     handler->SetTransitionHClass(thread_, JSTaggedValue::Undefined());
3828     return JSHandle<TransitionHandler>(thread_, handler);
3829 }
3830 
NewPrototypeHandler()3831 JSHandle<PrototypeHandler> ObjectFactory::NewPrototypeHandler()
3832 {
3833     NewObjectHook();
3834     PrototypeHandler *header =
3835         PrototypeHandler::Cast(heap_->AllocateYoungOrHugeObject(
3836             JSHClass::Cast(thread_->GlobalConstants()->GetPrototypeHandlerClass().GetTaggedObject())));
3837     JSHandle<PrototypeHandler> handler(thread_, header);
3838     handler->SetHandlerInfo(thread_, JSTaggedValue::Undefined());
3839     handler->SetProtoCell(thread_, JSTaggedValue::Undefined());
3840     handler->SetHolder(thread_, JSTaggedValue::Undefined());
3841     handler->SetAccessorJSFunction(thread_, JSTaggedValue::Undefined());
3842     handler->SetAccessorMethodId(0);
3843     return handler;
3844 }
3845 
NewTransWithProtoHandler()3846 JSHandle<TransWithProtoHandler> ObjectFactory::NewTransWithProtoHandler()
3847 {
3848     NewObjectHook();
3849     TransWithProtoHandler *header =
3850         TransWithProtoHandler::Cast(heap_->AllocateYoungOrHugeObject(
3851             JSHClass::Cast(thread_->GlobalConstants()->GetTransWithProtoHandlerClass().GetTaggedObject())));
3852     JSHandle<TransWithProtoHandler> handler(thread_, header);
3853     handler->SetHandlerInfo(thread_, JSTaggedValue::Undefined());
3854     handler->SetProtoCell(thread_, JSTaggedValue::Undefined());
3855     handler->SetTransitionHClass(thread_, JSTaggedValue::Undefined());
3856     return handler;
3857 }
3858 
NewStoreTSHandler()3859 JSHandle<StoreTSHandler> ObjectFactory::NewStoreTSHandler()
3860 {
3861     NewObjectHook();
3862     StoreTSHandler *header =
3863         StoreTSHandler::Cast(heap_->AllocateYoungOrHugeObject(
3864             JSHClass::Cast(thread_->GlobalConstants()->GetStoreTSHandlerClass().GetTaggedObject())));
3865     JSHandle<StoreTSHandler> handler(thread_, header);
3866     handler->SetHandlerInfo(thread_, JSTaggedValue::Undefined());
3867     handler->SetProtoCell(thread_, JSTaggedValue::Undefined());
3868     handler->SetHolder(thread_, JSTaggedValue::Undefined());
3869     return handler;
3870 }
3871 
NewPromiseRecord()3872 JSHandle<PromiseRecord> ObjectFactory::NewPromiseRecord()
3873 {
3874     NewObjectHook();
3875     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
3876         JSHClass::Cast(thread_->GlobalConstants()->GetPromiseRecordClass().GetTaggedObject()));
3877     JSHandle<PromiseRecord> obj(thread_, header);
3878     obj->SetValue(thread_, JSTaggedValue::Undefined());
3879     return obj;
3880 }
3881 
NewResolvingFunctionsRecord()3882 JSHandle<ResolvingFunctionsRecord> ObjectFactory::NewResolvingFunctionsRecord()
3883 {
3884     NewObjectHook();
3885     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
3886         JSHClass::Cast(thread_->GlobalConstants()->GetPromiseResolvingFunctionsRecordClass().GetTaggedObject()));
3887     JSHandle<ResolvingFunctionsRecord> obj(thread_, header);
3888     obj->SetResolveFunction(thread_, JSTaggedValue::Undefined());
3889     obj->SetRejectFunction(thread_, JSTaggedValue::Undefined());
3890     return obj;
3891 }
3892 
CreateObjectClass(const JSHandle<TaggedArray> & properties,size_t length)3893 JSHandle<JSHClass> ObjectFactory::CreateObjectClass(const JSHandle<TaggedArray> &properties, size_t length)
3894 {
3895     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3896     JSHandle<JSTaggedValue> proto = env->GetObjectFunctionPrototype();
3897 
3898     uint32_t fieldOrder = 0;
3899     JSMutableHandle<JSTaggedValue> key(thread_, JSTaggedValue::Undefined());
3900     JSHandle<LayoutInfo> layoutInfoHandle = CreateLayoutInfo(length);
3901     while (fieldOrder < length) {
3902         key.Update(properties->Get(fieldOrder * 2));  // 2: Meaning to double
3903         ASSERT_PRINT(JSTaggedValue::IsPropertyKey(key), "Key is not a property key");
3904         PropertyAttributes attributes = PropertyAttributes::Default();
3905 
3906         if (properties->Get(fieldOrder * 2 + 1).IsAccessor()) {  // 2: Meaning to double
3907             attributes.SetIsAccessor(true);
3908         }
3909 
3910         attributes.SetIsInlinedProps(true);
3911         attributes.SetRepresentation(Representation::TAGGED);
3912         attributes.SetOffset(fieldOrder);
3913         layoutInfoHandle->AddKey(thread_, fieldOrder, key.GetTaggedValue(), attributes);
3914         fieldOrder++;
3915     }
3916     ASSERT(fieldOrder <= PropertyAttributes::MAX_FAST_PROPS_CAPACITY);
3917     JSHandle<JSHClass> objClass = NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, fieldOrder);
3918     objClass->SetPrototype(thread_, proto.GetTaggedValue());
3919     {
3920         objClass->SetExtensible(true);
3921         objClass->SetLayout(thread_, layoutInfoHandle);
3922         objClass->SetNumberOfProps(fieldOrder);
3923     }
3924     return objClass;
3925 }
3926 
SetLayoutInObjHClass(const JSHandle<TaggedArray> & properties,size_t length,const JSHandle<JSHClass> & objClass)3927 JSHandle<JSHClass> ObjectFactory::SetLayoutInObjHClass(const JSHandle<TaggedArray> &properties, size_t length,
3928                                                        const JSHandle<JSHClass> &objClass)
3929 {
3930     JSMutableHandle<JSTaggedValue> key(thread_, JSTaggedValue::Undefined());
3931     JSHandle<JSHClass> newObjHclass(objClass);
3932 
3933     for (size_t fieldOffset = 0; fieldOffset < length; fieldOffset++) {
3934         key.Update(properties->Get(fieldOffset * 2)); // 2 : pair of key and value
3935         ASSERT_PRINT(JSTaggedValue::IsPropertyKey(key), "Key is not a property key");
3936         PropertyAttributes attributes = PropertyAttributes::Default();
3937         auto value = properties->Get(fieldOffset * 2 + 1);
3938         if (value.IsAccessor()) {  // 2: Meaning to double
3939             attributes.SetIsAccessor(true);
3940         }
3941         attributes.SetIsInlinedProps(true);
3942         attributes.SetRepresentation(Representation::TAGGED);
3943         attributes.SetOffset(fieldOffset);
3944         attributes.SetRepresentation(Representation::TAGGED);
3945         auto rep = PropertyAttributes::TranslateToRep(value);
3946         newObjHclass = JSHClass::SetPropertyOfObjHClass(thread_, newObjHclass, key, attributes, rep);
3947     }
3948     return newObjHclass;
3949 }
3950 
CanObjectLiteralHClassCache(size_t length)3951 bool ObjectFactory::CanObjectLiteralHClassCache(size_t length)
3952 {
3953     return length <= MAX_LITERAL_HCLASS_CACHE_SIZE;
3954 }
3955 
CreateObjectLiteralRootHClass(size_t length)3956 JSHandle<JSHClass> ObjectFactory::CreateObjectLiteralRootHClass(size_t length)
3957 {
3958     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3959     JSHandle<JSTaggedValue> proto = env->GetObjectFunctionPrototype();
3960     JSHandle<JSHClass> hclass = NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, length);
3961     hclass->SetPrototype(thread_, proto.GetTaggedValue());
3962     {
3963         hclass->SetNumberOfProps(0);
3964         hclass->SetExtensible(true);
3965     }
3966     return hclass;
3967 }
3968 
GetObjectLiteralRootHClass(size_t length)3969 JSHandle<JSHClass> ObjectFactory::GetObjectLiteralRootHClass(size_t length)
3970 {
3971     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
3972     JSHandle<JSTaggedValue> maybeCache = env->GetObjectLiteralHClassCache();
3973     if (UNLIKELY(maybeCache->IsHole())) {
3974         JSHandle<TaggedArray> cacheArr = NewTaggedArray(MAX_LITERAL_HCLASS_CACHE_SIZE + 1);
3975         env->SetObjectLiteralHClassCache(thread_, cacheArr.GetTaggedValue());
3976         JSHandle<JSHClass> objHClass = CreateObjectLiteralRootHClass(length);
3977         cacheArr->Set(thread_, length, objHClass);
3978         return objHClass;
3979     }
3980     JSHandle<TaggedArray> hclassCacheArr = JSHandle<TaggedArray>::Cast(maybeCache);
3981     JSTaggedValue maybeHClass = hclassCacheArr->Get(length);
3982     if (UNLIKELY(maybeHClass.IsHole())) {
3983         JSHandle<JSHClass> objHClass = CreateObjectLiteralRootHClass(length);
3984         hclassCacheArr->Set(thread_, length, objHClass);
3985         return objHClass;
3986     }
3987     return JSHandle<JSHClass>(thread_, maybeHClass);
3988 }
3989 
GetObjectLiteralHClass(const JSHandle<TaggedArray> & properties,size_t length)3990 JSHandle<JSHClass> ObjectFactory::GetObjectLiteralHClass(const JSHandle<TaggedArray> &properties, size_t length)
3991 {
3992     ASSERT(length <= PropertyAttributes::MAX_FAST_PROPS_CAPACITY);
3993     // 64 : If object literal gets too many properties, create hclass directly.
3994     if (!CanObjectLiteralHClassCache(length)) {
3995         return CreateObjectClass(properties, length);
3996     }
3997     JSHandle<JSHClass> rootHClass = GetObjectLiteralRootHClass(length);
3998     return SetLayoutInObjHClass(properties, length, rootHClass);
3999 }
4000 
NewOldSpaceObjLiteralByHClass(const JSHandle<JSHClass> & hclass)4001 JSHandle<JSObject> ObjectFactory::NewOldSpaceObjLiteralByHClass(const JSHandle<JSHClass> &hclass)
4002 {
4003     JSHandle<JSObject> obj = NewOldSpaceJSObject(hclass);
4004     InitializeJSObject(obj, hclass);
4005     return obj;
4006 }
4007 
NewEmptyJSObject(uint32_t inlinedProps)4008 JSHandle<JSObject> ObjectFactory::NewEmptyJSObject(uint32_t inlinedProps)
4009 {
4010     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
4011     JSHandle<JSFunction> builtinObj(env->GetObjectFunction());
4012     return NewJSObjectByConstructor(builtinObj, inlinedProps);
4013 }
4014 
CreateNullJSObject()4015 JSHandle<JSObject> ObjectFactory::CreateNullJSObject()
4016 {
4017     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4018     JSHandle<JSTaggedValue> nullValue = globalConst->GetHandledNull();
4019     return OrdinaryNewJSObjectCreate(nullValue);
4020 }
4021 
NewSpaceBySnapshotAllocator(size_t size)4022 uintptr_t ObjectFactory::NewSpaceBySnapshotAllocator(size_t size)
4023 {
4024     NewObjectHook();
4025     return heap_->AllocateSnapshotSpace(size);
4026 }
4027 
NewMachineCodeObject(size_t length,MachineCodeDesc & desc)4028 TaggedObject *ObjectFactory::NewMachineCodeObject(size_t length,
4029     MachineCodeDesc &desc)
4030 {
4031     NewObjectHook();
4032     TaggedObject *obj = heap_->AllocateMachineCodeObject(
4033         JSHClass::Cast(thread_->GlobalConstants()->GetMachineCodeClass().GetTaggedObject()),
4034         length + MachineCode::SIZE, &desc);
4035     return (obj);
4036 }
4037 
NewMachineCodeObject(size_t length,const MachineCodeDesc & desc,JSHandle<Method> & method)4038 JSHandle<MachineCode> ObjectFactory::NewMachineCodeObject(size_t length,
4039     const MachineCodeDesc &desc, JSHandle<Method> &method)
4040 {
4041     NewObjectHook();
4042     TaggedObject *obj = heap_->AllocateMachineCodeObject(
4043         JSHClass::Cast(thread_->GlobalConstants()->GetMachineCodeClass().GetTaggedObject()),
4044         length + MachineCode::SIZE);
4045     return SetMachineCodeObjectData(obj, length, desc, method);
4046 }
4047 
SetMachineCodeObjectData(TaggedObject * obj,size_t length,const MachineCodeDesc & desc,JSHandle<Method> & method)4048 JSHandle<MachineCode> ObjectFactory::SetMachineCodeObjectData(TaggedObject *obj, size_t length,
4049     const MachineCodeDesc &desc, JSHandle<Method> &method)
4050 {
4051     MachineCode *code = MachineCode::Cast(obj);
4052     if (code == nullptr) {
4053         LOG_FULL(FATAL) << "machine code cast failed";
4054         UNREACHABLE();
4055     }
4056     if (code->SetData(desc, method, length)) {
4057         JSHandle<MachineCode> codeObj(thread_, code);
4058         return codeObj;
4059     } else {
4060         JSHandle<MachineCode> codeObj;
4061         return codeObj;
4062     }
4063 }
4064 
NewClassInfoExtractor(JSHandle<JSTaggedValue> method)4065 JSHandle<ClassInfoExtractor> ObjectFactory::NewClassInfoExtractor(JSHandle<JSTaggedValue> method)
4066 {
4067     NewObjectHook();
4068     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4069         JSHClass::Cast(thread_->GlobalConstants()->GetClassInfoExtractorHClass().GetTaggedObject()));
4070     JSHandle<ClassInfoExtractor> obj(thread_, header);
4071     obj->ClearBitField();
4072     obj->SetConstructorMethod(thread_, method.GetTaggedValue());
4073     JSHandle<TaggedArray> emptyArray = EmptyArray();
4074     obj->SetNonStaticKeys(thread_, emptyArray, SKIP_BARRIER);
4075     obj->SetNonStaticProperties(thread_, emptyArray, SKIP_BARRIER);
4076     obj->SetNonStaticElements(thread_, emptyArray, SKIP_BARRIER);
4077     obj->SetStaticKeys(thread_, emptyArray, SKIP_BARRIER);
4078     obj->SetStaticProperties(thread_, emptyArray, SKIP_BARRIER);
4079     obj->SetStaticElements(thread_, emptyArray, SKIP_BARRIER);
4080     return obj;
4081 }
4082 
4083 // ----------------------------------- new string ----------------------------------------
NewFromASCII(std::string_view data)4084 JSHandle<EcmaString> ObjectFactory::NewFromASCII(std::string_view data)
4085 {
4086     auto utf8Data = reinterpret_cast<const uint8_t *>(data.data());
4087     ASSERT(EcmaStringAccessor::CanBeCompressed(utf8Data, data.length()));
4088     return GetStringFromStringTable(utf8Data, data.length(), true);
4089 }
4090 
4091 // At this situation, Create string directly without using a StringTable.
NewFromASCIISkippingStringTable(std::string_view data)4092 JSHandle<EcmaString> ObjectFactory::NewFromASCIISkippingStringTable(std::string_view data)
4093 {
4094     auto utf8Data = reinterpret_cast<const uint8_t *>(data.data());
4095     ASSERT(EcmaStringAccessor::CanBeCompressed(utf8Data, data.length()));
4096     EcmaString *str = EcmaStringAccessor::CreateFromUtf8(vm_, utf8Data, data.length(), true);
4097     return JSHandle<EcmaString>(thread_, str);
4098 }
4099 
NewFromASCIINonMovable(std::string_view data)4100 JSHandle<EcmaString> ObjectFactory::NewFromASCIINonMovable(std::string_view data)
4101 {
4102     auto utf8Data = reinterpret_cast<const uint8_t *>(data.data());
4103     ASSERT(EcmaStringAccessor::CanBeCompressed(utf8Data, data.length()));
4104     return GetStringFromStringTableNonMovable(utf8Data, data.length());
4105 }
4106 
NewFromASCIIReadOnly(std::string_view data)4107 JSHandle<EcmaString> ObjectFactory::NewFromASCIIReadOnly(std::string_view data)
4108 {
4109     auto utf8Data = reinterpret_cast<const uint8_t *>(data.data());
4110     ASSERT(EcmaStringAccessor::CanBeCompressed(utf8Data, data.length()));
4111     return GetStringFromStringTableReadOnly(utf8Data, data.length());
4112 }
4113 
NewFromUtf8WithoutStringTable(std::string_view data)4114 JSHandle<EcmaString> ObjectFactory::NewFromUtf8WithoutStringTable(std::string_view data)
4115 {
4116     auto utf8Data = reinterpret_cast<const uint8_t *>(data.data());
4117     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf8Data, data.length());
4118     uint32_t utf8Len = data.length();
4119     NewObjectHook();
4120     if (utf8Len == 0) {
4121         return GetEmptyString();
4122     }
4123     EcmaString *str =
4124         EcmaStringAccessor::CreateFromUtf8(vm_, utf8Data, utf8Len, canBeCompress, MemSpaceType::SHARED_OLD_SPACE);
4125     uint32_t hashCode = EcmaStringAccessor::ComputeHashcodeUtf8(utf8Data, utf8Len, canBeCompress);
4126     str->SetMixHashcode(hashCode);
4127     return JSHandle<EcmaString>(thread_, str);
4128 }
4129 
NewFromUtf8(std::string_view data)4130 JSHandle<EcmaString> ObjectFactory::NewFromUtf8(std::string_view data)
4131 {
4132     auto utf8Data = reinterpret_cast<const uint8_t *>(data.data());
4133     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf8Data, data.length());
4134     return GetStringFromStringTable(utf8Data, data.length(), canBeCompress);
4135 }
4136 
NewFromUtf8(std::string_view data,bool canBeCompress)4137 JSHandle<EcmaString> ObjectFactory::NewFromUtf8(std::string_view data, bool canBeCompress)
4138 {
4139     auto utf8Data = reinterpret_cast<const uint8_t *>(data.data());
4140     ASSERT(canBeCompress == EcmaStringAccessor::CanBeCompressed(utf8Data, data.length()));
4141     return GetStringFromStringTable(utf8Data, data.length(), canBeCompress);
4142 }
4143 
NewFromUtf8ReadOnly(std::string_view data)4144 JSHandle<EcmaString> ObjectFactory::NewFromUtf8ReadOnly(std::string_view data)
4145 {
4146     auto utf8Data = reinterpret_cast<const uint8_t *>(data.data());
4147     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf8Data, data.length());
4148     return GetStringFromStringTableReadOnly(utf8Data, data.length(), canBeCompress);
4149 }
4150 
NewFromUtf16WithoutStringTable(std::u16string_view data)4151 JSHandle<EcmaString> ObjectFactory::NewFromUtf16WithoutStringTable(std::u16string_view data)
4152 {
4153     uint32_t utf16Len = data.length();
4154     auto utf16Data = reinterpret_cast<const uint16_t *>(data.data());
4155     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf16Data, utf16Len);
4156     NewObjectHook();
4157     if (utf16Len == 0) {
4158         return GetEmptyString();
4159     }
4160     EcmaString *str =
4161         EcmaStringAccessor::CreateFromUtf16(vm_, utf16Data, utf16Len, canBeCompress, MemSpaceType::SHARED_OLD_SPACE);
4162     uint32_t hashCode = EcmaStringAccessor::ComputeHashcodeUtf16(const_cast<uint16_t *>(utf16Data), utf16Len);
4163     str->SetMixHashcode(hashCode);
4164     return JSHandle<EcmaString>(thread_, str);
4165 }
4166 
NewFromUtf16(std::u16string_view data)4167 JSHandle<EcmaString> ObjectFactory::NewFromUtf16(std::u16string_view data)
4168 {
4169     uint32_t length = data.length();
4170     auto utf16Data = reinterpret_cast<const uint16_t *>(data.data());
4171     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf16Data, length);
4172     return GetStringFromStringTable(utf16Data, length, canBeCompress);
4173 }
4174 
NewFromStdString(const std::string & data)4175 JSHandle<EcmaString> ObjectFactory::NewFromStdString(const std::string &data)
4176 {
4177     auto utf8Data = reinterpret_cast<const uint8_t *>(data.c_str());
4178     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf8Data, data.length());
4179     return GetStringFromStringTable(utf8Data, data.size(), canBeCompress);
4180 }
4181 
NewFromUtf8WithoutStringTable(const uint8_t * utf8Data,uint32_t utf8Len)4182 JSHandle<EcmaString> ObjectFactory::NewFromUtf8WithoutStringTable(const uint8_t *utf8Data, uint32_t utf8Len)
4183 {
4184     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf8Data, utf8Len);
4185     NewObjectHook();
4186     if (utf8Len == 0) {
4187         return GetEmptyString();
4188     }
4189     EcmaString *str =
4190         EcmaStringAccessor::CreateFromUtf8(vm_, utf8Data, utf8Len, canBeCompress, MemSpaceType::SHARED_OLD_SPACE);
4191     uint32_t hashCode = EcmaStringAccessor::ComputeHashcodeUtf8(utf8Data, utf8Len, canBeCompress);
4192     str->SetMixHashcode(hashCode);
4193     return JSHandle<EcmaString>(thread_, str);
4194 }
4195 
NewFromUtf8(const uint8_t * utf8Data,uint32_t utf8Len)4196 JSHandle<EcmaString> ObjectFactory::NewFromUtf8(const uint8_t *utf8Data, uint32_t utf8Len)
4197 {
4198     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf8Data, utf8Len);
4199     return GetStringFromStringTable(utf8Data, utf8Len, canBeCompress);
4200 }
4201 
NewFromUtf16WithoutStringTable(const uint16_t * utf16Data,uint32_t utf16Len)4202 JSHandle<EcmaString> ObjectFactory::NewFromUtf16WithoutStringTable(const uint16_t *utf16Data, uint32_t utf16Len)
4203 {
4204     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf16Data, utf16Len);
4205     NewObjectHook();
4206     if (utf16Len == 0) {
4207         return GetEmptyString();
4208     }
4209     EcmaString *str =
4210         EcmaStringAccessor::CreateFromUtf16(vm_, utf16Data, utf16Len, canBeCompress, MemSpaceType::SHARED_OLD_SPACE);
4211     uint32_t hashCode = EcmaStringAccessor::ComputeHashcodeUtf16(const_cast<uint16_t *>(utf16Data), utf16Len);
4212     str->SetMixHashcode(hashCode);
4213     return JSHandle<EcmaString>(thread_, str);
4214 }
4215 
NewFromUtf16(const uint16_t * utf16Data,uint32_t utf16Len)4216 JSHandle<EcmaString> ObjectFactory::NewFromUtf16(const uint16_t *utf16Data, uint32_t utf16Len)
4217 {
4218     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf16Data, utf16Len);
4219     return GetStringFromStringTable(utf16Data, utf16Len, canBeCompress);
4220 }
4221 
NewFromUtf16Compress(const uint16_t * utf16Data,uint32_t utf16Len)4222 JSHandle<EcmaString> ObjectFactory::NewFromUtf16Compress(const uint16_t *utf16Data, uint32_t utf16Len)
4223 {
4224     ASSERT(EcmaStringAccessor::CanBeCompressed(utf16Data, utf16Len));
4225     return GetStringFromStringTable(utf16Data, utf16Len, true);
4226 }
4227 
NewFromUtf16NotCompress(const uint16_t * utf16Data,uint32_t utf16Len)4228 JSHandle<EcmaString> ObjectFactory::NewFromUtf16NotCompress(const uint16_t *utf16Data, uint32_t utf16Len)
4229 {
4230     ASSERT(!EcmaStringAccessor::CanBeCompressed(utf16Data, utf16Len));
4231     return GetStringFromStringTable(utf16Data, utf16Len, false);
4232 }
4233 
NewFromUtf8Literal(const uint8_t * utf8Data,uint32_t utf8Len)4234 JSHandle<EcmaString> ObjectFactory::NewFromUtf8Literal(const uint8_t *utf8Data, uint32_t utf8Len)
4235 {
4236     NewObjectHook();
4237     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf8Data, utf8Len);
4238     return JSHandle<EcmaString>(thread_, EcmaStringAccessor::CreateFromUtf8(vm_, utf8Data, utf8Len, canBeCompress));
4239 }
4240 
NewFromUtf8LiteralCompress(const uint8_t * utf8Data,uint32_t utf8Len)4241 JSHandle<EcmaString> ObjectFactory::NewFromUtf8LiteralCompress(const uint8_t *utf8Data, uint32_t utf8Len)
4242 {
4243     NewObjectHook();
4244     ASSERT(EcmaStringAccessor::CanBeCompressed(utf8Data, utf8Len));
4245     return JSHandle<EcmaString>(thread_, EcmaStringAccessor::CreateFromUtf8(vm_, utf8Data, utf8Len, true));
4246 }
4247 
NewFromUtf8LiteralCompressSubString(const JSHandle<EcmaString> & string,uint32_t offset,uint32_t utf8Len)4248 JSHandle<EcmaString> ObjectFactory::NewFromUtf8LiteralCompressSubString(const JSHandle<EcmaString> &string,
4249                                                                         uint32_t offset, uint32_t utf8Len)
4250 {
4251     NewObjectHook();
4252     ASSERT(EcmaStringAccessor::CanBeCompressed(EcmaStringAccessor(string).GetDataUtf8() + offset, utf8Len));
4253     return JSHandle<EcmaString>(thread_, EcmaStringAccessor::CreateFromUtf8CompressedSubString(vm_, string,
4254         offset, utf8Len));
4255 }
4256 
NewCompressedUtf8(const uint8_t * utf8Data,uint32_t utf8Len)4257 JSHandle<EcmaString> ObjectFactory::NewCompressedUtf8(const uint8_t *utf8Data, uint32_t utf8Len)
4258 {
4259     NewObjectHook();
4260     ASSERT(EcmaStringAccessor::CanBeCompressed(utf8Data, utf8Len));
4261     return GetStringFromStringTable(utf8Data, utf8Len, true);
4262 }
4263 
NewCompressedUtf8SubString(const JSHandle<EcmaString> & string,uint32_t offset,uint32_t utf8Len)4264 JSHandle<EcmaString> ObjectFactory::NewCompressedUtf8SubString(const JSHandle<EcmaString> &string,
4265                                                                uint32_t offset, uint32_t utf8Len)
4266 {
4267     NewObjectHook();
4268     ASSERT(EcmaStringAccessor::CanBeCompressed(EcmaStringAccessor(string).GetDataUtf8() + offset, utf8Len));
4269     return GetCompressedSubStringFromStringTable(string, offset, utf8Len);
4270 }
4271 
NewFromUtf16Literal(const uint16_t * utf16Data,uint32_t utf16Len)4272 JSHandle<EcmaString> ObjectFactory::NewFromUtf16Literal(const uint16_t *utf16Data, uint32_t utf16Len)
4273 {
4274     NewObjectHook();
4275     bool canBeCompress = EcmaStringAccessor::CanBeCompressed(utf16Data, utf16Len);
4276     return JSHandle<EcmaString>(thread_, EcmaStringAccessor::CreateFromUtf16(vm_, utf16Data, utf16Len, canBeCompress));
4277 }
4278 
NewFromUtf16LiteralCompress(const uint16_t * utf16Data,uint32_t utf16Len)4279 JSHandle<EcmaString> ObjectFactory::NewFromUtf16LiteralCompress(const uint16_t *utf16Data, uint32_t utf16Len)
4280 {
4281     NewObjectHook();
4282     ASSERT(EcmaStringAccessor::CanBeCompressed(utf16Data, utf16Len));
4283     return JSHandle<EcmaString>(thread_, EcmaStringAccessor::CreateFromUtf16(vm_, utf16Data, utf16Len, true));
4284 }
4285 
NewFromUtf16LiteralNotCompress(const uint16_t * utf16Data,uint32_t utf16Len)4286 JSHandle<EcmaString> ObjectFactory::NewFromUtf16LiteralNotCompress(const uint16_t *utf16Data, uint32_t utf16Len)
4287 {
4288     NewObjectHook();
4289     ASSERT(!EcmaStringAccessor::CanBeCompressed(utf16Data, utf16Len));
4290     return JSHandle<EcmaString>(thread_, EcmaStringAccessor::CreateFromUtf16(vm_, utf16Data, utf16Len, false));
4291 }
4292 
ConcatFromString(const JSHandle<EcmaString> & firstString,const JSHandle<EcmaString> & secondString)4293 JSHandle<EcmaString> ObjectFactory::ConcatFromString(const JSHandle<EcmaString> &firstString,
4294                                                      const JSHandle<EcmaString> &secondString)
4295 {
4296     if (EcmaStringAccessor(firstString).GetLength() == 0) {
4297         return secondString;
4298     }
4299     if (EcmaStringAccessor(secondString).GetLength() == 0) {
4300         return firstString;
4301     }
4302     return GetStringFromStringTable(firstString, secondString);
4303 }
4304 
GetStringFromStringTable(const JSHandle<EcmaString> & firstString,const JSHandle<EcmaString> & secondString)4305 JSHandle<EcmaString> ObjectFactory::GetStringFromStringTable(const JSHandle<EcmaString> &firstString,
4306                                                              const JSHandle<EcmaString> &secondString)
4307 {
4308     auto stringTable = vm_->GetEcmaStringTable();
4309     return JSHandle<EcmaString>(thread_, stringTable->GetOrInternString(vm_, firstString, secondString));
4310 }
4311 
NewJSAPIArrayList(uint32_t capacity)4312 JSHandle<JSAPIArrayList> ObjectFactory::NewJSAPIArrayList(uint32_t capacity)
4313 {
4314     NewObjectHook();
4315     JSHandle<JSFunction> builtinObj(thread_, thread_->GlobalConstants()->GetArrayListFunction());
4316     JSHandle<JSAPIArrayList> obj = JSHandle<JSAPIArrayList>(NewJSObjectByConstructor(builtinObj));
4317     ObjectFactory *factory = thread_->GetEcmaVM()->GetFactory();
4318     JSHandle<TaggedArray> elements = factory->NewTaggedArray(capacity);
4319     obj->SetElements(thread_, elements);
4320 
4321     return obj;
4322 }
4323 
NewJSAPIArrayListIterator(const JSHandle<JSAPIArrayList> & arrayList)4324 JSHandle<JSAPIArrayListIterator> ObjectFactory::NewJSAPIArrayListIterator(const JSHandle<JSAPIArrayList> &arrayList)
4325 {
4326     NewObjectHook();
4327     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4328     JSHandle<JSTaggedValue> protoValue(thread_, globalConst->GetArrayListIteratorPrototype());
4329     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIArrayListIteratorClass());
4330     hclassHandle->SetPrototype(thread_, protoValue);
4331     JSHandle<JSAPIArrayListIterator> iter(NewJSObject(hclassHandle));
4332     iter->GetJSHClass()->SetExtensible(true);
4333     iter->SetIteratedArrayList(thread_, arrayList);
4334     iter->SetNextIndex(0);
4335     return iter;
4336 }
4337 
NewJSAPILightWeightMapIterator(const JSHandle<JSAPILightWeightMap> & obj,IterationKind kind)4338 JSHandle<JSAPILightWeightMapIterator> ObjectFactory::NewJSAPILightWeightMapIterator(
4339     const JSHandle<JSAPILightWeightMap> &obj, IterationKind kind)
4340 {
4341     NewObjectHook();
4342     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4343     JSHandle<JSTaggedValue> protoValue(thread_, globalConst->GetLightWeightMapIteratorPrototype());
4344     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPILightWeightMapIteratorClass());
4345     hclassHandle->SetPrototype(thread_, protoValue);
4346     JSHandle<JSAPILightWeightMapIterator> iter(NewJSObject(hclassHandle));
4347     iter->GetJSHClass()->SetExtensible(true);
4348     iter->SetIteratedLightWeightMap(thread_, obj);
4349     iter->SetNextIndex(0);
4350     iter->SetIterationKind(kind);
4351     return iter;
4352 }
4353 
NewJSAPILightWeightSetIterator(const JSHandle<JSAPILightWeightSet> & obj,IterationKind kind)4354 JSHandle<JSAPILightWeightSetIterator> ObjectFactory::NewJSAPILightWeightSetIterator(
4355     const JSHandle<JSAPILightWeightSet> &obj, IterationKind kind)
4356 {
4357     NewObjectHook();
4358     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4359     JSHandle<JSTaggedValue> protoValue(thread_, globalConst->GetLightWeightSetIteratorPrototype());
4360     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPILightWeightSetIteratorClass());
4361     hclassHandle->SetPrototype(thread_, protoValue);
4362     JSHandle<JSAPILightWeightSetIterator> iter(NewJSObject(hclassHandle));
4363     iter->GetJSHClass()->SetExtensible(true);
4364     iter->SetIteratedLightWeightSet(thread_, obj);
4365     iter->SetNextIndex(0);
4366     iter->SetIterationKind(kind);
4367     return iter;
4368 }
4369 
NewJSAPIPlainArray(uint32_t capacity)4370 JSHandle<JSAPIPlainArray> ObjectFactory::NewJSAPIPlainArray(uint32_t capacity)
4371 {
4372     NewObjectHook();
4373     JSHandle<JSFunction> builtinObj(thread_, thread_->GlobalConstants()->GetPlainArrayFunction());
4374     JSHandle<JSAPIPlainArray> obj = JSHandle<JSAPIPlainArray>(NewJSObjectByConstructor(builtinObj));
4375     ObjectFactory *factory = thread_->GetEcmaVM()->GetFactory();
4376     JSHandle<TaggedArray> keyArray = factory->NewTaggedArray(capacity);
4377     JSHandle<TaggedArray> valueArray = factory->NewTaggedArray(capacity);
4378     obj->SetKeys(thread_, keyArray);
4379     obj->SetValues(thread_, valueArray);
4380 
4381     return obj;
4382 }
4383 
NewJSAPIPlainArrayIterator(const JSHandle<JSAPIPlainArray> & plainarray,IterationKind kind)4384 JSHandle<JSAPIPlainArrayIterator> ObjectFactory::NewJSAPIPlainArrayIterator(const JSHandle<JSAPIPlainArray> &plainarray,
4385                                                                             IterationKind kind)
4386 {
4387     NewObjectHook();
4388     JSHandle<JSTaggedValue> protoValue(thread_, thread_->GlobalConstants()->GetPlainArrayIteratorPrototype());
4389     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4390     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIPlainArrayIteratorClass());
4391     hclassHandle->SetPrototype(thread_, protoValue);
4392     JSHandle<JSAPIPlainArrayIterator> iter(NewJSObject(hclassHandle));
4393     iter->GetJSHClass()->SetExtensible(true);
4394     iter->SetIteratedPlainArray(thread_, plainarray);
4395     iter->SetNextIndex(0);
4396     iter->SetIterationKind(kind);
4397     return iter;
4398 }
4399 
NewJSAPIStackIterator(const JSHandle<JSAPIStack> & stack)4400 JSHandle<JSAPIStackIterator> ObjectFactory::NewJSAPIStackIterator(const JSHandle<JSAPIStack> &stack)
4401 {
4402     NewObjectHook();
4403     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4404     JSHandle<JSTaggedValue> protoValue(thread_, globalConst->GetStackIteratorPrototype());
4405     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIStackIteratorClass());
4406     hclassHandle->SetPrototype(thread_, protoValue);
4407     JSHandle<JSAPIStackIterator> iter(NewJSObject(hclassHandle));
4408     iter->GetJSHClass()->SetExtensible(true);
4409     iter->SetIteratedStack(thread_, stack);
4410     iter->SetNextIndex(0);
4411     return iter;
4412 }
4413 
CopyDeque(const JSHandle<TaggedArray> & old,uint32_t newLength,uint32_t oldLength,uint32_t first,uint32_t last)4414 JSHandle<TaggedArray> ObjectFactory::CopyDeque(const JSHandle<TaggedArray> &old, uint32_t newLength,
4415                                                [[maybe_unused]] uint32_t oldLength, uint32_t first, uint32_t last)
4416 {
4417     NewObjectHook();
4418     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), newLength);
4419     auto header = heap_->AllocateYoungOrHugeObject(
4420         JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject()), size);
4421     JSHandle<TaggedArray> newArray(thread_, header);
4422     newArray->InitializeWithSpecialValue(JSTaggedValue::Hole(), newLength, old->GetExtraLength());
4423 
4424     uint32_t curIndex = first;
4425     // newIndex use in new TaggedArray, 0 : New TaggedArray index
4426     uint32_t newIndex = 0;
4427     uint32_t oldCapacity = old->GetLength();
4428     while (curIndex != last) {
4429         JSTaggedValue value = old->Get(curIndex);
4430         newArray->Set(thread_, newIndex, value);
4431         ASSERT(oldCapacity != 0);
4432         curIndex = (curIndex + 1) % oldCapacity;
4433         newIndex = newIndex + 1;
4434     }
4435     return newArray;
4436 }
4437 
NewJSAPIDequeIterator(const JSHandle<JSAPIDeque> & deque)4438 JSHandle<JSAPIDequeIterator> ObjectFactory::NewJSAPIDequeIterator(const JSHandle<JSAPIDeque> &deque)
4439 {
4440     NewObjectHook();
4441     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4442     JSHandle<JSTaggedValue> protoValue(thread_, globalConst->GetDequeIteratorPrototype());
4443     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIDequeIteratorClass());
4444     hclassHandle->SetPrototype(thread_, protoValue);
4445     JSHandle<JSAPIDequeIterator> iter(NewJSObject(hclassHandle));
4446     iter->GetJSHClass()->SetExtensible(true);
4447     iter->SetIteratedDeque(thread_, deque);
4448     iter->SetNextIndex(deque->GetFirst());
4449     return iter;
4450 }
4451 
CopyQueue(const JSHandle<TaggedArray> & old,uint32_t newLength,uint32_t front,uint32_t tail)4452 JSHandle<TaggedArray> ObjectFactory::CopyQueue(const JSHandle<TaggedArray> &old, uint32_t newLength,
4453                                                uint32_t front, uint32_t tail)
4454 {
4455     NewObjectHook();
4456     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), newLength);
4457     auto header = heap_->AllocateYoungOrHugeObject(
4458         JSHClass::Cast(thread_->GlobalConstants()->GetArrayClass().GetTaggedObject()), size);
4459     JSHandle<TaggedArray> newArray(thread_, header);
4460     newArray->InitializeWithSpecialValue(JSTaggedValue::Hole(), newLength, old->GetExtraLength());
4461 
4462     uint32_t curIndex = front;
4463     // newIndex use in new TaggedArray, 0 : New TaggedArray index
4464     uint32_t newIndex = 0;
4465     uint32_t oldCapacity = old->GetLength();
4466     while (curIndex != tail) {
4467         JSTaggedValue value = old->Get(curIndex);
4468         newArray->Set(thread_, newIndex, value);
4469         ASSERT(oldCapacity != 0);
4470         curIndex = (curIndex + 1) % oldCapacity;
4471         newIndex = newIndex + 1;
4472     }
4473     return newArray;
4474 }
4475 
NewJSAPIQueueIterator(const JSHandle<JSAPIQueue> & queue)4476 JSHandle<JSAPIQueueIterator> ObjectFactory::NewJSAPIQueueIterator(const JSHandle<JSAPIQueue> &queue)
4477 {
4478     NewObjectHook();
4479     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4480     JSHandle<JSTaggedValue> protoValue(thread_, globalConst->GetQueueIteratorPrototype());
4481     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIQueueIteratorClass());
4482     hclassHandle->SetPrototype(thread_, protoValue);
4483     JSHandle<JSAPIQueueIterator> iter(NewJSObject(hclassHandle));
4484     iter->GetJSHClass()->SetExtensible(true);
4485     iter->SetIteratedQueue(thread_, queue); // IteratedQueue
4486     iter->SetNextIndex(0);
4487     return iter;
4488 }
4489 
NewJSAPITreeMapIterator(const JSHandle<JSAPITreeMap> & map,IterationKind kind)4490 JSHandle<JSAPITreeMapIterator> ObjectFactory::NewJSAPITreeMapIterator(const JSHandle<JSAPITreeMap> &map,
4491                                                                       IterationKind kind)
4492 {
4493     NewObjectHook();
4494     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4495     JSHandle<JSTaggedValue> proto(thread_, globalConst->GetTreeMapIteratorPrototype());
4496     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPITreeMapIteratorClass());
4497     hclassHandle->SetPrototype(thread_, proto);
4498     JSHandle<JSAPITreeMapIterator> iter(NewJSObject(hclassHandle));
4499     iter->GetJSHClass()->SetExtensible(true);
4500     iter->SetIteratedMap(thread_, map);
4501     iter->SetNextIndex(0);
4502     iter->SetEntries(thread_, JSTaggedValue::Hole());
4503     iter->SetIterationKind(kind);
4504     return iter;
4505 }
4506 
NewJSAPITreeSetIterator(const JSHandle<JSAPITreeSet> & set,IterationKind kind)4507 JSHandle<JSAPITreeSetIterator> ObjectFactory::NewJSAPITreeSetIterator(const JSHandle<JSAPITreeSet> &set,
4508                                                                       IterationKind kind)
4509 {
4510     NewObjectHook();
4511     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4512     JSHandle<JSTaggedValue> proto(thread_, globalConst->GetTreeSetIteratorPrototype());
4513     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPITreeSetIteratorClass());
4514     hclassHandle->SetPrototype(thread_, proto);
4515     JSHandle<JSAPITreeSetIterator> iter(NewJSObject(hclassHandle));
4516     iter->GetJSHClass()->SetExtensible(true);
4517     iter->SetIteratedSet(thread_, set);
4518     iter->SetNextIndex(0);
4519     iter->SetEntries(thread_, JSTaggedValue::Hole());
4520     iter->SetIterationKind(kind);
4521     return iter;
4522 }
4523 
NewJSAPIVector(uint32_t capacity)4524 JSHandle<JSAPIVector> ObjectFactory::NewJSAPIVector(uint32_t capacity)
4525 {
4526     NewObjectHook();
4527     JSHandle<JSFunction> builtinObj(thread_, thread_->GlobalConstants()->GetVectorFunction());
4528     JSHandle<JSAPIVector> obj = JSHandle<JSAPIVector>(NewJSObjectByConstructor(builtinObj));
4529     JSHandle<TaggedArray> newVector = NewTaggedArray(capacity);
4530     obj->SetElements(thread_, newVector);
4531 
4532     return obj;
4533 }
4534 
NewJSAPIVectorIterator(const JSHandle<JSAPIVector> & vector)4535 JSHandle<JSAPIVectorIterator> ObjectFactory::NewJSAPIVectorIterator(const JSHandle<JSAPIVector> &vector)
4536 {
4537     NewObjectHook();
4538     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4539     JSHandle<JSTaggedValue> proto(thread_, globalConst->GetVectorIteratorPrototype());
4540     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIVectorIteratorClass());
4541     hclassHandle->SetPrototype(thread_, proto);
4542     JSHandle<JSAPIVectorIterator> iter(NewJSObject(hclassHandle));
4543     iter->GetJSHClass()->SetExtensible(true);
4544     iter->SetIteratedVector(thread_, vector);
4545     iter->SetNextIndex(0);
4546     return iter;
4547 }
4548 
NewJSAPIBitVector(uint32_t capacity)4549 JSHandle<JSAPIBitVector> ObjectFactory::NewJSAPIBitVector(uint32_t capacity)
4550 {
4551     NewObjectHook();
4552     JSHandle<JSFunction> builtinObj(thread_->GetEcmaVM()->GetGlobalEnv()->GetBitVectorFunction());
4553     JSHandle<JSAPIBitVector> obj = JSHandle<JSAPIBitVector>(NewJSObjectByConstructor(builtinObj));
4554     uint32_t taggedArrayCapacity = (capacity >> JSAPIBitVector::TAGGED_VALUE_BIT_SIZE) + 1;
4555     auto *newBitSetVector = new std::vector<std::bitset<JSAPIBitVector::BIT_SET_LENGTH>>();
4556     newBitSetVector->resize(taggedArrayCapacity, 0);
4557     JSHandle<JSNativePointer> pointer = NewJSNativePointer(newBitSetVector);
4558     obj->SetNativePointer(thread_, pointer);
4559 
4560     return obj;
4561 }
4562 
NewJSAPIBitVectorIterator(const JSHandle<JSAPIBitVector> & bitVector)4563 JSHandle<JSAPIBitVectorIterator> ObjectFactory::NewJSAPIBitVectorIterator(const JSHandle<JSAPIBitVector> &bitVector)
4564 {
4565     NewObjectHook();
4566     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4567     JSHandle<GlobalEnv> env = thread_->GetEcmaVM()->GetGlobalEnv();
4568     JSHandle<JSTaggedValue> proto(env->GetBitVectorIteratorPrototype());
4569     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIBitVectorIteratorClass());
4570     hclassHandle->SetPrototype(thread_, proto);
4571     JSHandle<JSAPIBitVectorIterator> iter(NewJSObject(hclassHandle));
4572     iter->GetJSHClass()->SetExtensible(true);
4573     iter->SetIteratedBitVector(thread_, bitVector);
4574     iter->SetNextIndex(0);
4575     return iter;
4576 }
4577 
NewJSAPILinkedListIterator(const JSHandle<JSAPILinkedList> & linkedList)4578 JSHandle<JSAPILinkedListIterator> ObjectFactory::NewJSAPILinkedListIterator(const JSHandle<JSAPILinkedList> &linkedList)
4579 {
4580     NewObjectHook();
4581     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4582     JSHandle<JSTaggedValue> proto(thread_, globalConst->GetLinkedListIteratorPrototype());
4583     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPILinkedListIteratorClass());
4584     hclassHandle->SetPrototype(thread_, proto);
4585     JSHandle<JSAPILinkedListIterator> iter(NewJSObject(hclassHandle));
4586     iter->GetJSHClass()->SetExtensible(true);
4587     iter->SetIteratedLinkedList(thread_, linkedList->GetDoubleList());
4588     iter->SetNextIndex(0);
4589     const uint32_t linkedListElementStartIndex = 4;
4590     iter->SetDataIndex(linkedListElementStartIndex);
4591     return iter;
4592 }
4593 
NewJSAPIListIterator(const JSHandle<JSAPIList> & List)4594 JSHandle<JSAPIListIterator> ObjectFactory::NewJSAPIListIterator(const JSHandle<JSAPIList> &List)
4595 {
4596     NewObjectHook();
4597     const GlobalEnvConstants *globalConst = thread_->GlobalConstants();
4598     JSHandle<JSTaggedValue> proto(thread_, globalConst->GetListIteratorPrototype());
4599     JSHandle<JSHClass> hclassHandle(globalConst->GetHandledJSAPIListIteratorClass());
4600     hclassHandle->SetPrototype(thread_, proto);
4601     JSHandle<JSAPIListIterator> iter(NewJSObject(hclassHandle));
4602     iter->GetJSHClass()->SetExtensible(true);
4603     iter->SetIteratedList(thread_, List->GetSingleList());
4604     iter->SetNextIndex(0);
4605     const uint32_t linkedListElementStartIndex = 4;
4606     iter->SetDataIndex(linkedListElementStartIndex);
4607     return iter;
4608 }
4609 
NewJSAPIList()4610 JSHandle<JSAPIList> ObjectFactory::NewJSAPIList()
4611 {
4612     NewObjectHook();
4613     JSHandle<JSFunction> function(thread_, thread_->GlobalConstants()->GetListFunction());
4614     return JSHandle<JSAPIList>::Cast(NewJSObjectByConstructor(function));
4615 }
4616 
NewJSAPILinkedList()4617 JSHandle<JSAPILinkedList> ObjectFactory::NewJSAPILinkedList()
4618 {
4619     NewObjectHook();
4620     JSHandle<JSFunction> function(thread_, thread_->GlobalConstants()->GetLinkedListFunction());
4621     return JSHandle<JSAPILinkedList>::Cast(NewJSObjectByConstructor(function));
4622 }
4623 
NewImportEntry()4624 JSHandle<ImportEntry> ObjectFactory::NewImportEntry()
4625 {
4626     JSHandle<JSTaggedValue> defautValue = thread_->GlobalConstants()->GetHandledUndefined();
4627     return NewImportEntry(defautValue, defautValue, defautValue, SharedTypes::UNSENDABLE_MODULE);
4628 }
4629 
NewImportEntry(const JSHandle<JSTaggedValue> & moduleRequest,const JSHandle<JSTaggedValue> & importName,const JSHandle<JSTaggedValue> & localName,SharedTypes sharedTypes)4630 JSHandle<ImportEntry> ObjectFactory::NewImportEntry(const JSHandle<JSTaggedValue> &moduleRequest,
4631                                                     const JSHandle<JSTaggedValue> &importName,
4632                                                     const JSHandle<JSTaggedValue> &localName,
4633                                                     SharedTypes sharedTypes)
4634 {
4635     if (sharedTypes == SharedTypes::SHARED_MODULE) {
4636         return NewSImportEntry(moduleRequest, importName, localName);
4637     }
4638     NewObjectHook();
4639     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4640         JSHClass::Cast(thread_->GlobalConstants()->GetImportEntryClass().GetTaggedObject()));
4641     JSHandle<ImportEntry> obj(thread_, header);
4642     obj->SetModuleRequest(thread_, moduleRequest);
4643     obj->SetImportName(thread_, importName);
4644     obj->SetLocalName(thread_, localName);
4645     return obj;
4646 }
4647 
NewLocalExportEntry()4648 JSHandle<LocalExportEntry> ObjectFactory::NewLocalExportEntry()
4649 {
4650     JSHandle<JSTaggedValue> defautValue = thread_->GlobalConstants()->GetHandledUndefined();
4651     return NewLocalExportEntry(defautValue, defautValue, LocalExportEntry::LOCAL_DEFAULT_INDEX,
4652                                SharedTypes::UNSENDABLE_MODULE);
4653 }
4654 
NewLocalExportEntry(const JSHandle<JSTaggedValue> & exportName,const JSHandle<JSTaggedValue> & localName,const uint32_t index,SharedTypes sharedTypes)4655 JSHandle<LocalExportEntry> ObjectFactory::NewLocalExportEntry(const JSHandle<JSTaggedValue> &exportName,
4656     const JSHandle<JSTaggedValue> &localName, const uint32_t index, SharedTypes sharedTypes)
4657 {
4658     if (sharedTypes == SharedTypes::SHARED_MODULE) {
4659         return NewSLocalExportEntry(exportName, localName, index);
4660     }
4661     NewObjectHook();
4662     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4663         JSHClass::Cast(thread_->GlobalConstants()->GetLocalExportEntryClass().GetTaggedObject()));
4664     JSHandle<LocalExportEntry> obj(thread_, header);
4665     obj->SetExportName(thread_, exportName);
4666     obj->SetLocalName(thread_, localName);
4667     obj->SetLocalIndex(index);
4668     return obj;
4669 }
4670 
NewIndirectExportEntry()4671 JSHandle<IndirectExportEntry> ObjectFactory::NewIndirectExportEntry()
4672 {
4673     JSHandle<JSTaggedValue> defautValue = thread_->GlobalConstants()->GetHandledUndefined();
4674     return NewIndirectExportEntry(defautValue, defautValue, defautValue, SharedTypes::UNSENDABLE_MODULE);
4675 }
4676 
NewIndirectExportEntry(const JSHandle<JSTaggedValue> & exportName,const JSHandle<JSTaggedValue> & moduleRequest,const JSHandle<JSTaggedValue> & importName,SharedTypes sharedTypes)4677 JSHandle<IndirectExportEntry> ObjectFactory::NewIndirectExportEntry(const JSHandle<JSTaggedValue> &exportName,
4678                                                                     const JSHandle<JSTaggedValue> &moduleRequest,
4679                                                                     const JSHandle<JSTaggedValue> &importName,
4680                                                                     SharedTypes sharedTypes)
4681 {
4682     if (sharedTypes == SharedTypes::SHARED_MODULE) {
4683         return NewSIndirectExportEntry(exportName, moduleRequest, importName);
4684     }
4685     NewObjectHook();
4686     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4687         JSHClass::Cast(thread_->GlobalConstants()->GetIndirectExportEntryClass().GetTaggedObject()));
4688     JSHandle<IndirectExportEntry> obj(thread_, header);
4689     obj->SetExportName(thread_, exportName);
4690     obj->SetModuleRequest(thread_, moduleRequest);
4691     obj->SetImportName(thread_, importName);
4692     return obj;
4693 }
4694 
NewStarExportEntry()4695 JSHandle<StarExportEntry> ObjectFactory::NewStarExportEntry()
4696 {
4697     JSHandle<JSTaggedValue> defautValue = thread_->GlobalConstants()->GetHandledUndefined();
4698     return NewStarExportEntry(defautValue, SharedTypes::UNSENDABLE_MODULE);
4699 }
4700 
NewStarExportEntry(const JSHandle<JSTaggedValue> & moduleRequest,SharedTypes sharedTypes)4701 JSHandle<StarExportEntry> ObjectFactory::NewStarExportEntry(const JSHandle<JSTaggedValue> &moduleRequest,
4702                                                             SharedTypes sharedTypes)
4703 {
4704     if (sharedTypes == SharedTypes::SHARED_MODULE) {
4705         return NewSStarExportEntry(moduleRequest);
4706     }
4707     NewObjectHook();
4708     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4709         JSHClass::Cast(thread_->GlobalConstants()->GetStarExportEntryClass().GetTaggedObject()));
4710     JSHandle<StarExportEntry> obj(thread_, header);
4711     obj->SetModuleRequest(thread_, moduleRequest);
4712     return obj;
4713 }
4714 
NewSourceTextModule()4715 JSHandle<SourceTextModule> ObjectFactory::NewSourceTextModule()
4716 {
4717     NewObjectHook();
4718     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4719         JSHClass::Cast(thread_->GlobalConstants()->GetSourceTextModuleClass().GetTaggedObject()));
4720     JSHandle<SourceTextModule> obj(thread_, header);
4721     JSTaggedValue undefinedValue = thread_->GlobalConstants()->GetUndefined();
4722     obj->SetEnvironment(thread_, undefinedValue);
4723     obj->SetNamespace(thread_, undefinedValue);
4724     obj->SetRequestedModules(thread_, undefinedValue);
4725     obj->SetImportEntries(thread_, undefinedValue);
4726     obj->SetLocalExportEntries(thread_, undefinedValue);
4727     obj->SetIndirectExportEntries(thread_, undefinedValue);
4728     obj->SetStarExportEntries(thread_, undefinedValue);
4729     obj->SetNameDictionary(thread_, undefinedValue);
4730     // [[CycleRoot]]: For a module not in a cycle, this would be the module itself.
4731     obj->SetCycleRoot(thread_, obj);
4732     obj->SetTopLevelCapability(thread_, undefinedValue);
4733     obj->SetAsyncParentModules(thread_, undefinedValue);
4734     obj->SetHasTLA(false);
4735     obj->SetAsyncEvaluatingOrdinal(SourceTextModule::NOT_ASYNC_EVALUATED);
4736     obj->SetPendingAsyncDependencies(SourceTextModule::UNDEFINED_INDEX);
4737     obj->SetDFSIndex(SourceTextModule::UNDEFINED_INDEX);
4738     obj->SetDFSAncestorIndex(SourceTextModule::UNDEFINED_INDEX);
4739     obj->SetEvaluationError(SourceTextModule::UNDEFINED_INDEX);
4740     obj->SetStatus(ModuleStatus::UNINSTANTIATED);
4741     obj->SetTypes(ModuleTypes::UNKNOWN);
4742     obj->SetIsNewBcVersion(false);
4743     obj->SetRegisterCounts(UINT16_MAX);
4744     obj->SetLazyImportStatus(ToUintPtr(nullptr));
4745     obj->SetEcmaModuleFilename(ToUintPtr(nullptr));
4746     obj->SetEcmaModuleRecordName(ToUintPtr(nullptr));
4747     obj->SetSharedType(SharedTypes::UNSENDABLE_MODULE);
4748     obj->SetSendableEnv(thread_, undefinedValue);
4749     return obj;
4750 }
4751 
NewResolvedBindingRecord()4752 JSHandle<ResolvedBinding> ObjectFactory::NewResolvedBindingRecord()
4753 {
4754     JSHandle<JSTaggedValue> undefinedValue = thread_->GlobalConstants()->GetHandledUndefined();
4755     JSHandle<SourceTextModule> ecmaModule(undefinedValue);
4756     JSHandle<JSTaggedValue> bindingName(undefinedValue);
4757     return NewResolvedBindingRecord(ecmaModule, bindingName);
4758 }
4759 
NewResolvedBindingRecord(const JSHandle<SourceTextModule> & module,const JSHandle<JSTaggedValue> & bindingName)4760 JSHandle<ResolvedBinding> ObjectFactory::NewResolvedBindingRecord(const JSHandle<SourceTextModule> &module,
4761                                                                   const JSHandle<JSTaggedValue> &bindingName)
4762 {
4763     NewObjectHook();
4764     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4765         JSHClass::Cast(thread_->GlobalConstants()->GetResolvedBindingClass().GetTaggedObject()));
4766     JSHandle<ResolvedBinding> obj(thread_, header);
4767     obj->SetModule(thread_, module);
4768     obj->SetBindingName(thread_, bindingName);
4769     return obj;
4770 }
4771 
NewResolvedIndexBindingRecord()4772 JSHandle<ResolvedIndexBinding> ObjectFactory::NewResolvedIndexBindingRecord()
4773 {
4774     JSHandle<JSTaggedValue> undefinedValue = thread_->GlobalConstants()->GetHandledUndefined();
4775     JSHandle<SourceTextModule> ecmaModule(undefinedValue);
4776     int32_t index = 0;
4777     return NewResolvedIndexBindingRecord(ecmaModule, index);
4778 }
4779 
NewResolvedIndexBindingRecord(const JSHandle<SourceTextModule> & module,int32_t index)4780 JSHandle<ResolvedIndexBinding> ObjectFactory::NewResolvedIndexBindingRecord(const JSHandle<SourceTextModule> &module,
4781                                                                             int32_t index)
4782 {
4783     NewObjectHook();
4784     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4785         JSHClass::Cast(thread_->GlobalConstants()->GetResolvedIndexBindingClass().GetTaggedObject()));
4786     JSHandle<ResolvedIndexBinding> obj(thread_, header);
4787     obj->SetModule(thread_, module);
4788     obj->SetIndex(index);
4789     return obj;
4790 }
4791 
NewCellRecord()4792 JSHandle<CellRecord> ObjectFactory::NewCellRecord()
4793 {
4794     NewObjectHook();
4795     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4796         JSHClass::Cast(thread_->GlobalConstants()->GetCellRecordClass().GetTaggedObject()));
4797     JSHandle<CellRecord> obj(thread_, header);
4798     obj->SetWeakRefTarget(thread_, JSTaggedValue::Undefined());
4799     obj->SetHeldValue(thread_, JSTaggedValue::Undefined());
4800     return obj;
4801 }
4802 
CreateIteratorResultInstanceClass(const JSHandle<GlobalEnv> & env)4803 JSHandle<JSHClass> ObjectFactory::CreateIteratorResultInstanceClass(const JSHandle<GlobalEnv> &env)
4804 {
4805     auto globalConst = thread_->GlobalConstants();
4806     JSHandle<JSTaggedValue> proto = env->GetObjectFunctionPrototype();
4807     JSHandle<JSHClass> iterResultClass = NewEcmaHClass(JSObject::SIZE, JSType::JS_OBJECT, proto);
4808 
4809     uint32_t fieldOrder = 0;
4810     JSHandle<LayoutInfo> layoutInfoHandle = CreateLayoutInfo(2); // 2 means two field
4811     {
4812         ASSERT(JSIterator::VALUE_INLINE_PROPERTY_INDEX == fieldOrder);
4813         PropertyAttributes attributes = PropertyAttributes::Default();
4814         attributes.SetIsInlinedProps(true);
4815         attributes.SetRepresentation(Representation::TAGGED);
4816         attributes.SetOffset(fieldOrder);
4817         layoutInfoHandle->AddKey(thread_, fieldOrder++, globalConst->GetValueString(), attributes);
4818     }
4819     {
4820         ASSERT(JSIterator::DONE_INLINE_PROPERTY_INDEX == fieldOrder);
4821         PropertyAttributes attributes = PropertyAttributes::Default();
4822         attributes.SetIsInlinedProps(true);
4823         attributes.SetRepresentation(Representation::TAGGED);
4824         attributes.SetOffset(fieldOrder);
4825         layoutInfoHandle->AddKey(thread_, fieldOrder++, globalConst->GetDoneString(), attributes);
4826     }
4827 
4828     {
4829         iterResultClass->SetLayout(thread_, layoutInfoHandle);
4830         iterResultClass->SetNumberOfProps(fieldOrder);
4831     }
4832     return iterResultClass;
4833 }
4834 
NewOldSpaceObject(const JSHandle<JSHClass> & hclass)4835 TaggedObject *ObjectFactory::NewOldSpaceObject(const JSHandle<JSHClass> &hclass)
4836 {
4837     NewObjectHook();
4838     TaggedObject *header = heap_->AllocateOldOrHugeObject(*hclass);
4839     uint32_t inobjPropCount = hclass->GetInlinedProperties();
4840     if (inobjPropCount > 0) {
4841         InitializeExtraProperties(hclass, header, inobjPropCount);
4842     }
4843     return header;
4844 }
4845 
NewOldSpaceJSObject(const JSHandle<JSHClass> & jshclass)4846 JSHandle<JSObject> ObjectFactory::NewOldSpaceJSObject(const JSHandle<JSHClass> &jshclass)
4847 {
4848     JSHandle<JSObject> obj(thread_, JSObject::Cast(NewOldSpaceObject(jshclass)));
4849     JSHandle<TaggedArray> emptyArray = EmptyArray();
4850     obj->InitializeHash();
4851     obj->SetElements(thread_, emptyArray);
4852     obj->SetProperties(thread_, emptyArray);
4853     return obj;
4854 }
4855 
NewOldSpaceTaggedArray(uint32_t length,JSTaggedValue initVal)4856 JSHandle<TaggedArray> ObjectFactory::NewOldSpaceTaggedArray(uint32_t length, JSTaggedValue initVal)
4857 {
4858     return NewTaggedArray(length, initVal, MemSpaceType::OLD_SPACE);
4859 }
4860 
NewJSStableArrayWithElements(const JSHandle<TaggedArray> & elements)4861 JSHandle<JSArray> ObjectFactory::NewJSStableArrayWithElements(const JSHandle<TaggedArray> &elements)
4862 {
4863     JSHandle<JSHClass> cls(thread_,
4864                            JSHandle<JSFunction>::Cast(vm_->GetGlobalEnv()->GetArrayFunction())->GetProtoOrHClass());
4865     JSHandle<JSArray> array = JSHandle<JSArray>::Cast(NewJSObject(cls));
4866     array->SetElements(thread_, elements);
4867     array->SetLength(elements->GetLength());
4868     array->SetTrackInfo(thread_, JSTaggedValue::Undefined());
4869     auto accessor = thread_->GlobalConstants()->GetArrayLengthAccessor();
4870     array->SetPropertyInlinedProps(thread_, JSArray::LENGTH_INLINE_PROPERTY_INDEX, accessor);
4871     return array;
4872 }
4873 
NewJSAsyncGeneratorFunction(const JSHandle<Method> & method)4874 JSHandle<JSFunction> ObjectFactory::NewJSAsyncGeneratorFunction(const JSHandle<Method> &method)
4875 {
4876     NewObjectHook();
4877     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
4878 
4879     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetAsyncGeneratorFunctionClass());
4880     JSHandle<JSFunction> asyncGeneratorFunc = JSHandle<JSFunction>::Cast(NewJSObject(hclass));
4881     JSFunction::InitializeJSFunction(thread_, asyncGeneratorFunc, FunctionKind::ASYNC_GENERATOR_FUNCTION);
4882     asyncGeneratorFunc->SetMethod(thread_, method);
4883     return asyncGeneratorFunc;
4884 }
4885 
NewAsyncGeneratorRequest()4886 JSHandle<AsyncGeneratorRequest> ObjectFactory::NewAsyncGeneratorRequest()
4887 {
4888     NewObjectHook();
4889     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4890         JSHClass::Cast(thread_->GlobalConstants()->GetAsyncGeneratorRequestRecordClass().GetTaggedObject()));
4891     JSHandle<AsyncGeneratorRequest> obj(thread_, header);
4892     obj->SetCompletion(thread_, JSTaggedValue::Undefined());
4893     obj->SetCapability(thread_, JSTaggedValue::Undefined());
4894     return obj;
4895 }
4896 
NewAsyncIteratorRecord(const JSHandle<JSTaggedValue> & itor,const JSHandle<JSTaggedValue> & next,bool done)4897 JSHandle<AsyncIteratorRecord> ObjectFactory::NewAsyncIteratorRecord(const JSHandle<JSTaggedValue> &itor,
4898                                                                     const JSHandle<JSTaggedValue> &next, bool done)
4899 {
4900     NewObjectHook();
4901     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4902         JSHClass::Cast(thread_->GlobalConstants()->GetAsyncIteratorRecordClass().GetTaggedObject()));
4903     JSHandle<AsyncIteratorRecord> obj(thread_, header);
4904     obj->SetIterator(thread_, itor.GetTaggedValue());
4905     obj->SetNextMethod(thread_, next.GetTaggedValue());
4906     obj->SetDone(done);
4907     return obj;
4908 }
4909 
NewAOTLiteralInfo(uint32_t length,JSTaggedValue initVal)4910 JSHandle<AOTLiteralInfo> ObjectFactory::NewAOTLiteralInfo(uint32_t length, JSTaggedValue initVal)
4911 {
4912     NewObjectHook();
4913     size_t size = AOTLiteralInfo::ComputeSize(length);
4914     auto header = heap_->AllocateYoungOrHugeObject(
4915         JSHClass::Cast(thread_->GlobalConstants()->GetAOTLiteralInfoClass().GetTaggedObject()), size);
4916 
4917     JSHandle<AOTLiteralInfo> aotLiteralInfo(thread_, header);
4918     aotLiteralInfo->InitializeWithSpecialValue(initVal, length);
4919     return aotLiteralInfo;
4920 }
4921 
NewExtraProfileTypeInfo()4922 JSHandle<ExtraProfileTypeInfo> ObjectFactory::NewExtraProfileTypeInfo()
4923 {
4924     NewObjectHook();
4925     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4926         JSHClass::Cast(thread_->GlobalConstants()->GetExtraProfileTypeInfoClass().GetTaggedObject()));
4927     JSHandle<ExtraProfileTypeInfo> extraProfileTypeInfo(thread_, header);
4928     extraProfileTypeInfo->SetReceiverObject(thread_, JSTaggedValue::Undefined());
4929     extraProfileTypeInfo->SetHolderObject(thread_, JSTaggedValue::Undefined());
4930     return extraProfileTypeInfo;
4931 }
4932 
NewProfileTypeInfoCell(const JSHandle<JSTaggedValue> & value)4933 JSHandle<ProfileTypeInfoCell> ObjectFactory::NewProfileTypeInfoCell(const JSHandle<JSTaggedValue> &value)
4934 {
4935     NewObjectHook();
4936     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4937         JSHClass::Cast(thread_->GlobalConstants()->GetProfileTypeInfoCell0Class().GetTaggedObject()));
4938     JSHandle<ProfileTypeInfoCell> profileTypeInfoCell(thread_, header);
4939     profileTypeInfoCell->SetValue(thread_, value.GetTaggedValue());
4940     profileTypeInfoCell->SetMachineCode(thread_, JSTaggedValue::Hole());
4941     profileTypeInfoCell->SetHandle(thread_, JSTaggedValue::Undefined());
4942     profileTypeInfoCell->SetExtraInfoMap(thread_, JSTaggedValue::Undefined());
4943     return profileTypeInfoCell;
4944 }
4945 
NewFunctionTemplate(const JSHandle<Method> & method,const JSHandle<JSTaggedValue> & module,int32_t length)4946 JSHandle<FunctionTemplate> ObjectFactory::NewFunctionTemplate(
4947     const JSHandle<Method> &method, const JSHandle<JSTaggedValue> &module, int32_t length)
4948 {
4949     NewObjectHook();
4950     auto globalConstants = thread_->GlobalConstants();
4951     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4952         JSHClass::Cast(globalConstants->GetFunctionTemplateClass().GetTaggedObject()));
4953     JSHandle<FunctionTemplate> funcTemp(thread_, header);
4954     funcTemp->SetMethod(thread_, method);
4955     funcTemp->SetModule(thread_, module);
4956     funcTemp->SetRawProfileTypeInfo(thread_, globalConstants->GetEmptyProfileTypeInfoCell(), SKIP_BARRIER);
4957     funcTemp->SetLength(length);
4958     return funcTemp;
4959 }
4960 
NewVTable(uint32_t length,JSTaggedValue initVal)4961 JSHandle<VTable> ObjectFactory::NewVTable(uint32_t length, JSTaggedValue initVal)
4962 {
4963     NewObjectHook();
4964     size_t size = TaggedArray::ComputeSize(JSTaggedValue::TaggedTypeSize(), length * VTable::TUPLE_SIZE);
4965     auto header = heap_->AllocateYoungOrHugeObject(
4966         JSHClass::Cast(thread_->GlobalConstants()->GetVTableClass().GetTaggedObject()), size);
4967 
4968     JSHandle<VTable> vtable(thread_, header);
4969     vtable->InitializeWithSpecialValue(initVal, length * VTable::TUPLE_SIZE);
4970     return vtable;
4971 }
4972 
NewClassLiteral()4973 JSHandle<ClassLiteral> ObjectFactory::NewClassLiteral()
4974 {
4975     NewObjectHook();
4976 
4977     TaggedObject *header = heap_->AllocateYoungOrHugeObject(
4978         JSHClass::Cast(thread_->GlobalConstants()->GetClassLiteralClass().GetTaggedObject()));
4979     JSHandle<TaggedArray> emptyArray = EmptyArray();
4980 
4981     JSHandle<ClassLiteral> classLiteral(thread_, header);
4982     classLiteral->SetArray(thread_, emptyArray);
4983     classLiteral->SetIsAOTUsed(false);
4984 
4985     return classLiteral;
4986 }
4987 
NewJSFunction(const JSHandle<Method> & methodHandle)4988 JSHandle<JSFunction> ObjectFactory::NewJSFunction(const JSHandle<Method> &methodHandle)
4989 {
4990     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
4991     FunctionKind kind = methodHandle->GetFunctionKind();
4992     JSHandle<JSHClass> hclass;
4993     switch (kind) {
4994         case FunctionKind::NORMAL_FUNCTION:
4995         case FunctionKind::BASE_CONSTRUCTOR: {
4996             hclass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithProto());
4997             break;
4998         }
4999         case FunctionKind::ARROW_FUNCTION: {
5000             hclass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithoutProto());
5001             break;
5002         }
5003         case FunctionKind::GENERATOR_FUNCTION: {
5004             hclass = JSHandle<JSHClass>::Cast(env->GetGeneratorFunctionClass());
5005             break;
5006         }
5007         case FunctionKind::CONCURRENT_FUNCTION:
5008         case FunctionKind::ASYNC_ARROW_FUNCTION:
5009         case FunctionKind::ASYNC_FUNCTION: {
5010             hclass = JSHandle<JSHClass>::Cast(env->GetAsyncFunctionClass());
5011             break;
5012         }
5013         case FunctionKind::ASYNC_GENERATOR_FUNCTION: {
5014             hclass = JSHandle<JSHClass>::Cast(env->GetAsyncGeneratorFunctionClass());
5015             break;
5016         }
5017         default:
5018             LOG_ECMA(FATAL) << "this branch is unreachable";
5019             UNREACHABLE();
5020     }
5021 
5022     JSHandle<JSFunction> jsfunc = NewJSFunctionByHClass(methodHandle, hclass);
5023     ASSERT_NO_ABRUPT_COMPLETION(thread_);
5024     return jsfunc;
5025 }
5026 
NewJSFunction(const JSHandle<Method> & methodHandle,const JSHandle<JSTaggedValue> & homeObject)5027 JSHandle<JSFunction> ObjectFactory::NewJSFunction(const JSHandle<Method> &methodHandle,
5028                                                   const JSHandle<JSTaggedValue> &homeObject)
5029 {
5030     ASSERT(homeObject->IsECMAObject());
5031     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
5032     JSHandle<JSHClass> hclass = JSHandle<JSHClass>::Cast(env->GetFunctionClassWithoutProto());
5033 
5034     JSHandle<JSFunction> jsFunc = NewJSFunctionByHClass(methodHandle, hclass);
5035     jsFunc->SetHomeObject(thread_, homeObject);
5036     ASSERT_NO_ABRUPT_COMPLETION(thread_);
5037     return jsFunc;
5038 }
5039 
CreateJSObjectWithProperties(size_t propertyCount,const Local<JSValueRef> * keys,const PropertyDescriptor * descs)5040 JSHandle<JSTaggedValue> ObjectFactory::CreateJSObjectWithProperties(size_t propertyCount,
5041                                                                     const Local<JSValueRef> *keys,
5042                                                                     const PropertyDescriptor *descs)
5043 {
5044     if (!CanObjectLiteralHClassCache(propertyCount)) {
5045         return CreateLargeJSObjectWithProperties(propertyCount, keys, descs);
5046     }
5047 
5048     // At least 4 inlined slot
5049     int inlineProps = std::max(static_cast<int>(propertyCount), JSHClass::DEFAULT_CAPACITY_OF_IN_OBJECTS);
5050     JSMutableHandle<JSHClass> hclassHandle(thread_, GetObjectLiteralRootHClass(inlineProps));
5051     for (size_t i = 0; i < propertyCount; ++i) {
5052         JSMutableHandle<JSTaggedValue> key(JSNApiHelper::ToJSMutableHandle(keys[i]));
5053         if (key->IsString() && !EcmaStringAccessor(key.GetTaggedValue()).IsInternString()) {
5054             // update string stable
5055             key.Update(JSTaggedValue(InternString(key)));
5056         }
5057         ASSERT(EcmaStringAccessor(key->GetTaggedObject()).IsInternString());
5058         if (UNLIKELY(!JSTaggedValue::IsPureString(key.GetTaggedValue()))) {
5059             THROW_TYPE_ERROR_AND_RETURN(thread_, "property key must be string and can not convert into element index",
5060                                         JSHandle<JSTaggedValue>());
5061         }
5062         PropertyAttributes attr(descs[i]);
5063         attr.SetIsInlinedProps(true);
5064         attr.SetOffset(i);
5065         attr.SetRepresentation(Representation::TAGGED);
5066         auto value = descs[i].GetValue().GetTaggedValue();
5067         auto rep = PropertyAttributes::TranslateToRep(value);
5068         hclassHandle.Update(JSHClass::SetPropertyOfObjHClass<true>(thread_, hclassHandle, key, attr, rep));
5069         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread_, JSHandle<JSTaggedValue>());
5070     }
5071     JSHandle<JSObject> object = NewJSObject(hclassHandle);
5072 
5073     for (size_t i = 0; i < propertyCount; ++i) {
5074         object->SetPropertyInlinedProps<true>(thread_, i, descs[i].GetValue().GetTaggedValue());
5075     }
5076     return JSHandle<JSTaggedValue>(object);
5077 }
5078 
CreateLargeJSObjectWithProperties(size_t propertyCount,const Local<JSValueRef> * keys,const PropertyDescriptor * descs)5079 JSHandle<JSTaggedValue> ObjectFactory::CreateLargeJSObjectWithProperties(size_t propertyCount,
5080                                                                          const Local<JSValueRef> *keys,
5081                                                                          const PropertyDescriptor *descs)
5082 {
5083     ASSERT(!CanObjectLiteralHClassCache(propertyCount));
5084     if (UNLIKELY(propertyCount > PropertyAttributes::MAX_FAST_PROPS_CAPACITY)) {
5085         return CreateDictionaryJSObjectWithProperties(propertyCount, keys, descs);
5086     }
5087     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
5088     JSHandle<JSTaggedValue> objFuncProto = env->GetObjectFunctionPrototype();
5089 
5090     JSHandle<JSHClass> hClassHandle = NewEcmaHClass(JSObject::SIZE, propertyCount, JSType::JS_OBJECT, objFuncProto);
5091     JSHandle<LayoutInfo> layoutHandle = CreateLayoutInfo(propertyCount);
5092     JSHandle<JSObject> object = NewJSObject(hClassHandle);
5093 
5094     for (size_t i = 0; i < propertyCount; ++i) {
5095         JSMutableHandle<JSTaggedValue> key(JSNApiHelper::ToJSMutableHandle(keys[i]));
5096         if (key->IsString() && !EcmaStringAccessor(key.GetTaggedValue()).IsInternString()) {
5097             // update string stable
5098             key.Update(JSTaggedValue(InternString(key)));
5099         }
5100         ASSERT(EcmaStringAccessor(key->GetTaggedObject()).IsInternString());
5101         if (UNLIKELY(!JSTaggedValue::IsPureString(key.GetTaggedValue()))) {
5102             THROW_TYPE_ERROR_AND_RETURN(thread_, "property key must be string and can not convert into element index",
5103                                         JSHandle<JSTaggedValue>());
5104         }
5105         PropertyAttributes attr(descs[i]);
5106         attr.SetIsInlinedProps(true);
5107         attr.SetOffset(i);
5108         LayoutInfo *layout = LayoutInfo::Cast(layoutHandle.GetTaggedValue().GetTaggedObject());
5109         layout->AddKey<true>(thread_, i, key.GetTaggedValue(), attr);
5110         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread_, JSHandle<JSTaggedValue>());
5111         object->SetPropertyInlinedProps<true>(thread_, i, descs[i].GetValue().GetTaggedValue());
5112     }
5113     hClassHandle->SetNumberOfProps(propertyCount);
5114     hClassHandle->SetLayout(thread_, layoutHandle);
5115     return JSHandle<JSTaggedValue>(object);
5116 }
5117 
CreateDictionaryJSObjectWithProperties(size_t propertyCount,const Local<JSValueRef> * keys,const PropertyDescriptor * descs)5118 JSHandle<JSTaggedValue> ObjectFactory::CreateDictionaryJSObjectWithProperties(size_t propertyCount,
5119                                                                               const Local<JSValueRef> *keys,
5120                                                                               const PropertyDescriptor *descs)
5121 {
5122     ASSERT(propertyCount > PropertyAttributes::MAX_FAST_PROPS_CAPACITY);
5123     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
5124     JSHandle<JSTaggedValue> objFuncProto = env->GetObjectFunctionPrototype();
5125     JSHandle<JSHClass> hClassHandle = NewEcmaHClass(JSObject::SIZE, 0, JSType::JS_OBJECT, objFuncProto);
5126     hClassHandle->SetNumberOfProps(0);
5127     hClassHandle->SetIsDictionaryMode(true);
5128     JSHandle<JSObject> object = NewJSObject(hClassHandle);
5129 
5130     JSMutableHandle<NameDictionary> dict(
5131         thread_, NameDictionary::Create(thread_, NameDictionary::ComputeHashTableSize(propertyCount)));
5132     for (size_t i = 0; i < propertyCount; ++i) {
5133         JSMutableHandle<JSTaggedValue> key(JSNApiHelper::ToJSMutableHandle(keys[i]));
5134         if (key->IsString() && !EcmaStringAccessor(key.GetTaggedValue()).IsInternString()) {
5135             // update string stable
5136             key.Update(JSTaggedValue(InternString(key)));
5137         }
5138         ASSERT(EcmaStringAccessor(key->GetTaggedObject()).IsInternString());
5139         if (UNLIKELY(!JSTaggedValue::IsPureString(key.GetTaggedValue()))) {
5140             THROW_TYPE_ERROR_AND_RETURN(thread_, "property key must be string and can not convert into element index",
5141                                         JSHandle<JSTaggedValue>());
5142         }
5143         PropertyAttributes attr(descs[i]);
5144         dict.Update(NameDictionary::PutIfAbsent(thread_, dict, key, descs[i].GetValue(), attr));
5145     }
5146     if (UNLIKELY(dict->EntriesCount() != static_cast<int>(propertyCount))) {
5147         THROW_TYPE_ERROR_AND_RETURN(thread_, "property keys can not duplicate", JSHandle<JSTaggedValue>());
5148     }
5149     object->SetProperties(thread_, dict);
5150     return JSHandle<JSTaggedValue>(object);
5151 }
5152 
CreateJSObjectWithNamedProperties(size_t propertyCount,const char ** keys,const Local<JSValueRef> * values)5153 JSHandle<JSTaggedValue> ObjectFactory::CreateJSObjectWithNamedProperties(size_t propertyCount, const char **keys,
5154                                                                          const Local<JSValueRef> *values)
5155 {
5156     if (!CanObjectLiteralHClassCache(propertyCount)) {
5157         return CreateLargeJSObjectWithNamedProperties(propertyCount, keys, values);
5158     }
5159 
5160     // At least 4 inlined slot
5161     int inlineProps = std::max(static_cast<int>(propertyCount), JSHClass::DEFAULT_CAPACITY_OF_IN_OBJECTS);
5162     JSMutableHandle<JSHClass> hclassHandle(thread_, GetObjectLiteralRootHClass(inlineProps));
5163     for (size_t i = 0; i < propertyCount; ++i) {
5164         JSHandle<JSTaggedValue> key(NewFromUtf8(keys[i]));
5165         ASSERT(EcmaStringAccessor(key->GetTaggedObject()).IsInternString());
5166         if (UNLIKELY(!JSTaggedValue::IsPureString(key.GetTaggedValue()))) {
5167             THROW_TYPE_ERROR_AND_RETURN(thread_, "property key must be string and can not convert into element index",
5168                                         JSHandle<JSTaggedValue>());
5169         }
5170         PropertyAttributes attr(PropertyAttributes::GetDefaultAttributes());
5171         attr.SetIsInlinedProps(true);
5172         attr.SetOffset(i);
5173         attr.SetRepresentation(Representation::TAGGED);
5174         auto value = JSNApiHelper::ToJSHandle(values[i]).GetTaggedValue();
5175         auto rep = PropertyAttributes::TranslateToRep(value);
5176         hclassHandle.Update(JSHClass::SetPropertyOfObjHClass<true>(thread_, hclassHandle, key, attr, rep));
5177         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread_, JSHandle<JSTaggedValue>());
5178     }
5179     JSHandle<JSObject> object = NewJSObject(hclassHandle);
5180 
5181     for (size_t i = 0; i < propertyCount; ++i) {
5182         object->SetPropertyInlinedProps<true>(thread_, i, JSNApiHelper::ToJSHandle(values[i]).GetTaggedValue());
5183     }
5184     return JSHandle<JSTaggedValue>(object);
5185 }
5186 
CreateLargeJSObjectWithNamedProperties(size_t propertyCount,const char ** keys,const Local<JSValueRef> * values)5187 JSHandle<JSTaggedValue> ObjectFactory::CreateLargeJSObjectWithNamedProperties(size_t propertyCount, const char **keys,
5188                                                                               const Local<JSValueRef> *values)
5189 {
5190     ASSERT(!CanObjectLiteralHClassCache(propertyCount));
5191     if (UNLIKELY(propertyCount > PropertyAttributes::MAX_FAST_PROPS_CAPACITY)) {
5192         return CreateDictionaryJSObjectWithNamedProperties(propertyCount, keys, values);
5193     }
5194     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
5195     JSHandle<JSTaggedValue> objFuncProto = env->GetObjectFunctionPrototype();
5196 
5197     JSHandle<JSHClass> hClassHandle = NewEcmaHClass(JSObject::SIZE, propertyCount, JSType::JS_OBJECT, objFuncProto);
5198     JSHandle<LayoutInfo> layoutHandle = CreateLayoutInfo(propertyCount);
5199     JSHandle<JSObject> object = NewJSObject(hClassHandle);
5200 
5201     for (size_t i = 0; i < propertyCount; ++i) {
5202         JSHandle<JSTaggedValue> key(NewFromUtf8(keys[i]));
5203         ASSERT(EcmaStringAccessor(key->GetTaggedObject()).IsInternString());
5204         if (UNLIKELY(!JSTaggedValue::IsPureString(key.GetTaggedValue()))) {
5205             THROW_TYPE_ERROR_AND_RETURN(thread_, "property key must be string and can not convert into element index",
5206                                         JSHandle<JSTaggedValue>());
5207         }
5208         PropertyAttributes attr(PropertyAttributes::GetDefaultAttributes());
5209         attr.SetIsInlinedProps(true);
5210         attr.SetOffset(i);
5211         LayoutInfo *layout = LayoutInfo::Cast(layoutHandle.GetTaggedValue().GetTaggedObject());
5212         layout->AddKey<true>(thread_, i, key.GetTaggedValue(), attr);
5213         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread_, JSHandle<JSTaggedValue>());
5214         object->SetPropertyInlinedProps<true>(thread_, i, JSNApiHelper::ToJSHandle(values[i]).GetTaggedValue());
5215     }
5216     hClassHandle->SetNumberOfProps(propertyCount);
5217     hClassHandle->SetLayout(thread_, layoutHandle);
5218     return JSHandle<JSTaggedValue>(object);
5219 }
5220 
CreateDictionaryJSObjectWithNamedProperties(size_t propertyCount,const char ** keys,const Local<JSValueRef> * values)5221 JSHandle<JSTaggedValue> ObjectFactory::CreateDictionaryJSObjectWithNamedProperties(size_t propertyCount,
5222                                                                                    const char **keys,
5223                                                                                    const Local<JSValueRef> *values)
5224 {
5225     ASSERT(propertyCount > PropertyAttributes::MAX_FAST_PROPS_CAPACITY);
5226     JSHandle<GlobalEnv> env = vm_->GetGlobalEnv();
5227     JSHandle<JSTaggedValue> objFuncProto = env->GetObjectFunctionPrototype();
5228     JSHandle<JSHClass> hClassHandle = NewEcmaHClass(JSObject::SIZE, 0, JSType::JS_OBJECT, objFuncProto);
5229     hClassHandle->SetNumberOfProps(0);
5230     hClassHandle->SetIsDictionaryMode(true);
5231     JSHandle<JSObject> object = NewJSObject(hClassHandle);
5232 
5233     JSMutableHandle<NameDictionary> dict(
5234         thread_, NameDictionary::Create(thread_, NameDictionary::ComputeHashTableSize(propertyCount)));
5235     for (size_t i = 0; i < propertyCount; ++i) {
5236         JSHandle<JSTaggedValue> key(NewFromUtf8(keys[i]));
5237         ASSERT(EcmaStringAccessor(key->GetTaggedObject()).IsInternString());
5238         if (UNLIKELY(!JSTaggedValue::IsPureString(key.GetTaggedValue()))) {
5239             THROW_TYPE_ERROR_AND_RETURN(thread_, "property key must be string and can not convert into element index",
5240                                         JSHandle<JSTaggedValue>());
5241         }
5242         PropertyAttributes attr(PropertyAttributes::GetDefaultAttributes());
5243         dict.Update(NameDictionary::PutIfAbsent(thread_, dict, key, JSNApiHelper::ToJSHandle(values[i]), attr));
5244     }
5245     if (UNLIKELY(dict->EntriesCount() != static_cast<int>(propertyCount))) {
5246         THROW_TYPE_ERROR_AND_RETURN(thread_, "property keys can not duplicate", JSHandle<JSTaggedValue>());
5247     }
5248     object->SetProperties(thread_, dict);
5249     return JSHandle<JSTaggedValue>(object);
5250 }
5251 
FillFreeMemoryRange(uintptr_t start,uintptr_t end)5252 void ObjectFactory::FillFreeMemoryRange(uintptr_t start, uintptr_t end)
5253 {
5254     ASSERT(start <= end);
5255     ASSERT(start % static_cast<uint8_t>(MemAlignment::MEM_ALIGN_OBJECT) == 0);
5256     ASSERT(end % static_cast<uint8_t>(MemAlignment::MEM_ALIGN_OBJECT) == 0);
5257     while (start < end) {
5258         Barriers::SetPrimitive<JSTaggedType>(reinterpret_cast<void*>(start), 0, FREE_MEMMORY_ADDRESS_ZAM_VALUE);
5259         start += sizeof(JSTaggedType);
5260     }
5261 }
5262 }  // namespace panda::ecmascript
5263