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 22 namespace panda::ecmascript { 23 using DeleteEntryPoint = void (*)(void *, void *); 24 25 // Used for the requirement of ACE that wants to associated a registered C++ resource with a JSObject. 26 class JSNativePointer : public TaggedObject { 27 public: Cast(ObjectHeader * object)28 static JSNativePointer *Cast(ObjectHeader *object) 29 { 30 ASSERT(JSTaggedValue(object).IsJSNativePointer()); 31 return reinterpret_cast<JSNativePointer *>(object); 32 } 33 ResetExternalPointer(void * externalPointer)34 inline void ResetExternalPointer(void *externalPointer) 35 { 36 DeleteExternalPointer(); 37 SetExternalPointer(externalPointer); 38 } 39 Destroy()40 inline void Destroy() 41 { 42 DeleteExternalPointer(); 43 SetExternalPointer(nullptr); 44 SetDeleter(nullptr); 45 SetData(nullptr); 46 } 47 48 static constexpr size_t POINTER_OFFSET = TaggedObjectSize(); 49 ACCESSORS_NATIVE_FIELD(ExternalPointer, void, POINTER_OFFSET, DELETER_OFFSET); 50 ACCESSORS_PRIMITIVE_FIELD(Deleter, DeleteEntryPoint, DELETER_OFFSET, DATA_OFFSET) 51 ACCESSORS_NATIVE_FIELD(Data, void, DATA_OFFSET, LAST_OFFSET); 52 DEFINE_ALIGN_SIZE(LAST_OFFSET); 53 54 private: DeleteExternalPointer()55 inline void DeleteExternalPointer() 56 { 57 void *externalPointer = GetExternalPointer(); 58 if (externalPointer != nullptr) { 59 DeleteEntryPoint deleter = GetDeleter(); 60 if (deleter != nullptr) { 61 deleter(externalPointer, GetData()); 62 } 63 } 64 } 65 }; 66 } // namespace panda::ecmascript 67 #endif // ECMASCRIPT_JSNATIVEPOINTER_H 68