1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef ECMASCRIPT_JSNATIVEPOINTER_H 17 #define ECMASCRIPT_JSNATIVEPOINTER_H 18 19 #include "ecmascript/ecma_macros.h" 20 #include "ecmascript/mem/tagged_object.h" 21 #include "ecmascript/mem/native_area_allocator.h" 22 23 namespace panda::ecmascript { 24 using DeleteEntryPoint = void (*)(void *, void *); 25 26 // Used for the requirement of ACE that wants to associated a registered C++ resource with a JSObject. 27 class JSNativePointer : public TaggedObject { 28 public: Cast(TaggedObject * object)29 static JSNativePointer *Cast(TaggedObject *object) 30 { 31 ASSERT(JSTaggedValue(object).IsJSNativePointer()); 32 return reinterpret_cast<JSNativePointer *>(object); 33 } 34 ResetExternalPointer(void * externalPointer)35 inline void ResetExternalPointer(void *externalPointer) 36 { 37 DeleteExternalPointer(); 38 SetExternalPointer(externalPointer); 39 } 40 Destroy()41 inline void Destroy() 42 { 43 DeleteExternalPointer(); 44 SetExternalPointer(nullptr); 45 SetDeleter(nullptr); 46 SetData(nullptr); 47 SetNativeFlag(NativeFlag::NO_DIV); 48 } 49 Detach()50 inline void Detach() 51 { 52 // Keep other fields accessible after detached 53 SetDeleter(nullptr); 54 } 55 56 static constexpr size_t POINTER_OFFSET = TaggedObjectSize(); 57 ACCESSORS_NATIVE_FIELD(ExternalPointer, void, POINTER_OFFSET, DELETER_OFFSET); 58 ACCESSORS_PRIMITIVE_FIELD(Deleter, DeleteEntryPoint, DELETER_OFFSET, DATA_OFFSET) 59 ACCESSORS_NATIVE_FIELD(Data, void, DATA_OFFSET, DATA_SIZE_OFFSET); 60 ACCESSORS_PRIMITIVE_FIELD(BindingSize, uint64_t, DATA_SIZE_OFFSET, FLAG_OFFSET); 61 // native memory statistic flag 62 ACCESSORS_PRIMITIVE_FIELD(NativeFlag, NativeFlag, FLAG_OFFSET, LAST_OFFSET); 63 DEFINE_ALIGN_SIZE(LAST_OFFSET); 64 DECL_VISIT_NATIVE_FIELD(POINTER_OFFSET,DATA_SIZE_OFFSET)65 DECL_VISIT_NATIVE_FIELD(POINTER_OFFSET, DATA_SIZE_OFFSET) 66 67 private: 68 inline void DeleteExternalPointer() 69 { 70 void *externalPointer = GetExternalPointer(); 71 DeleteEntryPoint deleter = GetDeleter(); 72 if (deleter != nullptr) { 73 deleter(externalPointer, GetData()); 74 } 75 } 76 }; 77 } // namespace panda::ecmascript 78 #endif // ECMASCRIPT_JSNATIVEPOINTER_H 79