• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #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(TaggedObject * object)28     static JSNativePointer *Cast(TaggedObject *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 
Detach()48     inline void Detach()
49     {
50         // Keep other fields accessible after detached
51         SetDeleter(nullptr);
52     }
53 
54     static constexpr size_t POINTER_OFFSET = TaggedObjectSize();
55     ACCESSORS_NATIVE_FIELD(ExternalPointer, void, POINTER_OFFSET, DELETER_OFFSET);
56     ACCESSORS_PRIMITIVE_FIELD(Deleter, DeleteEntryPoint, DELETER_OFFSET, DATA_OFFSET)
57     ACCESSORS_NATIVE_FIELD(Data, void, DATA_OFFSET, DATA_SIZE_OFFSET);
58     ACCESSORS_PRIMITIVE_FIELD(BindingSize, uint64_t, DATA_SIZE_OFFSET, LAST_OFFSET)
59 
60     DEFINE_ALIGN_SIZE(LAST_OFFSET);
61 
DECL_VISIT_NATIVE_FIELD(POINTER_OFFSET,DATA_SIZE_OFFSET)62     DECL_VISIT_NATIVE_FIELD(POINTER_OFFSET, DATA_SIZE_OFFSET)
63 
64 private:
65     inline void DeleteExternalPointer()
66     {
67         void *externalPointer = GetExternalPointer();
68         DeleteEntryPoint deleter = GetDeleter();
69         if (deleter != nullptr) {
70             deleter(externalPointer, GetData());
71         }
72     }
73 };
74 }  // namespace panda::ecmascript
75 #endif  // ECMASCRIPT_JSNATIVEPOINTER_H
76