diff --git a/.github/workflows/native-compile-platforms.yml b/.github/workflows/native-compile-platforms.yml index 3c6d29b61d..7e053973f9 100644 --- a/.github/workflows/native-compile-platforms.yml +++ b/.github/workflows/native-compile-platforms.yml @@ -428,6 +428,9 @@ jobs: echo "set(CC_USE_GLES2 OFF)" >> build-mac/proj/cfg.cmake echo "set(CC_USE_GLES3 OFF)" >> build-mac/proj/cfg.cmake echo "set(CC_USE_METAL ON)" >> build-mac/proj/cfg.cmake + # Test JSVM v8 backend on macOS. + echo "set(USE_SE_V8 OFF)" >> build-mac/proj/cfg.cmake + echo "set(USE_SE_JSVM ON)" >> build-mac/proj/cfg.cmake echo "set(USE_WEBSOCKET_SERVER OFF)" >> build-mac/proj/cfg.cmake echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-mac/proj/cfg.cmake echo "set(CC_EXECUTABLE_NAME \"\")" >> build-mac/proj/cfg.cmake diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 3c8c7ddc19..8a3383f672 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -16,9 +16,7 @@ cc_set_if_undefined(CC_DEBUG_FORCE OFF) cc_set_if_undefined(USE_SE_V8 ON) cc_set_if_undefined(USE_SE_SM OFF) cc_set_if_undefined(USE_SE_NAPI OFF) -if(OPENHARMONY) - cc_set_if_undefined(USE_SE_JSVM OFF) -endif() +cc_set_if_undefined(USE_SE_JSVM OFF) cc_set_if_undefined(USE_V8_DEBUGGER ON) cc_set_if_undefined(USE_V8_DEBUGGER_FORCE OFF) cc_set_if_undefined(USE_SOCKET ON) @@ -218,6 +216,7 @@ cc_inspect_values( CC_USE_VULKAN CC_DEBUG_FORCE USE_SE_V8 + USE_SE_JSVM USE_V8_DEBUGGER USE_V8_DEBUGGER_FORCE USE_SE_SM @@ -2884,14 +2883,14 @@ elseif(LINUX) endif() ############# module bindings -cocos_source_files(MODULE ccbindings - cocos/bindings/sebind/intl/common.h - cocos/bindings/sebind/intl/common.cpp - cocos/bindings/sebind/class.inl - cocos/bindings/sebind/sebind.h -) - if(USE_SE_V8) + cocos_source_files(MODULE ccbindings + cocos/bindings/sebind/intl/common.h + cocos/bindings/sebind/intl/common.cpp + cocos/bindings/sebind/class.inl + cocos/bindings/sebind/sebind.h + ) + cocos_source_files(MODULE ccbindings cocos/bindings/sebind/class_v8.h cocos/bindings/sebind/class_v8.cpp @@ -2978,7 +2977,7 @@ endif() -if(OPENHARMONY AND USE_SE_JSVM) +if(USE_SE_JSVM) cocos_source_files(MODULE ccbindings cocos/bindings/jswrapper/jsvm/Class.cpp cocos/bindings/jswrapper/jsvm/Class.h @@ -2993,6 +2992,21 @@ if(OPENHARMONY AND USE_SE_JSVM) cocos/bindings/jswrapper/jsvm/Utils.h cocos/bindings/jswrapper/jsvm/CommonHeader.h ) + + if (NOT OPENHARMONY) + include_directories(${CWD}/cocos/bindings/jswrapper/jsvm-v8-backend) + cocos_source_files(MODULE ccbindings + cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.cc + cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.h + cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8_internals.h + cocos/bindings/jswrapper/jsvm-v8-backend/jsvm.h + cocos/bindings/jswrapper/jsvm-v8-backend/jsvm_types.h + cocos/bindings/jswrapper/jsvm-v8-backend/util.h + cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue-inl.h + cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue.h + ) + endif() + endif() cocos_source_files(MODULE ccbindings diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue-inl.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue-inl.h new file mode 100644 index 0000000000..9e46ae4869 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue-inl.h @@ -0,0 +1,97 @@ +#ifndef SRC_CALLBACK_QUEUE_INL_H_ +#define SRC_CALLBACK_QUEUE_INL_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include "callback_queue.h" + +namespace node { + +template +template +std::unique_ptr::Callback> +CallbackQueue::CreateCallback(Fn&& fn, CallbackFlags::Flags flags) { + return std::make_unique>(std::move(fn), flags); +} + +template +std::unique_ptr::Callback> +CallbackQueue::Shift() { + std::unique_ptr ret = std::move(head_); + if (ret) { + head_ = ret->get_next(); + if (!head_) + tail_ = nullptr; // The queue is now empty. + size_--; + } + return ret; +} + +template +void CallbackQueue::Push(std::unique_ptr cb) { + Callback* prev_tail = tail_; + + size_++; + tail_ = cb.get(); + if (prev_tail != nullptr) + prev_tail->set_next(std::move(cb)); + else + head_ = std::move(cb); +} + +template +void CallbackQueue::ConcatMove(CallbackQueue&& other) { + size_ += other.size_; + if (tail_ != nullptr) + tail_->set_next(std::move(other.head_)); + else + head_ = std::move(other.head_); + tail_ = other.tail_; + other.tail_ = nullptr; + other.size_ = 0; +} + +template +size_t CallbackQueue::size() const { + return size_.load(); +} + +template +CallbackQueue::Callback::Callback(CallbackFlags::Flags flags) + : flags_(flags) {} + +template +CallbackFlags::Flags CallbackQueue::Callback::flags() const { + return flags_; +} + +template +std::unique_ptr::Callback> +CallbackQueue::Callback::get_next() { + return std::move(next_); +} + +template +void CallbackQueue::Callback::set_next( + std::unique_ptr next) { + next_ = std::move(next); +} + +template +template +CallbackQueue::CallbackImpl::CallbackImpl( + Fn&& callback, CallbackFlags::Flags flags) + : Callback(flags), + callback_(std::move(callback)) {} + +template +template +R CallbackQueue::CallbackImpl::Call(Args... args) { + return callback_(std::forward(args)...); +} + +} // namespace node + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_CALLBACK_QUEUE_INL_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue.h new file mode 100644 index 0000000000..e5694d5e1f --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue.h @@ -0,0 +1,78 @@ +#ifndef SRC_CALLBACK_QUEUE_H_ +#define SRC_CALLBACK_QUEUE_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include + +namespace node { + +namespace CallbackFlags { +enum Flags { + kUnrefed = 0, + kRefed = 1, +}; +} + +// A queue of C++ functions that take Args... as arguments and return R +// (this is similar to the signature of std::function). +// New entries are added using `CreateCallback()`/`Push()`, and removed using +// `Shift()`. +// The `refed` flag is left for easier use in situations in which some of these +// should be run even if nothing else is keeping the event loop alive. +template +class CallbackQueue { + public: + class Callback { + public: + explicit inline Callback(CallbackFlags::Flags flags); + + virtual ~Callback() = default; + virtual R Call(Args... args) = 0; + + inline CallbackFlags::Flags flags() const; + + private: + inline std::unique_ptr get_next(); + inline void set_next(std::unique_ptr next); + + CallbackFlags::Flags flags_; + std::unique_ptr next_; + + friend class CallbackQueue; + }; + + template + inline std::unique_ptr CreateCallback( + Fn&& fn, CallbackFlags::Flags); + + inline std::unique_ptr Shift(); + inline void Push(std::unique_ptr cb); + // ConcatMove adds elements from 'other' to the end of this list, and clears + // 'other' afterwards. + inline void ConcatMove(CallbackQueue&& other); + + // size() is atomic and may be called from any thread. + inline size_t size() const; + + private: + template + class CallbackImpl final : public Callback { + public: + CallbackImpl(Fn&& callback, CallbackFlags::Flags flags); + R Call(Args... args) override; + + private: + Fn callback_; + }; + + std::atomic size_ {0}; + std::unique_ptr head_; + Callback* tail_ = nullptr; +}; + +} // namespace node + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_CALLBACK_QUEUE_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.cc b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.cc new file mode 100644 index 0000000000..78ce20f468 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.cc @@ -0,0 +1,5428 @@ +#include +#include +#include +#include // INT_MAX +#include +#include + +#include // for backtrace +#include // for demangling + +#include "v8-debug.h" +#include "v8-internal.h" +#include "v8-local-handle.h" +#include "v8-primitive.h" +#include "v8-statistics.h" +#include "v8-version-string.h" +#define JSVM_EXPERIMENTAL +// #include "env-inl.h" +#include "jsvm.h" +#include "js_native_api_v8.h" +//#include "js_native_api_v8_inspector.h" +#include "libplatform/libplatform.h" +// #include "util-inl.h" +// #include "util.h" +// #include "sourcemap.def" + +#define SECARGCNT 2 + +#define CHECK_MAYBE_NOTHING(env, maybe, status) \ + RETURN_STATUS_IF_FALSE((env), !((maybe).IsNothing()), (status)) + +#define CHECK_MAYBE_NOTHING_WITH_PREAMBLE(env, maybe, status) \ + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsNothing()), (status)) + +#define CHECK_TO_NUMBER(env, context, result, src) \ + CHECK_TO_TYPE((env), Number, (context), (result), (src), JSVM_NUMBER_EXPECTED) + +// n-api defines JSVM_AUTO_LENGTH as the indicator that a string +// is null terminated. For V8 the equivalent is -1. The assert +// validates that our cast of JSVM_AUTO_LENGTH results in -1 as +// needed by V8. +#define CHECK_NEW_FROM_UTF8_LEN(env, result, str, len) \ + do { \ + static_assert(static_cast(JSVM_AUTO_LENGTH) == -1, \ + "Casting JSVM_AUTO_LENGTH to int must result in -1"); \ + RETURN_STATUS_IF_FALSE( \ + (env), (len == JSVM_AUTO_LENGTH) || len <= INT_MAX, JSVM_INVALID_ARG); \ + RETURN_STATUS_IF_FALSE((env), (str) != nullptr, JSVM_INVALID_ARG); \ + auto str_maybe = v8::String::NewFromUtf8((env)->isolate, \ + (str), \ + v8::NewStringType::kInternalized, \ + static_cast(len)); \ + CHECK_MAYBE_EMPTY((env), str_maybe, JSVM_GENERIC_FAILURE); \ + (result) = str_maybe.ToLocalChecked(); \ + } while (0) + +#define CHECK_NEW_FROM_UTF8(env, result, str) \ + CHECK_NEW_FROM_UTF8_LEN((env), (result), (str), JSVM_AUTO_LENGTH) + +#define CHECK_NEW_STRING_ARGS(env, str, length, result) \ + do { \ + CHECK_ENV_NOT_IN_GC((env)); \ + if ((length) > 0) CHECK_ARG((env), (str)); \ + CHECK_ARG((env), (result)); \ + RETURN_STATUS_IF_FALSE( \ + (env), \ + ((length) == JSVM_AUTO_LENGTH) || (length) <= INT_MAX, \ + JSVM_INVALID_ARG); \ + } while (0) + +#define CREATE_TYPED_ARRAY( \ + env, type, size_of_element, buffer, byteOffset, length, out) \ + do { \ + if ((size_of_element) > 1) { \ + THROW_RANGE_ERROR_IF_FALSE( \ + (env), \ + (byteOffset) % (size_of_element) == 0, \ + "ERR_JSVM_INVALID_TYPEDARRAY_ALIGNMENT", \ + "start offset of " #type \ + " should be a multiple of " #size_of_element); \ + } \ + THROW_RANGE_ERROR_IF_FALSE( \ + (env), \ + (length) * (size_of_element) + (byteOffset) <= buffer->ByteLength(), \ + "ERR_JSVM_INVALID_TYPEDARRAY_LENGTH", \ + "Invalid typed array length"); \ + (out) = v8::type::New((buffer), (byteOffset), (length)); \ + } while (0) + +JSVM_Env__::JSVM_Env__(v8::Isolate* isolate, int32_t module_api_version) + : isolate(isolate), module_api_version(module_api_version) { +//cjh inspector_agent_ = new v8impl::Agent(this); + jsvm_clear_last_error(this); +} + +void JSVM_Env__::DeleteMe() { + // First we must finalize those references that have `napi_finalizer` + // callbacks. The reason is that addons might store other references which + // they delete during their `napi_finalizer` callbacks. If we deleted such + // references here first, they would be doubly deleted when the + // `napi_finalizer` deleted them subsequently. + v8impl::RefTracker::FinalizeAll(&finalizing_reflist); + v8impl::RefTracker::FinalizeAll(&reflist); + { + v8::Context::Scope context_scope(context()); +//cjh if (inspector_agent_->IsActive()) { +// inspector_agent_->WaitForDisconnect(); +// } +// delete inspector_agent_; + } + delete this; +} + +//cjh void JSVM_Env__::RunAndClearInterrupts() { +// while (native_immediates_interrupts_.size() > 0) { +// NativeImmediateQueue queue; +// { +// node::Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_); +// queue.ConcatMove(std::move(native_immediates_interrupts_)); +// } +// node::DebugSealHandleScope seal_handle_scope(isolate); +// +// while (auto head = queue.Shift()) +// head->Call(this); +// } +//} + +void JSVM_Env__::InvokeFinalizerFromGC(v8impl::RefTracker* finalizer) { + // The experimental code calls finalizers immediately to release native + // objects as soon as possible. In that state any code that may affect GC + // state causes a fatal error. To work around this issue the finalizer code + // can call node_api_post_finalizer. + auto restore_state = node::OnScopeLeave( + [this, saved = in_gc_finalizer] { in_gc_finalizer = saved; }); + in_gc_finalizer = true; + finalizer->Finalize(); +} + +namespace v8impl { + +namespace { + +//cjh added begin +class BufferFinalizer : private Finalizer { + public: + static BufferFinalizer* New(JSVM_Env env, + JSVM_Finalize finalizeCallback = nullptr, + void* finalizeData = nullptr, + void* finalizeHint = nullptr) { + return new BufferFinalizer( + env, finalizeCallback, finalizeData, finalizeHint); + } + // node::Buffer::FreeCallback + static void FinalizeBufferCallback(char* data, void* hint) { + std::unique_ptr finalizer{ + static_cast(hint)}; + finalizer->finalize_data_ = data; + + // It is safe to call into JavaScript at this point. + if (finalizer->finalize_callback_ == nullptr) return; + finalizer->env_->CallFinalizer(finalizer->finalize_callback_, + finalizer->finalize_data_, + finalizer->finalize_hint_); + } + + struct Deleter { + void operator()(BufferFinalizer* finalizer) { delete finalizer; } + }; + + private: + BufferFinalizer(JSVM_Env env, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint) + : Finalizer(env, finalizeCallback, finalizeData, finalizeHint) { + env_->Ref(); + } + + ~BufferFinalizer() { env_->Unref(); } +}; +//cjh added end + +enum IsolateDataSlot { + kIsolateData = 0, + kIsolateSnapshotCreatorSlot = 1, +}; + +enum ContextEmbedderIndex { + kContextEnvIndex = 1, +}; + +struct IsolateData { + IsolateData(v8::StartupData* blob) : blob(blob) {} + + ~IsolateData() { + delete blob; + } + + v8::StartupData* blob; + v8::Eternal jsvm_type_tag_key; + v8::Eternal jsvm_wrapper_key; +}; + +static void CreateIsolateData(v8::Isolate* isolate, v8::StartupData* blob) { + auto data = new IsolateData(blob); + v8::Isolate::Scope isolate_scope(isolate); + v8::HandleScope handle_scope(isolate); + if (blob) { + // NOTE: The order of getting the data must be consistent with the order of + // adding data in OH_JSVM_CreateSnapshot. + auto wrapper_key = isolate->GetDataFromSnapshotOnce(0); + auto type_tag_key = isolate->GetDataFromSnapshotOnce(1); + data->jsvm_wrapper_key.Set(isolate, wrapper_key.ToLocalChecked()); + data->jsvm_type_tag_key.Set(isolate, type_tag_key.ToLocalChecked()); + } else { + data->jsvm_wrapper_key.Set(isolate, v8::Private::New(isolate)); + data->jsvm_type_tag_key.Set(isolate, v8::Private::New(isolate)); + } + isolate->SetData(v8impl::kIsolateData, data); +} + +static IsolateData* GetIsolateData(v8::Isolate* isolate) { + auto data = isolate->GetData(v8impl::kIsolateData); + return reinterpret_cast(data); +} + +static void SetIsolateSnapshotCreator(v8::Isolate* isolate, + v8::SnapshotCreator* creator) { + isolate->SetData(v8impl::kIsolateSnapshotCreatorSlot, creator); +} + +static v8::SnapshotCreator* GetIsolateSnapshotCreator(v8::Isolate* isolate) { + auto data = isolate->GetData(v8impl::kIsolateSnapshotCreatorSlot); + return reinterpret_cast(data); +} + +static void SetContextEnv(v8::Local context, JSVM_Env env) { + context->SetAlignedPointerInEmbedderData(kContextEnvIndex, env); +} + +static JSVM_Env GetContextEnv(v8::Local context) { + auto data = context->GetAlignedPointerFromEmbedderData(kContextEnvIndex); + return reinterpret_cast(data); +} + +//class OutputStream : public v8::OutputStream { +// public: +// OutputStream(JSVM_OutputStream stream, void* data, int chunk_size = 65536) +// : stream_(stream), stream_data_(data), chunk_size_(chunk_size) {} +// +// int GetChunkSize() override { return chunk_size_; } +// +// void EndOfStream() override { +// stream_(nullptr, 0, stream_data_); +// } +// +// WriteResult WriteAsciiChunk(char* data, const int size) override { +// return stream_(data, size, stream_data_) ? kContinue : kAbort; +// } +// +// private: +// JSVM_OutputStream stream_; +// void* stream_data_; +// int chunk_size_; +//}; + +static std::unique_ptr g_platform = v8::platform::NewDefaultPlatform(); + +static std::vector externalReferenceRegistry; + +static std::unordered_map sourceMapUrlMap; + +static std::unique_ptr defaultArrayBufferAllocator; + +static v8::ArrayBuffer::Allocator *GetOrCreateDefaultArrayBufferAllocator() { + if (!defaultArrayBufferAllocator) { + defaultArrayBufferAllocator.reset(v8::ArrayBuffer::Allocator::NewDefaultAllocator()); + } + return defaultArrayBufferAllocator.get(); +} + +static void SetFileToSourceMapMapping(std::string &&file, std::string &&sourceMapUrl) { + auto it = sourceMapUrlMap.find(file); + if (it == sourceMapUrlMap.end()) { + sourceMapUrlMap.emplace(file, sourceMapUrl); + return; + } + auto &&prevSourceMapUrl = it->second; + CHECK(prevSourceMapUrl == sourceMapUrl); +} + +static std::string GetSourceMapFromFileName(std::string &&file) { + auto it = sourceMapUrlMap.find(file); + if (it != sourceMapUrlMap.end()) { + return it->second; + } + return ""; +} + +template +JSVM_Status NewString(JSVM_Env env, + const CCharType* str, + size_t length, + JSVM_Value* result, + StringMaker string_maker) { + CHECK_NEW_STRING_ARGS(env, str, length, result); + + auto isolate = env->isolate; + auto str_maybe = string_maker(isolate); + CHECK_MAYBE_EMPTY(env, str_maybe, JSVM_GENERIC_FAILURE); + *result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked()); + return jsvm_clear_last_error(env); +} + +template +JSVM_Status NewExternalString(JSVM_Env env, + CharType* str, + size_t length, + JSVM_Finalize finalizeCallback, + void* finalizeHint, + JSVM_Value* result, + bool* copied, + CreateAPI create_api, + StringMaker string_maker) { + CHECK_NEW_STRING_ARGS(env, str, length, result); + JSVM_Status status; +#if defined(V8_ENABLE_SANDBOX) + status = create_api(env, str, length, result); + if (status == JSVM_OK) { + if (copied != nullptr) { + *copied = true; + } + if (finalizeCallback) { + env->CallFinalizer( + finalizeCallback, static_cast(str), finalizeHint); + } + } +#else + status = NewString(env, str, length, result, string_maker); + if (status == JSVM_OK && copied != nullptr) { + *copied = false; + } +#endif // V8_ENABLE_SANDBOX + return status; +} + +class TrackedStringResource : public Finalizer, RefTracker { + public: + TrackedStringResource(JSVM_Env env, + JSVM_Finalize finalizeCallback, + void* data, + void* finalizeHint) + : Finalizer(env, finalizeCallback, data, finalizeHint) { + Link(finalizeCallback == nullptr ? &env->reflist + : &env->finalizing_reflist); + } + + protected: + // The only time Finalize() gets called before Dispose() is if the + // environment is dying. Finalize() expects that the item will be unlinked, + // so we do it here. V8 will still call Dispose() on us later, so we don't do + // any deleting here. We just null out env_ to avoid passing a stale pointer + // to the user's finalizer when V8 does finally call Dispose(). + void Finalize() override { + Unlink(); + env_ = nullptr; + } + + ~TrackedStringResource() { + if (finalize_callback_ == nullptr) return; + if (env_ == nullptr) { + // The environment is dead. Call the finalizer directly. + finalize_callback_(nullptr, finalize_data_, finalize_hint_); + } else { + // The environment is still alive. Let's remove ourselves from its list + // of references and call the user's finalizer. + Unlink(); + env_->CallFinalizer(finalize_callback_, finalize_data_, finalize_hint_); + } + } +}; + +class ExternalOneByteStringResource + : public v8::String::ExternalOneByteStringResource, + TrackedStringResource { + public: + ExternalOneByteStringResource(JSVM_Env env, + char* string, + const size_t length, + JSVM_Finalize finalizeCallback, + void* finalizeHint) + : TrackedStringResource(env, finalizeCallback, string, finalizeHint), + string_(string), + length_(length) {} + + const char* data() const override { return string_; } + size_t length() const override { return length_; } + + private: + const char* string_; + const size_t length_; +}; + +class ExternalStringResource : public v8::String::ExternalStringResource, + TrackedStringResource { + public: + ExternalStringResource(JSVM_Env env, + char16_t* string, + const size_t length, + JSVM_Finalize finalizeCallback, + void* finalizeHint) + : TrackedStringResource(env, finalizeCallback, string, finalizeHint), + string_(reinterpret_cast(string)), + length_(length) {} + + const uint16_t* data() const override { return string_; } + size_t length() const override { return length_; } + + private: + const uint16_t* string_; + const size_t length_; +}; + +inline JSVM_Status V8NameFromPropertyDescriptor( + JSVM_Env env, + const JSVM_PropertyDescriptor* p, + v8::Local* result) { + if (p->utf8name != nullptr) { + CHECK_NEW_FROM_UTF8(env, *result, p->utf8name); + } else { + v8::Local property_value = + v8impl::V8LocalValueFromJsValue(p->name); + + RETURN_STATUS_IF_FALSE(env, property_value->IsName(), JSVM_NAME_EXPECTED); + *result = property_value.As(); + } + + return JSVM_OK; +} + +// convert from n-api property attributes to v8::PropertyAttribute +inline v8::PropertyAttribute V8PropertyAttributesFromDescriptor( + const JSVM_PropertyDescriptor* descriptor) { + unsigned int attribute_flags = v8::PropertyAttribute::None; + + // The JSVM_WRITABLE attribute is ignored for accessor descriptors, but + // V8 would throw `TypeError`s on assignment with nonexistence of a setter. + if ((descriptor->getter == nullptr && descriptor->setter == nullptr) && + (descriptor->attributes & JSVM_WRITABLE) == 0) { + attribute_flags |= v8::PropertyAttribute::ReadOnly; + } + + if ((descriptor->attributes & JSVM_ENUMERABLE) == 0) { + attribute_flags |= v8::PropertyAttribute::DontEnum; + } + if ((descriptor->attributes & JSVM_CONFIGURABLE) == 0) { + attribute_flags |= v8::PropertyAttribute::DontDelete; + } + + return static_cast(attribute_flags); +} + +inline JSVM_Deferred JsDeferredFromNodePersistent( + v8impl::Persistent* local) { + return reinterpret_cast(local); +} + +inline v8impl::Persistent* NodePersistentFromJsDeferred( + JSVM_Deferred local) { + return reinterpret_cast*>(local); +} + +class HandleScopeWrapper { + public: + explicit HandleScopeWrapper(v8::Isolate* isolate) : scope(isolate) {} + + private: + v8::HandleScope scope; +}; + +// In node v0.10 version of v8, there is no EscapableHandleScope and the +// node v0.10 port use HandleScope::Close(Local v) to mimic the behavior +// of a EscapableHandleScope::Escape(Local v), but it is not the same +// semantics. This is an example of where the api abstraction fail to work +// across different versions. +class EscapableHandleScopeWrapper { + public: + explicit EscapableHandleScopeWrapper(v8::Isolate* isolate) + : scope(isolate), escape_called_(false) {} + bool escape_called() const { return escape_called_; } + template + v8::Local Escape(v8::Local handle) { + escape_called_ = true; + return scope.Escape(handle); + } + + private: + v8::EscapableHandleScope scope; + bool escape_called_; +}; + +inline JSVM_HandleScope JsHandleScopeFromV8HandleScope(HandleScopeWrapper* s) { + return reinterpret_cast(s); +} + +inline HandleScopeWrapper* V8HandleScopeFromJsHandleScope(JSVM_HandleScope s) { + return reinterpret_cast(s); +} + +inline JSVM_EscapableHandleScope +JsEscapableHandleScopeFromV8EscapableHandleScope( + EscapableHandleScopeWrapper* s) { + return reinterpret_cast(s); +} + +inline EscapableHandleScopeWrapper* +V8EscapableHandleScopeFromJsEscapableHandleScope( + JSVM_EscapableHandleScope s) { + return reinterpret_cast(s); +} + +inline JSVM_Status ConcludeDeferred(JSVM_Env env, + JSVM_Deferred deferred, + JSVM_Value result, + bool is_resolved) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8impl::Persistent* deferred_ref = + NodePersistentFromJsDeferred(deferred); + v8::Local v8_deferred = + v8::Local::New(env->isolate, *deferred_ref); + + auto v8_resolver = v8_deferred.As(); + + v8::Maybe success = + is_resolved ? v8_resolver->Resolve( + context, v8impl::V8LocalValueFromJsValue(result)) + : v8_resolver->Reject( + context, v8impl::V8LocalValueFromJsValue(result)); + + delete deferred_ref; + + RETURN_STATUS_IF_FALSE(env, success.FromMaybe(false), JSVM_GENERIC_FAILURE); + + return GET_RETURN_STATUS(env); +} + +enum UnwrapAction { KeepWrap, RemoveWrap }; + +inline JSVM_Status Unwrap(JSVM_Env env, + JSVM_Value jsObject, + void** result, + UnwrapAction action) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, jsObject); + if (action == KeepWrap) { + CHECK_ARG(env, result); + } + + v8::Local context = env->context(); + + v8::Local value = v8impl::V8LocalValueFromJsValue(jsObject); + RETURN_STATUS_IF_FALSE(env, value->IsObject(), JSVM_INVALID_ARG); + v8::Local obj = value.As(); + + auto val = obj->GetPrivate(context, JSVM_PRIVATE_KEY(env->isolate, wrapper)) + .ToLocalChecked(); + RETURN_STATUS_IF_FALSE(env, val->IsExternal(), JSVM_INVALID_ARG); + Reference* reference = + static_cast(val.As()->Value()); + + if (result) { + *result = reference->Data(); + } + + if (action == RemoveWrap) { + CHECK(obj->DeletePrivate(context, JSVM_PRIVATE_KEY(env->isolate, wrapper)) + .FromJust()); + if (reference->ownership() == Ownership::kUserland) { + // When the wrap is been removed, the finalizer should be reset. + reference->ResetFinalizer(); + } else { + delete reference; + } + } + + return GET_RETURN_STATUS(env); +} + +//=== Function JSVM_Callback wrapper ================================= + +// Use this data structure to associate callback data with each N-API function +// exposed to JavaScript. The structure is stored in a v8::External which gets +// passed into our callback wrapper. This reduces the performance impact of +// calling through N-API. +// Ref: benchmark/misc/function_call +// Discussion (incl. perf. data): https://github.com/nodejs/node/pull/21072 +class CallbackBundle { + public: + // Creates an object to be made available to the static function callback + // wrapper, used to retrieve the native callback function and data pointer. + static inline v8::Local New(JSVM_Env env, + JSVM_Callback cb) { + return v8::External::New(env->isolate, cb); + } + + static inline v8::Local New(JSVM_Env env, + v8impl::JSVM_PropertyHandlerCfgStruct* cb) { + return v8::External::New(env->isolate, cb); + } +}; + +// Base class extended by classes that wrap V8 function and property callback +// info. +class CallbackWrapper { + public: + inline CallbackWrapper(JSVM_Value thisArg, size_t args_length, void* data) + : _this(thisArg), _args_length(args_length), _data(data) {} + + virtual JSVM_Value GetNewTarget() {}; + virtual void Args(JSVM_Value* buffer, size_t bufferlength) {}; + virtual void SetReturnValue(JSVM_Value value) = 0; + + JSVM_Value This() { return _this; } + + size_t ArgsLength() { return _args_length; } + + void* Data() { return _data; } + + protected: + const JSVM_Value _this; + const size_t _args_length; + void* _data; +}; + +class CallbackWrapperBase : public CallbackWrapper { + public: + inline CallbackWrapperBase(const v8::FunctionCallbackInfo& cbinfo, + const size_t args_length) + : CallbackWrapper( + JsValueFromV8LocalValue(cbinfo.This()), args_length, nullptr), + _cbinfo(cbinfo) { + _cb = (JSVM_Callback)cbinfo.Data().As()->Value(); + _data = _cb->data; + } + + protected: + inline void InvokeCallback() { + JSVM_CallbackInfo cbinfo_wrapper = reinterpret_cast( + static_cast(this)); + + // All other pointers we need are stored in `_bundle` + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto cb = _cb->callback; + + JSVM_Value result = nullptr; + bool exceptionOccurred = false; + env->CallIntoModule([&](JSVM_Env env) { result = cb(env, cbinfo_wrapper); }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + + if (!exceptionOccurred && (result != nullptr)) { + this->SetReturnValue(result); + } + } + + const v8::FunctionCallbackInfo& _cbinfo; + JSVM_Callback _cb; +}; + +class FunctionCallbackWrapper : public CallbackWrapperBase { + public: + static void Invoke(const v8::FunctionCallbackInfo& info) { + FunctionCallbackWrapper cbwrapper(info); + cbwrapper.InvokeCallback(); + } + + static inline JSVM_Status NewFunction(JSVM_Env env, + JSVM_Callback cb, + v8::Local* result) { + v8::Local cbdata = v8impl::CallbackBundle::New(env, cb); + RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), JSVM_GENERIC_FAILURE); + + v8::MaybeLocal maybe_function = + v8::Function::New(env->context(), Invoke, cbdata); + CHECK_MAYBE_EMPTY(env, maybe_function, JSVM_GENERIC_FAILURE); + + *result = maybe_function.ToLocalChecked(); + return jsvm_clear_last_error(env); + } + + static inline JSVM_Status NewTemplate( + JSVM_Env env, + JSVM_Callback cb, + v8::Local* result, + v8::Local sig = v8::Local()) { + v8::Local cbdata = v8impl::CallbackBundle::New(env, cb); + RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), JSVM_GENERIC_FAILURE); + + *result = v8::FunctionTemplate::New(env->isolate, Invoke, cbdata, sig); + return jsvm_clear_last_error(env); + } + + explicit FunctionCallbackWrapper( + const v8::FunctionCallbackInfo& cbinfo) + : CallbackWrapperBase(cbinfo, cbinfo.Length()) {} + + JSVM_Value GetNewTarget() override { + if (_cbinfo.IsConstructCall()) { + return v8impl::JsValueFromV8LocalValue(_cbinfo.NewTarget()); + } else { + return nullptr; + } + } + + /*virtual*/ + void Args(JSVM_Value* buffer, size_t buffer_length) override { + size_t i = 0; + size_t min = std::min(buffer_length, _args_length); + + for (; i < min; i += 1) { + buffer[i] = v8impl::JsValueFromV8LocalValue(_cbinfo[i]); + } + + if (i < buffer_length) { + JSVM_Value undefined = + v8impl::JsValueFromV8LocalValue(v8::Undefined(_cbinfo.GetIsolate())); + for (; i < buffer_length; i += 1) { + buffer[i] = undefined; + } + } + } + + /*virtual*/ + void SetReturnValue(JSVM_Value value) override { + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + _cbinfo.GetReturnValue().Set(val); + } +}; + +template +class PropertyCallbackWrapperBase : public CallbackWrapper { + public: + inline PropertyCallbackWrapperBase(uint32_t index, v8::Local property, v8::Local value, + const v8::PropertyCallbackInfo& cbinfo, const size_t args_length) + : CallbackWrapper( + JsValueFromV8LocalValue(cbinfo.This()), args_length, nullptr), + _cbinfo(cbinfo), _property(property), _value(value), _index(index) { + _cb = (v8impl::JSVM_PropertyHandlerCfgStruct *)_cbinfo.Data().template As()->Value(); + } + + protected: + inline void NameSetterInvokeCallback() { + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto setterCb = _cb->namedSetterCallback_; + + JSVM_Value innerData = nullptr; + if (_cb->namedPropertyData_ != nullptr) { + v8impl::Reference* reference = reinterpret_cast(_cb->namedPropertyData_); + innerData = v8impl::JsValueFromV8LocalValue(reference->Get()); + } + + bool exceptionOccurred = false; + JSVM_Value result = nullptr; + JSVM_Value name = JsValueFromV8LocalValue(_property); + JSVM_Value value = JsValueFromV8LocalValue(_value); + JSVM_Value thisArg = this->This(); + env->CallIntoModule([&](JSVM_Env env) { + if (setterCb) { + result = setterCb(env, name, value, thisArg, innerData); + } + }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + if (!exceptionOccurred && (result != nullptr)) { + this->SetReturnValue(result); + } + } + + inline void NameGetterInvokeCallback() { + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto getterCb = _cb->namedGetterCallback_; + + JSVM_Value innerData = nullptr; + if (_cb->namedPropertyData_ != nullptr) { + v8impl::Reference* reference = reinterpret_cast(_cb->namedPropertyData_); + innerData = v8impl::JsValueFromV8LocalValue(reference->Get()); + } + bool exceptionOccurred = false; + JSVM_Value result = nullptr; + JSVM_Value name = JsValueFromV8LocalValue(_property); + JSVM_Value thisArg = this->This(); + env->CallIntoModule([&](JSVM_Env env) { + if (getterCb) { + result = getterCb(env, name, thisArg, innerData); + } + }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + if (!exceptionOccurred && (result != nullptr)) { + this->SetReturnValue(result); + } + } + + inline void NameDeleterInvokeCallback() { + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto deleterCb = _cb->nameDeleterCallback_; + + JSVM_Value innerData = nullptr; + if (_cb->namedPropertyData_ != nullptr) { + v8impl::Reference* reference = reinterpret_cast(_cb->namedPropertyData_); + innerData = v8impl::JsValueFromV8LocalValue(reference->Get()); + } + + bool exceptionOccurred = false; + JSVM_Value result = nullptr; + JSVM_Value name = JsValueFromV8LocalValue(_property); + JSVM_Value thisArg = this->This(); + env->CallIntoModule([&](JSVM_Env env) { + if (deleterCb) { + result = deleterCb(env, name, thisArg, innerData); + } + }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + if (!exceptionOccurred && (result != nullptr)) { + if (v8impl::V8LocalValueFromJsValue(result)->IsBoolean()) { + this->SetReturnValue(result); + } + } + } + + inline void NameEnumeratorInvokeCallback() { + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto enumeratorCb = _cb->namedEnumeratorCallback_; + + JSVM_Value innerData = nullptr; + if (_cb->namedPropertyData_ != nullptr) { + v8impl::Reference* reference = reinterpret_cast(_cb->namedPropertyData_); + innerData = v8impl::JsValueFromV8LocalValue(reference->Get()); + } + + bool exceptionOccurred = false; + JSVM_Value result = nullptr; + JSVM_Value thisArg = this->This(); + env->CallIntoModule([&](JSVM_Env env) { + if (enumeratorCb) { + result = enumeratorCb(env, thisArg, innerData); + } + }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + if (!exceptionOccurred && (result != nullptr)) { + if (v8impl::V8LocalValueFromJsValue(result)->IsArray()) { + this->SetReturnValue(result); + } + } + } + + inline void IndexSetterInvokeCallback() { + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto indexSetterCb = _cb->indexedSetterCallback_; + + JSVM_Value innerData = nullptr; + if (_cb->indexedPropertyData_ != nullptr) { + v8impl::Reference* reference = reinterpret_cast(_cb->indexedPropertyData_); + innerData = v8impl::JsValueFromV8LocalValue(reference->Get()); + } + + bool exceptionOccurred = false; + JSVM_Value result = nullptr; + JSVM_Value index = JsValueFromV8LocalValue(v8::Integer::NewFromUnsigned(env->isolate, _index)); + JSVM_Value value = JsValueFromV8LocalValue(_value); + JSVM_Value thisArg = this->This(); + env->CallIntoModule([&](JSVM_Env env) { + if (indexSetterCb) { + result = indexSetterCb(env, index, value, thisArg, innerData); + } + }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + if (!exceptionOccurred && (result != nullptr)) { + this->SetReturnValue(result); + } + } + + inline void IndexGetterInvokeCallback() { + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto indexGetterCb = _cb->indexedGetterCallback_; + + JSVM_Value innerData = nullptr; + if (_cb->indexedPropertyData_ != nullptr) { + v8impl::Reference* reference = reinterpret_cast(_cb->indexedPropertyData_); + innerData = v8impl::JsValueFromV8LocalValue(reference->Get()); + } + + JSVM_Value result = nullptr; + bool exceptionOccurred = false; + JSVM_Value index = JsValueFromV8LocalValue(v8::Integer::NewFromUnsigned(env->isolate, _index)); + JSVM_Value thisArg = this->This(); + env->CallIntoModule([&](JSVM_Env env) { + if (indexGetterCb) { + result = indexGetterCb(env, index, thisArg, innerData); + } + }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + if (!exceptionOccurred && (result != nullptr)) { + this->SetReturnValue(result); + } + } + + inline void IndexDeleterInvokeCallback() { + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto indexDeleterCb = _cb->indexedDeleterCallback_; + + JSVM_Value innerData = nullptr; + if (_cb->indexedPropertyData_ != nullptr) { + v8impl::Reference* reference = reinterpret_cast(_cb->indexedPropertyData_); + innerData = v8impl::JsValueFromV8LocalValue(reference->Get()); + } + + bool exceptionOccurred = false; + JSVM_Value result = nullptr; + JSVM_Value index = JsValueFromV8LocalValue(v8::Integer::NewFromUnsigned(env->isolate, _index)); + JSVM_Value thisArg = this->This(); + env->CallIntoModule([&](JSVM_Env env) { + if (indexDeleterCb) { + result = indexDeleterCb(env, index, thisArg, innerData); + } + }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + if (!exceptionOccurred && (result != nullptr)) { + if (v8impl::V8LocalValueFromJsValue(result)->IsBoolean()) { + this->SetReturnValue(result); + } + } + } + + inline void IndexEnumeratorInvokeCallback() { + auto context = _cbinfo.GetIsolate()->GetCurrentContext(); + auto env = v8impl::GetContextEnv(context); + auto enumeratorCb = _cb->indexedEnumeratorCallback_; + + JSVM_Value innerData = nullptr; + if (_cb->indexedPropertyData_ != nullptr) { + v8impl::Reference* reference = reinterpret_cast(_cb->indexedPropertyData_); + innerData = v8impl::JsValueFromV8LocalValue(reference->Get()); + } + + bool exceptionOccurred = false; + JSVM_Value result = nullptr; + JSVM_Value thisArg = this->This(); + env->CallIntoModule([&](JSVM_Env env) { + if (enumeratorCb) { + result = enumeratorCb(env, thisArg, innerData); + } + }, + [&](JSVM_Env env, v8::Local value) { + exceptionOccurred = true; + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + }); + if (!exceptionOccurred && (result != nullptr)) { + if (v8impl::V8LocalValueFromJsValue(result)->IsArray()) { + this->SetReturnValue(result); + } + } + } + + const v8::PropertyCallbackInfo& _cbinfo; + JSVM_PropertyHandlerCfgStruct* _cb; + v8::Local _property; + v8::Local _value; + uint32_t _index; +}; + +template +class PropertyCallbackWrapper : public PropertyCallbackWrapperBase { + public: + static void NameSetterInvoke(v8::Local property, v8::Local value, + const v8::PropertyCallbackInfo& info) { + PropertyCallbackWrapper propertyCbWrapper(property, value, info); + propertyCbWrapper.NameSetterInvokeCallback(); + } + + static void NameGetterInvoke(v8::Local property, const v8::PropertyCallbackInfo& info) { + PropertyCallbackWrapper propertyCbWrapper(property, v8::Local(), info); + propertyCbWrapper.NameGetterInvokeCallback(); + } + + static void NameDeleterInvoke(v8::Local property, const v8::PropertyCallbackInfo& info) { + PropertyCallbackWrapper propertyCbWrapper(property, v8::Local(), info); + propertyCbWrapper.NameDeleterInvokeCallback(); + } + + static void NameEnumeratorInvoke(const v8::PropertyCallbackInfo& info) { + PropertyCallbackWrapper propertyCbWrapper(v8::Local(), v8::Local(), info); + propertyCbWrapper.NameEnumeratorInvokeCallback(); + } + + static void IndexSetterInvoke(uint32_t index, v8::Local value, + const v8::PropertyCallbackInfo& info) { + PropertyCallbackWrapper propertyCbWrapper(index, value, info); + propertyCbWrapper.IndexSetterInvokeCallback(); + } + + static void IndexGetterInvoke(uint32_t index, const v8::PropertyCallbackInfo& info) { + PropertyCallbackWrapper propertyCbWrapper(index, v8::Local(), info); + propertyCbWrapper.IndexGetterInvokeCallback(); + } + + static void IndexDeleterInvoke(uint32_t index, const v8::PropertyCallbackInfo& info) { + PropertyCallbackWrapper propertyCbWrapper(index, v8::Local(), info); + propertyCbWrapper.IndexDeleterInvokeCallback(); + } + + static void IndexEnumeratorInvoke(const v8::PropertyCallbackInfo& info) { + PropertyCallbackWrapper propertyCbWrapper(0, v8::Local(), info); + propertyCbWrapper.IndexEnumeratorInvokeCallback(); + } + + explicit PropertyCallbackWrapper(v8::Local name, v8::Local value, + const v8::PropertyCallbackInfo& cbinfo) + : PropertyCallbackWrapperBase(0, name, value, cbinfo, 0), _cbInfo(cbinfo) {} + + explicit PropertyCallbackWrapper(uint32_t index, v8::Local value, + const v8::PropertyCallbackInfo& cbinfo) + : PropertyCallbackWrapperBase(index, v8::Local(), value, cbinfo, 0), _cbInfo(cbinfo) {} + + /*virtual*/ + void SetReturnValue(JSVM_Value value) override { + v8::Local val = v8impl::V8LocalValueFromJsValue(value).As(); + _cbInfo.GetReturnValue().Set(val); + } + +protected: + const v8::PropertyCallbackInfo& _cbInfo; +}; + +inline JSVM_Status Wrap(JSVM_Env env, + JSVM_Value jsObject, + void* nativeObject, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Ref* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, jsObject); + + v8::Local context = env->context(); + + v8::Local value = v8impl::V8LocalValueFromJsValue(jsObject); + RETURN_STATUS_IF_FALSE(env, value->IsObject(), JSVM_INVALID_ARG); + v8::Local obj = value.As(); + + // If we've already wrapped this object, we error out. + RETURN_STATUS_IF_FALSE( + env, + !obj->HasPrivate(context, JSVM_PRIVATE_KEY(env->isolate, wrapper)).FromJust(), + JSVM_INVALID_ARG); + + v8impl::Reference* reference = nullptr; + if (result != nullptr) { + // The returned reference should be deleted via OH_JSVM_DeleteReference() + // ONLY in response to the finalize callback invocation. (If it is deleted + // before then, then the finalize callback will never be invoked.) + // Therefore a finalize callback is required when returning a reference. + CHECK_ARG(env, finalizeCb); + reference = v8impl::Reference::New(env, + obj, + 0, + v8impl::Ownership::kUserland, + finalizeCb, + nativeObject, + finalizeHint); + *result = reinterpret_cast(reference); + } else { + // Create a self-deleting reference. + reference = v8impl::Reference::New( + env, + obj, + 0, + v8impl::Ownership::kRuntime, + finalizeCb, + nativeObject, + finalizeCb == nullptr ? nullptr : finalizeHint); + } + + CHECK(obj->SetPrivate(context, + JSVM_PRIVATE_KEY(env->isolate, wrapper), + v8::External::New(env->isolate, reference)) + .FromJust()); + + return GET_RETURN_STATUS(env); +} + +// In JavaScript, weak references can be created for object types (Object, +// Function, and external Object) and for local symbols that are created with +// the `Symbol` function call. Global symbols created with the `Symbol.for` +// method cannot be weak references because they are never collected. +// +// Currently, V8 has no API to detect if a symbol is local or global. +// Until we have a V8 API for it, we consider that all symbols can be weak. +// This matches the current Node-API behavior. +inline bool CanBeHeldWeakly(v8::Local value) { + return value->IsObject() || value->IsSymbol(); +} + +} // end of anonymous namespace + +void Finalizer::ResetFinalizer() { + finalize_callback_ = nullptr; + finalize_data_ = nullptr; + finalize_hint_ = nullptr; +} + +TrackedFinalizer::TrackedFinalizer(JSVM_Env env, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint) + : Finalizer(env, finalizeCallback, finalizeData, finalizeHint), + RefTracker() { + Link(finalizeCallback == nullptr ? &env->reflist : &env->finalizing_reflist); +} + +TrackedFinalizer* TrackedFinalizer::New(JSVM_Env env, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint) { + return new TrackedFinalizer( + env, finalizeCallback, finalizeData, finalizeHint); +} + +// When a TrackedFinalizer is being deleted, it may have been queued to call its +// finalizer. +TrackedFinalizer::~TrackedFinalizer() { + // Remove from the env's tracked list. + Unlink(); + // Try to remove the finalizer from the scheduled second pass callback. + env_->DequeueFinalizer(this); +} + +void TrackedFinalizer::Finalize() { + FinalizeCore(/*deleteMe:*/ true); +} + +void TrackedFinalizer::FinalizeCore(bool deleteMe) { + // Swap out the field finalize_callback so that it can not be accidentally + // called more than once. + JSVM_Finalize finalizeCallback = finalize_callback_; + void* finalizeData = finalize_data_; + void* finalizeHint = finalize_hint_; + ResetFinalizer(); + + // Either the RefBase is going to be deleted in the finalize_callback or not, + // it should be removed from the tracked list. + Unlink(); + // If the finalize_callback is present, it should either delete the + // derived RefBase, or the RefBase ownership was set to Ownership::kRuntime + // and the deleteMe parameter is true. + if (finalizeCallback != nullptr) { + env_->CallFinalizer(finalizeCallback, finalizeData, finalizeHint); + } + + if (deleteMe) { + delete this; + } +} + +// Wrapper around v8impl::Persistent that implements reference counting. +RefBase::RefBase(JSVM_Env env, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint) + : TrackedFinalizer(env, finalizeCallback, finalizeData, finalizeHint), + refcount_(initialRefcount), + ownership_(ownership) {} + +RefBase* RefBase::New(JSVM_Env env, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint) { + return new RefBase(env, + initialRefcount, + ownership, + finalizeCallback, + finalizeData, + finalizeHint); +} + +void* RefBase::Data() { + return finalize_data_; +} + +uint32_t RefBase::Ref() { + return ++refcount_; +} + +uint32_t RefBase::Unref() { + if (refcount_ == 0) { + return 0; + } + return --refcount_; +} + +uint32_t RefBase::RefCount() { + return refcount_; +} + +void RefBase::Finalize() { + // If the RefBase is not Ownership::kRuntime, userland code should delete it. + // Delete it if it is Ownership::kRuntime. + FinalizeCore(/*deleteMe:*/ ownership_ == Ownership::kRuntime); +} + +template +Reference::Reference(JSVM_Env env, v8::Local value, Args&&... args) + : RefBase(env, std::forward(args)...), + persistent_(env->isolate, value), + can_be_weak_(CanBeHeldWeakly(value)), + deleted_by_user(false), + wait_callback(false) { + if (RefCount() == 0) { + SetWeak(); + } +} + +Reference::~Reference() { + // Reset the handle. And no weak callback will be invoked. + persistent_.Reset(); +} + +Reference* Reference::New(JSVM_Env env, + v8::Local value, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint) { + return new Reference(env, + value, + initialRefcount, + ownership, + finalizeCallback, + finalizeData, + finalizeHint); +} + +uint32_t Reference::Ref() { + // When the persistent_ is cleared in the WeakCallback, and a second pass + // callback is pending, return 0 unconditionally. + if (persistent_.IsEmpty()) { + return 0; + } + uint32_t refcount = RefBase::Ref(); + if (refcount == 1 && can_be_weak_) { + persistent_.ClearWeak(); + wait_callback = false; + } + return refcount; +} + +uint32_t Reference::Unref() { + // When the persistent_ is cleared in the WeakCallback, and a second pass + // callback is pending, return 0 unconditionally. + if (persistent_.IsEmpty()) { + return 0; + } + uint32_t old_refcount = RefCount(); + uint32_t refcount = RefBase::Unref(); + if (old_refcount == 1 && refcount == 0) { + SetWeak(); + } + return refcount; +} + +v8::Local Reference::Get() { + if (persistent_.IsEmpty()) { + return v8::Local(); + } else { + return v8::Local::New(env_->isolate, persistent_); + } +} + +void Reference::Delete() { + assert(ownership() == Ownership::kUserland); + if (!wait_callback) { + delete this; + } else { + deleted_by_user = true; + } +} + +void Reference::Finalize() { + // Unconditionally reset the persistent handle so that no weak callback will + // be invoked again. + persistent_.Reset(); + + // Chain up to perform the rest of the finalization. + RefBase::Finalize(); +} + +// Mark the reference as weak and eligible for collection +// by the gc. +void Reference::SetWeak() { + if (can_be_weak_) { + wait_callback = true; + persistent_.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter); + } else { + persistent_.Reset(); + } +} + +// The N-API finalizer callback may make calls into the engine. V8's heap is +// not in a consistent state during the weak callback, and therefore it does +// not support calls back into it. Enqueue the invocation of the finalizer. +void Reference::WeakCallback(const v8::WeakCallbackInfo& data) { + Reference* reference = data.GetParameter(); + // The reference must be reset during the weak callback as the API protocol. + assert(!reference->deleted); + reference->persistent_.Reset(); + assert(reference->wait_callback); + if (!reference->createStack.empty()) { + int a = 0; + } + // For owership == kRuntime, deleted_by_user is always false. + // Due to reference may be free in InvokeFinalizerFromGC, the status of + // reference should be set before finalize call. + bool need_delete = reference->deleted_by_user; + reference->wait_callback = false; + reference->env_->InvokeFinalizerFromGC(reference); + + if (need_delete) { + delete reference; + } else { + int a = 0; + } +} + +} // end of namespace v8impl + +v8::Platform* JSVM_Env__::platform() { + return v8impl::g_platform.get(); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_Init(const JSVM_InitOptions* options) { + static std::atomic initialized(false); + if (initialized.load()) { + return JSVM_GENERIC_FAILURE; + } + initialized.store(true); +#ifdef TARGET_OHOS + v8impl::ResourceSchedule::ReportKeyThread(getuid(), getprocpid(), getproctid(), + v8impl::ResourceSchedule::ResType::ThreadRole::IMPORTANT_DISPLAY); +#endif + v8::V8::InitializePlatform(v8impl::g_platform.get()); + +//cjh if (node::ReadSystemXpmState()) { +// int secArgc = SECARGCNT; +// char *secArgv[SECARGCNT] = {"jsvm", "--jitless"}; +// v8::V8::SetFlagsFromCommandLine(&secArgc, secArgv, false); +// } + + if (options && options->argc && options->argv) { + v8::V8::SetFlagsFromCommandLine(options->argc, options->argv, options->removeFlags); + } + v8::V8::Initialize(); + + const auto cb = v8impl::FunctionCallbackWrapper::Invoke; + v8impl::externalReferenceRegistry.push_back((intptr_t)cb); + if (auto p = options ? options->externalReferences : nullptr) { + for (; *p != 0; p++) { + v8impl::externalReferenceRegistry.push_back(*p); + } + } + v8impl::externalReferenceRegistry.push_back(0); + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetVM(JSVM_Env env, + JSVM_VM* result) { + *result = reinterpret_cast(env->isolate); + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CreateVM(const JSVM_CreateVMOptions* options, JSVM_VM* result) { +#ifdef TARGET_OHOS + v8impl::ResourceSchedule::ReportKeyThread(getuid(), getprocpid(), getproctid(), + v8impl::ResourceSchedule::ResType::ThreadRole::USER_INTERACT); +#endif + v8::Isolate::CreateParams create_params; + auto externalReferences = v8impl::externalReferenceRegistry.data(); + create_params.external_references = externalReferences; + + v8::StartupData* snapshotBlob = nullptr; + if (options && options->snapshotBlobData) { + snapshotBlob = new v8::StartupData(); + snapshotBlob->data = options->snapshotBlobData; + snapshotBlob->raw_size = options->snapshotBlobSize; + + if (!snapshotBlob->IsValid()) { + // TODO: Is VerifyCheckSum necessay if there has been a validity check? + delete snapshotBlob; + return JSVM_INVALID_ARG; + } + create_params.snapshot_blob = snapshotBlob; + } + + v8::Isolate* isolate; + if (options && options->isForSnapshotting) { + isolate = v8::Isolate::Allocate(); + auto creator = new v8::SnapshotCreator(isolate, externalReferences); + v8impl::SetIsolateSnapshotCreator(isolate, creator); + } else { + create_params.array_buffer_allocator = + v8impl::GetOrCreateDefaultArrayBufferAllocator(); + isolate = v8::Isolate::New(create_params); + } + v8impl::CreateIsolateData(isolate, snapshotBlob); + *result = reinterpret_cast(isolate); + + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL +OH_JSVM_DestroyVM(JSVM_VM vm) { + auto isolate = reinterpret_cast(vm); + auto creator = v8impl::GetIsolateSnapshotCreator(isolate); + auto data = v8impl::GetIsolateData(isolate); + + if (creator != nullptr) { + delete creator; + } else { + isolate->Dispose(); + } + if (data != nullptr) { + delete data; + } + + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL OH_JSVM_OpenVMScope(JSVM_VM vm, JSVM_VMScope* result) { + auto isolate = reinterpret_cast(vm); + auto scope = new v8::Isolate::Scope(isolate); + *result = reinterpret_cast(scope); + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CloseVMScope(JSVM_VM vm, JSVM_VMScope scope) { + auto v8scope = reinterpret_cast(scope); + delete v8scope; + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CreateEnv(JSVM_VM vm, + size_t propertyCount, + const JSVM_PropertyDescriptor* properties, + JSVM_Env* result) { + auto isolate = reinterpret_cast(vm); + auto env = new JSVM_Env__(isolate, NODE_API_DEFAULT_MODULE_API_VERSION); + v8::HandleScope handle_scope(isolate); + auto global_template = v8::ObjectTemplate::New(isolate); + + for (size_t i = 0; i < propertyCount; i++) { + const JSVM_PropertyDescriptor* p = properties + i; + + if ((p->attributes & JSVM_STATIC) != 0) { + //Ignore static properties. + continue; + } + + v8::Local property_name = + v8::String::NewFromUtf8(isolate, p->utf8name, v8::NewStringType::kInternalized) + .ToLocalChecked(); + + v8::PropertyAttribute attributes = + v8impl::V8PropertyAttributesFromDescriptor(p); + + if (p->getter != nullptr || p->setter != nullptr) { + v8::Local getter_tpl; + v8::Local setter_tpl; + if (p->getter != nullptr) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->getter, &getter_tpl)); + } + if (p->setter != nullptr) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->setter, &setter_tpl)); + } + + global_template->SetAccessorProperty( + property_name, getter_tpl, setter_tpl, attributes); + } else if (p->method != nullptr) { + v8::Local method_tpl; + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->method, &method_tpl)); + + global_template->Set(property_name, method_tpl, attributes); + } else { + v8::Local value = v8impl::V8LocalValueFromJsValue(p->value); + global_template->Set(property_name, value, attributes); + } + } + + v8::Local context = v8::Context::New(isolate, nullptr, global_template); + env->context_persistent.Reset(isolate, context); + v8impl::SetContextEnv(context, env); + *result = env; + return JSVM_OK; +} + +JSVM_EXTERN JSVM_Status JSVM_CDECL +OH_JSVM_CreateEnvFromSnapshot(JSVM_VM vm, size_t index, JSVM_Env* result) { + auto isolate = reinterpret_cast(vm); + v8::HandleScope handle_scope(isolate); + auto maybe = v8::Context::FromSnapshot(isolate, index); + + if (maybe.IsEmpty()) { + *result = nullptr; + // TODO: return error message. + return JSVM_GENERIC_FAILURE; + } + + auto env = new JSVM_Env__(isolate, NODE_API_DEFAULT_MODULE_API_VERSION); + auto context = maybe.ToLocalChecked(); + env->context_persistent.Reset(isolate, context); + v8impl::SetContextEnv(context, env); + *result = env; + + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL +OH_JSVM_DestroyEnv(JSVM_Env env) { + env->DeleteMe(); + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL + OH_JSVM_OpenEnvScope(JSVM_Env env, JSVM_EnvScope* result) { + auto v8scope = new v8::Context::Scope(env->context()); + *result = reinterpret_cast(v8scope); + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CloseEnvScope(JSVM_Env env, JSVM_EnvScope scope) { + auto v8scope = reinterpret_cast(scope); + delete v8scope; + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CompileScript(JSVM_Env env, + JSVM_Value script, + const uint8_t *cachedData, + size_t cachedDataLength, + bool eagerCompile, + bool* cacheRejected, + JSVM_Script* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, script); + CHECK_ARG(env, result); + + v8::Local v8_script = v8impl::V8LocalValueFromJsValue(script); + + RETURN_STATUS_IF_FALSE(env, v8_script->IsString(), JSVM_STRING_EXPECTED); + + v8::Local context = env->context(); + + v8::ScriptCompiler::CachedData* cache = cachedData + ? new v8::ScriptCompiler::CachedData(cachedData, cachedDataLength) : nullptr; + v8::ScriptCompiler::Source scriptSource(v8_script.As(), cache); + auto option = cache ? v8::ScriptCompiler::kConsumeCodeCache + : (eagerCompile ? v8::ScriptCompiler::kEagerCompile : v8::ScriptCompiler::kNoCompileOptions); + + auto maybe_script = v8::ScriptCompiler::Compile(context, &scriptSource, option); + + if (cache && cacheRejected) { + *cacheRejected = cache->rejected; + } + + CHECK_MAYBE_EMPTY(env, maybe_script, JSVM_GENERIC_FAILURE); + v8::Local compiled_script = maybe_script.ToLocalChecked(); + *result = reinterpret_cast(env->NewJsvmData(compiled_script)); + + return GET_RETURN_STATUS(env); +} + +v8::ScriptOrigin CreateScriptOrigin( + v8::Isolate* isolate, v8::Local resource_name, v8::ScriptType type) { + const int kOptionsLength = 2; + const uint32_t kOptionsMagicConstant = 0xF1F2F3F0; + auto options = v8::PrimitiveArray::New(isolate, kOptionsLength); + options->Set(isolate, 0, v8::Uint32::New(isolate, kOptionsMagicConstant)); + options->Set(isolate, 1, resource_name); + return v8::ScriptOrigin(isolate, resource_name, 0, 0, false, -1, v8::Local(), + false, false, type == v8::ScriptType::kModule, options); +} + +v8::MaybeLocal PrepareStackTraceCallback( + v8::Local context, v8::Local error, v8::Local trace) { + return v8::Local(); +//cjh auto *isolate = context->GetIsolate(); +// v8::TryCatch try_catch(isolate); +// v8::Local moduleName = +// v8::String::NewFromUtf8(isolate, "sourcemap").ToLocalChecked(); +// v8::Local moduleSourceString = +// v8::String::NewFromUtf8(isolate, SourceMapRunner.c_str()).ToLocalChecked(); +// +// v8::ScriptOrigin moduleOrigin = +// CreateScriptOrigin(isolate, moduleName, v8::ScriptType::kClassic); +// v8::Local moduleContext = v8::Context::New(isolate); +// v8::ScriptCompiler::Source moduleSource(moduleSourceString, moduleOrigin); +// auto script = +// v8::Script::Compile(moduleContext, moduleSourceString, &moduleOrigin).ToLocalChecked(); +// auto result = script->Run(moduleContext).ToLocalChecked(); +// auto resultFunc = v8::Local::Cast(result); +// +// v8::Local element = trace->Get(context, 0).ToLocalChecked(); +// std::string fileName = ""; +// if (element->IsObject()) { +// auto obj = element->ToObject(context); +// auto getFileName = v8::String::NewFromUtf8(isolate, "getFileName", v8::NewStringType::kNormal); +// auto function = obj.ToLocalChecked()->Get(context, getFileName.ToLocalChecked()).ToLocalChecked(); +// auto lineNumberFunction = v8::Local::Cast(function); +// auto fileNameObj = lineNumberFunction->Call(context, obj.ToLocalChecked(), 0, {}); +// fileName = std::string(*v8::String::Utf8Value(isolate, fileNameObj.ToLocalChecked())); +// } +// auto &&sourceMapUrl = (!fileName.empty()) ? v8impl::GetSourceMapFromFileName(std::move(fileName)) : ""; +// std::ifstream sourceMapfile(sourceMapUrl); +// std::string content = ""; +// if (sourceMapfile.good()) { +// std::stringstream buffer; +// buffer << sourceMapfile.rdbuf(); +// content = buffer.str(); +// } +// auto sourceMapObject = v8::String::NewFromUtf8( +// isolate, content.c_str(), v8::NewStringType::kNormal, content.length()); +// v8::Local args[] = { error, trace, sourceMapObject.ToLocalChecked() }; +// return resultFunc->Call(moduleContext, v8::Undefined(isolate), node::arraysize(args), args); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CompileScriptWithOrigin(JSVM_Env env, + JSVM_Value script, + const uint8_t* cachedData, + size_t cachedDataLength, + bool eagerCompile, + bool* cacheRejected, + JSVM_ScriptOrigin* origin, + JSVM_Script* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, script); + CHECK_ARG(env, result); + CHECK_NOT_NULL(origin->resourceName); + + v8::Local v8_script = v8impl::V8LocalValueFromJsValue(script); + + RETURN_STATUS_IF_FALSE(env, v8_script->IsString(), JSVM_STRING_EXPECTED); + + v8::Local context = env->context(); + auto *isolate = context->GetIsolate(); + + if (origin->sourceMapUrl) { + v8impl::SetFileToSourceMapMapping(origin->resourceName, origin->sourceMapUrl); + isolate->SetPrepareStackTraceCallback(PrepareStackTraceCallback); + } + auto sourceMapUrl = !origin->sourceMapUrl ? v8::Local() : + v8::String::NewFromUtf8(isolate, origin->sourceMapUrl).ToLocalChecked().As(); + auto resourceName = + v8::String::NewFromUtf8(isolate, origin->resourceName).ToLocalChecked(); + v8::ScriptOrigin scriptOrigin(isolate, resourceName, + origin->resourceLineOffset, origin->resourceColumnOffset, false, -1, sourceMapUrl); + + v8::ScriptCompiler::CachedData* cache = cachedData + ? new v8::ScriptCompiler::CachedData(cachedData, cachedDataLength) : nullptr; + v8::ScriptCompiler::Source scriptSource(v8_script.As(), scriptOrigin, cache); + auto option = cache ? v8::ScriptCompiler::kConsumeCodeCache + : (eagerCompile ? v8::ScriptCompiler::kEagerCompile : v8::ScriptCompiler::kNoCompileOptions); + + auto maybe_script = v8::ScriptCompiler::Compile(context, &scriptSource, option); + + if (cache && cacheRejected) { + *cacheRejected = cache->rejected; + } + + CHECK_MAYBE_EMPTY(env, maybe_script, JSVM_GENERIC_FAILURE); + v8::Local compiled_script = maybe_script.ToLocalChecked(); + *result = reinterpret_cast(env->NewJsvmData(compiled_script)); + + return GET_RETURN_STATUS(env); +} + +class CompileOptionResolver { + public: + CompileOptionResolver(size_t length, JSVM_CompileOptions options[], v8::Isolate *isolate) { + for (size_t i = 0; i < length; i++) { + switch(options[i].id) { + case JSVM_COMPILE_MODE: { + v8Option = static_cast(options[i].content.num); + break; + } + case JSVM_COMPILE_CODE_CACHE: { + auto cache = static_cast(options[i].content.ptr); + cachedData = cache->cache ? + new v8::ScriptCompiler::CachedData(cache->cache, cache->length) : nullptr; + break; + } + case JSVM_COMPILE_SCRIPT_ORIGIN: { + jsvmOrigin = static_cast(options[i].content.ptr); + break; + } + case JSVM_COMPILE_COMPILE_PROFILE: { + profile = static_cast(options[i].content.ptr); + break; + } + case JSVM_COMPILE_ENABLE_SOURCE_MAP: { + enableSourceMap = options[i].content.boolean; + break; + } + default: { + continue; + } + } + } + auto sourceString = jsvmOrigin ? jsvmOrigin->resourceName : + "script_" + std::to_string(compileCount++); + auto sourceMapPtr = jsvmOrigin && jsvmOrigin->sourceMapUrl ? + jsvmOrigin->sourceMapUrl : nullptr; + auto sourceMapUrl = (jsvmOrigin && jsvmOrigin->sourceMapUrl) ? + v8::String::NewFromUtf8(isolate, jsvmOrigin->sourceMapUrl).ToLocalChecked().As() : + v8::Local(); + auto resourceName = v8::String::NewFromUtf8(isolate, sourceString.c_str()).ToLocalChecked(); + v8Origin = new v8::ScriptOrigin(isolate, resourceName, + jsvmOrigin ? jsvmOrigin->resourceLineOffset : 0, + jsvmOrigin ? jsvmOrigin->resourceColumnOffset : 0, + false, -1, sourceMapUrl); + if (enableSourceMap && sourceMapPtr) { + v8impl::SetFileToSourceMapMapping(jsvmOrigin->resourceName, sourceMapPtr); + isolate->SetPrepareStackTraceCallback(PrepareStackTraceCallback); + } + if (v8Option == v8::ScriptCompiler::kConsumeCodeCache && !cachedData) { + hasInvalidOption = true; + } + } + + ~CompileOptionResolver() { + delete v8Origin; + v8Origin = nullptr; + } + + v8::ScriptCompiler::CompileOptions v8Option = + v8::ScriptCompiler::kNoCompileOptions; + v8::ScriptCompiler::CachedData *cachedData = nullptr; + v8::ScriptOrigin *v8Origin = nullptr; + JSVM_CompileProfile *profile = nullptr; + JSVM_ScriptOrigin *jsvmOrigin = nullptr; + bool enableSourceMap = false; + static size_t compileCount; + bool hasInvalidOption = false; +}; + +size_t CompileOptionResolver::compileCount = 0; + +JSVM_Status JSVM_CDECL +OH_JSVM_CompileScriptWithOptions(JSVM_Env env, + JSVM_Value script, + size_t optionCount, + JSVM_CompileOptions options[], + JSVM_Script* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, script); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + auto *isolate = context->GetIsolate(); + CompileOptionResolver optionResolver(optionCount, options, isolate); + RETURN_STATUS_IF_FALSE(env, !optionResolver.hasInvalidOption, JSVM_INVALID_ARG); + + v8::Local v8_script = v8impl::V8LocalValueFromJsValue(script); + + RETURN_STATUS_IF_FALSE(env, v8_script->IsString(), JSVM_STRING_EXPECTED); + + v8::ScriptCompiler::Source scriptSource(v8_script.As(), + *optionResolver.v8Origin, optionResolver.cachedData); + auto maybe_script = v8::ScriptCompiler::Compile(context, &scriptSource, optionResolver.v8Option); + + CHECK_MAYBE_EMPTY(env, maybe_script, JSVM_GENERIC_FAILURE); + v8::Local compiled_script = maybe_script.ToLocalChecked(); + *result = reinterpret_cast(env->NewJsvmData(compiled_script)); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CreateCodeCache(JSVM_Env env, + JSVM_Script script, + const uint8_t** data, + size_t* length) { + auto jsvmData = reinterpret_cast(script); + auto v8script = jsvmData->ToV8Local(env->isolate); + v8::ScriptCompiler::CachedData* cache; + cache = v8::ScriptCompiler::CreateCodeCache(v8script->GetUnboundScript()); + + if (cache == nullptr) { + // TODO: return error + return jsvm_set_last_error(env, JSVM_GENERIC_FAILURE); + } + + *data = cache->data; + *length = cache->length; + cache->buffer_policy = v8::ScriptCompiler::CachedData::BufferNotOwned; + delete cache; + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL +OH_JSVM_RunScript(JSVM_Env env, JSVM_Script script, JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, script); + CHECK_ARG(env, result); + + auto jsvmData = reinterpret_cast(script); + auto v8script = jsvmData->ToV8Local(env->isolate); + auto script_result = v8script->Run(env->context()); + CHECK_MAYBE_EMPTY(env, script_result, JSVM_GENERIC_FAILURE); + *result = v8impl::JsValueFromV8LocalValue(script_result.ToLocalChecked()); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_JsonParse(JSVM_Env env, JSVM_Value json_string, JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, json_string); + + v8::Local val = v8impl::V8LocalValueFromJsValue(json_string); + RETURN_STATUS_IF_FALSE(env, val->IsString(), JSVM_STRING_EXPECTED); + + auto maybe = v8::JSON::Parse(env->context(), val.As()); + CHECK_MAYBE_EMPTY(env, maybe,JSVM_GENERIC_FAILURE); + *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_JsonStringify(JSVM_Env env, JSVM_Value json_object, JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, json_object); + + v8::Local val = v8impl::V8LocalValueFromJsValue(json_object); + + auto maybe = v8::JSON::Stringify(env->context(), val); + CHECK_MAYBE_EMPTY(env, maybe,JSVM_GENERIC_FAILURE); + *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CreateSnapshot(JSVM_VM vm, + size_t contextCount, + const JSVM_Env* contexts, + const char** blobData, + size_t* blobSize) { + auto isolate = reinterpret_cast(vm); + auto creator = v8impl::GetIsolateSnapshotCreator(isolate); + + if (creator == nullptr) { + // TODO: return specific error message. + return JSVM_GENERIC_FAILURE; + } + { + v8::HandleScope scope(isolate); + v8::Local default_context = v8::Context::New(isolate); + creator->SetDefaultContext(default_context); + // NOTE: The order of the added data must be consistent with the order of + // getting data in v8impl::CreateIsolateData. + creator->AddData(JSVM_PRIVATE_KEY(isolate, wrapper)); + creator->AddData(JSVM_PRIVATE_KEY(isolate, type_tag)); + + for (size_t i = 0; i < contextCount; i++) { + auto ctx = contexts[i]->context(); + creator->AddData(ctx, ctx); + creator->AddContext(ctx); + } + } + auto blob = creator->CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kKeep); + *blobData = blob.data; + *blobSize = blob.raw_size; + + return JSVM_OK; +} + +JSVM_EXTERN JSVM_Status JSVM_CDECL OH_JSVM_GetVMInfo(JSVM_VMInfo* result) { + result->apiVersion = 1; + result->engine = "v8"; + result->version = V8_VERSION_STRING; + result->cachedDataVersionTag = v8::ScriptCompiler::CachedDataVersionTag(); + return JSVM_OK; +} + +JSVM_EXTERN JSVM_Status JSVM_CDECL +OH_JSVM_MemoryPressureNotification(JSVM_Env env, + JSVM_MemoryPressureLevel level) { + CHECK_ENV(env); + env->isolate->MemoryPressureNotification(v8::MemoryPressureLevel(level)); + return jsvm_clear_last_error(env); +} + +JSVM_EXTERN JSVM_Status JSVM_CDECL +OH_JSVM_GetHeapStatistics(JSVM_VM vm, JSVM_HeapStatistics* result) { + auto isolate = reinterpret_cast(vm); + v8::HeapStatistics stats; + isolate->GetHeapStatistics(&stats); + result->totalHeapSize = stats.total_heap_size(); + result->totalHeapSizeExecutable = stats.total_heap_size_executable(); + result->totalPhysicalSize = stats.total_physical_size(); + result->totalAvailableSize = stats.total_available_size(); + result->usedHeapSize = stats.used_heap_size(); + result->heapSizeLimit = stats.heap_size_limit(); + result->mallocedMemory = stats.malloced_memory(); + result->externalMemory = stats.external_memory(); + result->peakMallocedMemory = stats.peak_malloced_memory(); + result->numberOfNativeContexts = stats.number_of_native_contexts(); + result->numberOfDetachedContexts = stats.number_of_detached_contexts(); + result->totalGlobalHandlesSize = stats.total_global_handles_size(); + result->usedGlobalHandlesSize = stats.used_global_handles_size(); + return JSVM_OK; +} + +//cjh JSVM_EXTERN JSVM_Status JSVM_CDECL +//OH_JSVM_StartCpuProfiler(JSVM_VM vm, JSVM_CpuProfiler* result) { +// auto isolate = reinterpret_cast(vm); +// auto profiler = v8::CpuProfiler::New(isolate); +// v8::HandleScope scope(isolate); +// v8::CpuProfilingOptions options; +// profiler->Start(v8::String::Empty(isolate), std::move(options)); +// *result = reinterpret_cast(profiler); +// return JSVM_OK; +//} +// +//JSVM_EXTERN JSVM_Status JSVM_CDECL +//OH_JSVM_StopCpuProfiler(JSVM_VM vm, JSVM_CpuProfiler profiler, +// JSVM_OutputStream stream, void* streamData) { +// auto isolate = reinterpret_cast(vm); +// auto v8profiler = reinterpret_cast(profiler); +// v8::HandleScope scope(isolate); +// auto profile = v8profiler->StopProfiling(v8::String::Empty(isolate)); +// v8impl::OutputStream os(stream, streamData); +// profile->Serialize(&os); +// return JSVM_OK; +//} +// +//JSVM_EXTERN JSVM_Status JSVM_CDECL +//OH_JSVM_TakeHeapSnapshot(JSVM_VM vm, +// JSVM_OutputStream stream, void* streamData) { +// auto isolate = reinterpret_cast(vm); +// auto profiler = isolate->GetHeapProfiler(); +// auto snapshot = profiler->TakeHeapSnapshot(); +// v8impl::OutputStream os(stream, streamData); +// snapshot->Serialize(&os); +// return JSVM_OK; +//} +// +//JSVM_EXTERN JSVM_Status JSVM_CDECL +//OH_JSVM_OpenInspector(JSVM_Env env, const char* host, uint16_t port) { +// JSVM_PREAMBLE(env); +// +// std::string inspectorPath; +// std::string hostName(host); +// auto hostPort = +// std::make_shared>(hostName, port); +// env->inspector_agent()->Start(inspectorPath, hostPort, true, false); +// +// return GET_RETURN_STATUS(env); +//} +// +//JSVM_EXTERN JSVM_Status JSVM_CDECL OH_JSVM_CloseInspector(JSVM_Env env) { +// JSVM_PREAMBLE(env); +// auto agent = env->inspector_agent(); +// if (!agent->IsActive()) { +// return JSVM_GENERIC_FAILURE; +// } +// agent->Stop(); +// return GET_RETURN_STATUS(env); +//} +// +//JSVM_EXTERN JSVM_Status JSVM_CDECL OH_JSVM_WaitForDebugger(JSVM_Env env, bool breakNextLine) { +// JSVM_PREAMBLE(env); +// auto agent = env->inspector_agent(); +// if (!agent->IsActive()) { +// return JSVM_GENERIC_FAILURE; +// } +// +// agent->WaitForConnect(); +// if (breakNextLine) { +// agent->PauseOnNextJavascriptStatement("Break on debugger attached"); +// } +// +// return GET_RETURN_STATUS(env); +//} + +JSVM_EXTERN JSVM_Status JSVM_CDECL OH_JSVM_PumpMessageLoop(JSVM_VM vm, bool* result) { + auto isolate = reinterpret_cast(vm); + *result = v8::platform::PumpMessageLoop(v8impl::g_platform.get(), isolate); + return JSVM_OK; +} + +JSVM_EXTERN JSVM_Status JSVM_CDECL OH_JSVM_PerformMicrotaskCheckpoint(JSVM_VM vm) { + auto isolate = reinterpret_cast(vm); + isolate->PerformMicrotaskCheckpoint(); + return JSVM_OK; +} + +// Warning: Keep in-sync with JSVM_Status enum +static const char* error_messages[] = { + nullptr, + "Invalid argument", + "An object was expected", + "A string was expected", + "A string or symbol was expected", + "A function was expected", + "A number was expected", + "A boolean was expected", + "An array was expected", + "Unknown failure", + "An exception is pending", + "The async work item was cancelled", + "OH_JSVM_EscapeHandle already called on scope", + "Invalid handle scope usage", + "Invalid callback scope usage", + "Thread-safe function queue is full", + "Thread-safe function handle is closing", + "A bigint was expected", + "A date was expected", + "An arraybuffer was expected", + "A detachable arraybuffer was expected", + "Main thread would deadlock", + "External buffers are not allowed", + "Cannot run JavaScript", +}; + +JSVM_Status JSVM_CDECL OH_JSVM_GetLastErrorInfo( + JSVM_Env env, const JSVM_ExtendedErrorInfo** result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + // The value of the constant below must be updated to reference the last + // message in the `JSVM_Status` enum each time a new error message is added. + // We don't have a jsvm_status_last as this would result in an ABI + // change each time a message was added. + const int last_status = JSVM_CANNOT_RUN_JS; + + static_assert(JSVM_ARRAYSIZE(error_messages) == last_status + 1, + "Count of error messages must match count of error values"); + CHECK_LE(env->last_error.errorCode, last_status); + // Wait until someone requests the last error information to fetch the error + // message string + env->last_error.errorMessage = error_messages[env->last_error.errorCode]; + + if (env->last_error.errorCode == JSVM_OK) { + jsvm_clear_last_error(env); + } + *result = &(env->last_error); + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateFunction(JSVM_Env env, + const char* utf8name, + size_t length, + JSVM_Callback cb, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + CHECK_ARG(env, cb); + + v8::Local return_value; + v8::EscapableHandleScope scope(env->isolate); + v8::Local fn; + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewFunction( + env, cb, &fn)); + return_value = scope.Escape(fn); + + if (utf8name != nullptr) { + v8::Local name_string; + CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); + return_value->SetName(name_string); + } + + *result = v8impl::JsValueFromV8LocalValue(return_value); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateFunctionWithScript(JSVM_Env env, + const char* funcName, + size_t length, + size_t argc, + const JSVM_Value* argv, + JSVM_Value script, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, script); + CHECK_ARG(env, result); + if (argc > 0) { + CHECK_ARG(env, argv); + for (auto i = 0; i < argc; i++) { + RETURN_STATUS_IF_FALSE(env, v8impl::V8LocalValueFromJsValue(argv[i])->IsString(), + JSVM_STRING_EXPECTED); + } + } + + v8::Local v8_script = v8impl::V8LocalValueFromJsValue(script); + + RETURN_STATUS_IF_FALSE(env, v8_script->IsString(), JSVM_STRING_EXPECTED); + + v8::ScriptCompiler::Source scriptSource(v8_script.As()); + + v8::Local context = env->context(); + + v8::MaybeLocal maybe_fun = + v8::ScriptCompiler::CompileFunction(context, &scriptSource, argc, + reinterpret_cast*>(const_cast(argv))); + + CHECK_MAYBE_EMPTY(env, maybe_fun, JSVM_GENERIC_FAILURE); + + v8::Local func = maybe_fun.ToLocalChecked(); + + if (funcName != nullptr) { + v8::Local funcNameString; + CHECK_NEW_FROM_UTF8_LEN(env, funcNameString, funcName, length); + func->SetName(funcNameString); + } + + *result = + v8impl::JsValueFromV8LocalValue(func); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_DefineClass(JSVM_Env env, + const char* utf8name, + size_t length, + JSVM_Callback constructor, + size_t propertyCount, + const JSVM_PropertyDescriptor* properties, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + CHECK_ARG(env, constructor); + + if (propertyCount > 0) { + CHECK_ARG(env, properties); + } + + v8::Isolate* isolate = env->isolate; + + v8::EscapableHandleScope scope(isolate); + v8::Local tpl; + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, constructor, &tpl)); + + v8::Local name_string; + CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); + tpl->SetClassName(name_string); + + size_t static_property_count = 0; + for (size_t i = 0; i < propertyCount; i++) { + const JSVM_PropertyDescriptor* p = properties + i; + + if ((p->attributes & JSVM_STATIC) != 0) { + // Static properties are handled separately below. + static_property_count++; + continue; + } + + v8::Local property_name; + STATUS_CALL(v8impl::V8NameFromPropertyDescriptor(env, p, &property_name)); + + v8::PropertyAttribute attributes = + v8impl::V8PropertyAttributesFromDescriptor(p); + + // This code is similar to that in OH_JSVM_DefineProperties(); the + // difference is it applies to a template instead of an object, + // and preferred PropertyAttribute for lack of PropertyDescriptor + // support on ObjectTemplate. + if (p->getter != nullptr || p->setter != nullptr) { + v8::Local getter_tpl; + v8::Local setter_tpl; + if (p->getter != nullptr) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->getter, &getter_tpl)); + } + if (p->setter != nullptr) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->setter, &setter_tpl)); + } + + tpl->PrototypeTemplate()->SetAccessorProperty(property_name, + getter_tpl, + setter_tpl, + attributes, + v8::AccessControl::DEFAULT); + } else if (p->method != nullptr) { + v8::Local t; + if (p->attributes & JSVM_NO_RECEIVER_CHECK) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->method, &t)); + } else { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->method, &t, v8::Signature::New(isolate, tpl))); + } + + tpl->PrototypeTemplate()->Set(property_name, t, attributes); + } else { + v8::Local value = v8impl::V8LocalValueFromJsValue(p->value); + tpl->PrototypeTemplate()->Set(property_name, value, attributes); + } + } + + v8::Local context = env->context(); + *result = v8impl::JsValueFromV8LocalValue( + scope.Escape(tpl->GetFunction(context).ToLocalChecked())); + + if (static_property_count > 0) { + std::vector static_descriptors; + static_descriptors.reserve(static_property_count); + + for (size_t i = 0; i < propertyCount; i++) { + const JSVM_PropertyDescriptor* p = properties + i; + if ((p->attributes & JSVM_STATIC) != 0) { + static_descriptors.push_back(*p); + } + } + + STATUS_CALL(OH_JSVM_DefineProperties( + env, *result, static_descriptors.size(), static_descriptors.data())); + } + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetPropertyNames(JSVM_Env env, + JSVM_Value object, + JSVM_Value* result) { + return OH_JSVM_GetAllPropertyNames( + env, + object, + JSVM_KEY_INCLUDE_PROTOTYPES, + static_cast(JSVM_KEY_ENUMERABLE | JSVM_KEY_SKIP_SYMBOLS), + JSVM_KEY_NUMBERS_TO_STRINGS, + result); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_GetAllPropertyNames(JSVM_Env env, + JSVM_Value object, + JSVM_KeyCollectionMode keyMode, + JSVM_KeyFilter keyFilter, + JSVM_KeyConversion keyConversion, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, object); + + v8::PropertyFilter filter = v8::PropertyFilter::ALL_PROPERTIES; + if (keyFilter & JSVM_KEY_WRITABLE) { + filter = static_cast(filter | + v8::PropertyFilter::ONLY_WRITABLE); + } + if (keyFilter & JSVM_KEY_ENUMERABLE) { + filter = static_cast( + filter | v8::PropertyFilter::ONLY_ENUMERABLE); + } + if (keyFilter & JSVM_KEY_CONFIGURABLE) { + filter = static_cast( + filter | v8::PropertyFilter::ONLY_CONFIGURABLE); + } + if (keyFilter & JSVM_KEY_SKIP_STRINGS) { + filter = static_cast(filter | + v8::PropertyFilter::SKIP_STRINGS); + } + if (keyFilter & JSVM_KEY_SKIP_SYMBOLS) { + filter = static_cast(filter | + v8::PropertyFilter::SKIP_SYMBOLS); + } + v8::KeyCollectionMode collection_mode; + v8::KeyConversionMode conversion_mode; + + switch (keyMode) { + case JSVM_KEY_INCLUDE_PROTOTYPES: + collection_mode = v8::KeyCollectionMode::kIncludePrototypes; + break; + case JSVM_KEY_OWN_ONLY: + collection_mode = v8::KeyCollectionMode::kOwnOnly; + break; + default: + return jsvm_set_last_error(env, JSVM_INVALID_ARG); + } + + switch (keyConversion) { + case JSVM_KEY_KEEP_NUMBERS: + conversion_mode = v8::KeyConversionMode::kKeepNumbers; + break; + case JSVM_KEY_NUMBERS_TO_STRINGS: + conversion_mode = v8::KeyConversionMode::kConvertToString; + break; + default: + return jsvm_set_last_error(env, JSVM_INVALID_ARG); + } + + v8::MaybeLocal maybe_all_propertynames = + obj->GetPropertyNames(context, + collection_mode, + filter, + v8::IndexFilter::kIncludeIndices, + conversion_mode); + + CHECK_MAYBE_EMPTY_WITH_PREAMBLE( + env, maybe_all_propertynames, JSVM_GENERIC_FAILURE); + + *result = + v8impl::JsValueFromV8LocalValue(maybe_all_propertynames.ToLocalChecked()); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_SetProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + JSVM_Value value) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, key); + CHECK_ARG(env, value); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + v8::Maybe set_maybe = obj->Set(context, k, val); + + RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), JSVM_GENERIC_FAILURE); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_HasProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + bool* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + CHECK_ARG(env, key); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + v8::Maybe has_maybe = obj->Has(context, k); + + CHECK_MAYBE_NOTHING(env, has_maybe, JSVM_GENERIC_FAILURE); + + *result = has_maybe.FromMaybe(false); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, key); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + auto get_maybe = obj->Get(context, k); + + CHECK_MAYBE_EMPTY(env, get_maybe, JSVM_GENERIC_FAILURE); + + v8::Local val = get_maybe.ToLocalChecked(); + *result = v8impl::JsValueFromV8LocalValue(val); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_DeleteProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + bool* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, key); + + v8::Local context = env->context(); + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + v8::Maybe delete_maybe = obj->Delete(context, k); + CHECK_MAYBE_NOTHING(env, delete_maybe, JSVM_GENERIC_FAILURE); + + if (result != nullptr) *result = delete_maybe.FromMaybe(false); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_HasOwnProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + bool* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, key); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + RETURN_STATUS_IF_FALSE(env, k->IsName(), JSVM_NAME_EXPECTED); + v8::Maybe has_maybe = obj->HasOwnProperty(context, k.As()); + CHECK_MAYBE_NOTHING(env, has_maybe, JSVM_GENERIC_FAILURE); + *result = has_maybe.FromMaybe(false); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_SetNamedProperty(JSVM_Env env, + JSVM_Value object, + const char* utf8name, + JSVM_Value value) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, value); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local key; + CHECK_NEW_FROM_UTF8(env, key, utf8name); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + v8::Maybe set_maybe = obj->Set(context, key, val); + + RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), JSVM_GENERIC_FAILURE); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_HasNamedProperty(JSVM_Env env, + JSVM_Value object, + const char* utf8name, + bool* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local key; + CHECK_NEW_FROM_UTF8(env, key, utf8name); + + v8::Maybe has_maybe = obj->Has(context, key); + + CHECK_MAYBE_NOTHING(env, has_maybe, JSVM_GENERIC_FAILURE); + + *result = has_maybe.FromMaybe(false); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetNamedProperty(JSVM_Env env, + JSVM_Value object, + const char* utf8name, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + v8::Local key; + CHECK_NEW_FROM_UTF8(env, key, utf8name); + + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + auto get_maybe = obj->Get(context, key); + + CHECK_MAYBE_EMPTY(env, get_maybe, JSVM_GENERIC_FAILURE); + + v8::Local val = get_maybe.ToLocalChecked(); + *result = v8impl::JsValueFromV8LocalValue(val); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_SetElement(JSVM_Env env, + JSVM_Value object, + uint32_t index, + JSVM_Value value) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, value); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + auto set_maybe = obj->Set(context, index, val); + + RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), JSVM_GENERIC_FAILURE); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_HasElement(JSVM_Env env, + JSVM_Value object, + uint32_t index, + bool* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Maybe has_maybe = obj->Has(context, index); + + CHECK_MAYBE_NOTHING(env, has_maybe, JSVM_GENERIC_FAILURE); + + *result = has_maybe.FromMaybe(false); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetElement(JSVM_Env env, + JSVM_Value object, + uint32_t index, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + auto get_maybe = obj->Get(context, index); + + CHECK_MAYBE_EMPTY(env, get_maybe, JSVM_GENERIC_FAILURE); + + *result = v8impl::JsValueFromV8LocalValue(get_maybe.ToLocalChecked()); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_DeleteElement(JSVM_Env env, + JSVM_Value object, + uint32_t index, + bool* result) { + JSVM_PREAMBLE(env); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + v8::Maybe delete_maybe = obj->Delete(context, index); + CHECK_MAYBE_NOTHING(env, delete_maybe, JSVM_GENERIC_FAILURE); + + if (result != nullptr) *result = delete_maybe.FromMaybe(false); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_DefineProperties(JSVM_Env env, + JSVM_Value object, + size_t propertyCount, + const JSVM_PropertyDescriptor* properties) { + JSVM_PREAMBLE(env); + if (propertyCount > 0) { + CHECK_ARG(env, properties); + } + + v8::Local context = env->context(); + + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, object); + + for (size_t i = 0; i < propertyCount; i++) { + const JSVM_PropertyDescriptor* p = &properties[i]; + + v8::Local property_name; + STATUS_CALL(v8impl::V8NameFromPropertyDescriptor(env, p, &property_name)); + + if (p->getter != nullptr || p->setter != nullptr) { + v8::Local local_getter; + v8::Local local_setter; + + if (p->getter != nullptr) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewFunction( + env, p->getter, &local_getter)); + } + if (p->setter != nullptr) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewFunction( + env, p->setter, &local_setter)); + } + + v8::PropertyDescriptor descriptor(local_getter, local_setter); + descriptor.set_enumerable((p->attributes & JSVM_ENUMERABLE) != 0); + descriptor.set_configurable((p->attributes & JSVM_CONFIGURABLE) != 0); + + auto define_maybe = + obj->DefineProperty(context, property_name, descriptor); + + if (!define_maybe.FromMaybe(false)) { + return jsvm_set_last_error(env, JSVM_INVALID_ARG); + } + } else if (p->method != nullptr) { + v8::Local method; + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewFunction( + env, p->method, &method)); + v8::PropertyDescriptor descriptor(method, + (p->attributes & JSVM_WRITABLE) != 0); + descriptor.set_enumerable((p->attributes & JSVM_ENUMERABLE) != 0); + descriptor.set_configurable((p->attributes & JSVM_CONFIGURABLE) != 0); + + auto define_maybe = + obj->DefineProperty(context, property_name, descriptor); + + if (!define_maybe.FromMaybe(false)) { + return jsvm_set_last_error(env, JSVM_GENERIC_FAILURE); + } + } else { + v8::Local value = v8impl::V8LocalValueFromJsValue(p->value); + bool defined_successfully = false; + + if ((p->attributes & JSVM_ENUMERABLE) && + (p->attributes & JSVM_WRITABLE) && + (p->attributes & JSVM_CONFIGURABLE)) { + // Use a fast path for this type of data property. + auto define_maybe = + obj->CreateDataProperty(context, property_name, value); + defined_successfully = define_maybe.FromMaybe(false); + } else { + v8::PropertyDescriptor descriptor(value, + (p->attributes & JSVM_WRITABLE) != 0); + descriptor.set_enumerable((p->attributes & JSVM_ENUMERABLE) != 0); + descriptor.set_configurable((p->attributes & JSVM_CONFIGURABLE) != 0); + + auto define_maybe = + obj->DefineProperty(context, property_name, descriptor); + defined_successfully = define_maybe.FromMaybe(false); + } + + if (!defined_successfully) { + return jsvm_set_last_error(env, JSVM_INVALID_ARG); + } + } + } + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ObjectFreeze(JSVM_Env env, JSVM_Value object) { + JSVM_PREAMBLE(env); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Maybe set_frozen = + obj->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen); + + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE( + env, set_frozen.FromMaybe(false), JSVM_GENERIC_FAILURE); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ObjectSeal(JSVM_Env env, JSVM_Value object) { + JSVM_PREAMBLE(env); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Maybe set_sealed = + obj->SetIntegrityLevel(context, v8::IntegrityLevel::kSealed); + + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE( + env, set_sealed.FromMaybe(false), JSVM_GENERIC_FAILURE); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsArray(JSVM_Env env, + JSVM_Value value, + bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + *result = val->IsArray(); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsRegExp(JSVM_Env env, + JSVM_Value value, + bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + *result = val->IsRegExp(); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetArrayLength(JSVM_Env env, + JSVM_Value value, + uint32_t* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsArray(), JSVM_ARRAY_EXPECTED); + + v8::Local arr = val.As(); + *result = arr->Length(); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_StrictEquals(JSVM_Env env, + JSVM_Value lhs, + JSVM_Value rhs, + bool* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, lhs); + CHECK_ARG(env, rhs); + CHECK_ARG(env, result); + + v8::Local a = v8impl::V8LocalValueFromJsValue(lhs); + v8::Local b = v8impl::V8LocalValueFromJsValue(rhs); + + *result = a->StrictEquals(b); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_Equals(JSVM_Env env, + JSVM_Value lhs, + JSVM_Value rhs, + bool* result) +{ + JSVM_PREAMBLE(env); + CHECK_ARG(env, lhs); + CHECK_ARG(env, rhs); + CHECK_ARG(env, result); + + v8::Local a = v8impl::V8LocalValueFromJsValue(lhs); + v8::Local b = v8impl::V8LocalValueFromJsValue(rhs); + v8::Local context = env->context(); + + *result = a->Equals(context, b).FromJust(); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetPrototype(JSVM_Env env, + JSVM_Value object, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local val = obj->GetPrototype(); + *result = v8impl::JsValueFromV8LocalValue(val); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateObject(JSVM_Env env, JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue(v8::Object::New(env->isolate)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateArray(JSVM_Env env, JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue(v8::Array::New(env->isolate)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateArrayWithLength(JSVM_Env env, + size_t length, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = + v8impl::JsValueFromV8LocalValue(v8::Array::New(env->isolate, length)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateStringLatin1(JSVM_Env env, + const char* str, + size_t length, + JSVM_Value* result) { + return v8impl::NewString(env, str, length, result, [&](v8::Isolate* isolate) { + return v8::String::NewFromOneByte(isolate, + reinterpret_cast(str), + v8::NewStringType::kNormal, + length); + }); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateStringUtf8(JSVM_Env env, + const char* str, + size_t length, + JSVM_Value* result) { + return v8impl::NewString(env, str, length, result, [&](v8::Isolate* isolate) { + return v8::String::NewFromUtf8( + isolate, str, v8::NewStringType::kNormal, static_cast(length)); + }); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateStringUtf16(JSVM_Env env, + const char16_t* str, + size_t length, + JSVM_Value* result) { + return v8impl::NewString(env, str, length, result, [&](v8::Isolate* isolate) { + return v8::String::NewFromTwoByte(isolate, + reinterpret_cast(str), + v8::NewStringType::kNormal, + length); + }); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateDouble(JSVM_Env env, + double value, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = + v8impl::JsValueFromV8LocalValue(v8::Number::New(env->isolate, value)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateInt32(JSVM_Env env, + int32_t value, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = + v8impl::JsValueFromV8LocalValue(v8::Integer::New(env->isolate, value)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateUint32(JSVM_Env env, + uint32_t value, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Integer::NewFromUnsigned(env->isolate, value)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateInt64(JSVM_Env env, + int64_t value, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Number::New(env->isolate, static_cast(value))); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateBigintInt64(JSVM_Env env, + int64_t value, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = + v8impl::JsValueFromV8LocalValue(v8::BigInt::New(env->isolate, value)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateBigintUint64(JSVM_Env env, + uint64_t value, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::BigInt::NewFromUnsigned(env->isolate, value)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateBigintWords(JSVM_Env env, + int signBit, + size_t wordCount, + const uint64_t* words, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, words); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + RETURN_STATUS_IF_FALSE(env, wordCount <= INT_MAX, JSVM_INVALID_ARG); + + v8::MaybeLocal b = + v8::BigInt::NewFromWords(context, signBit, wordCount, words); + + CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, b, JSVM_GENERIC_FAILURE); + + *result = v8impl::JsValueFromV8LocalValue(b.ToLocalChecked()); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetBoolean(JSVM_Env env, + bool value, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + + if (value) { + *result = v8impl::JsValueFromV8LocalValue(v8::True(isolate)); + } else { + *result = v8impl::JsValueFromV8LocalValue(v8::False(isolate)); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateSymbol(JSVM_Env env, + JSVM_Value description, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + + if (description == nullptr) { + *result = v8impl::JsValueFromV8LocalValue(v8::Symbol::New(isolate)); + } else { + v8::Local desc = v8impl::V8LocalValueFromJsValue(description); + RETURN_STATUS_IF_FALSE(env, desc->IsString(), JSVM_STRING_EXPECTED); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Symbol::New(isolate, desc.As())); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_SymbolFor(JSVM_Env env, + const char* utf8description, + size_t length, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + JSVM_Value js_description_string; + STATUS_CALL(OH_JSVM_CreateStringUtf8( + env, utf8description, length, &js_description_string)); + v8::Local description_string = + v8impl::V8LocalValueFromJsValue(js_description_string).As(); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Symbol::For(env->isolate, description_string)); + + return jsvm_clear_last_error(env); +} + +static inline JSVM_Status set_error_code(JSVM_Env env, + v8::Local error, + JSVM_Value code, + const char* code_cstring) { + if ((code != nullptr) || (code_cstring != nullptr)) { + v8::Local context = env->context(); + v8::Local err_object = error.As(); + + v8::Local code_value = v8impl::V8LocalValueFromJsValue(code); + if (code != nullptr) { + code_value = v8impl::V8LocalValueFromJsValue(code); + RETURN_STATUS_IF_FALSE(env, code_value->IsString(), JSVM_STRING_EXPECTED); + } else { + CHECK_NEW_FROM_UTF8(env, code_value, code_cstring); + } + + v8::Local code_key; + CHECK_NEW_FROM_UTF8(env, code_key, "code"); + + v8::Maybe set_maybe = err_object->Set(context, code_key, code_value); + RETURN_STATUS_IF_FALSE( + env, set_maybe.FromMaybe(false), JSVM_GENERIC_FAILURE); + } + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateError(JSVM_Env env, + JSVM_Value code, + JSVM_Value msg, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, msg); + CHECK_ARG(env, result); + + v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); + RETURN_STATUS_IF_FALSE(env, message_value->IsString(), JSVM_STRING_EXPECTED); + + v8::Local error_obj = + v8::Exception::Error(message_value.As()); + STATUS_CALL(set_error_code(env, error_obj, code, nullptr)); + + *result = v8impl::JsValueFromV8LocalValue(error_obj); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateTypeError(JSVM_Env env, + JSVM_Value code, + JSVM_Value msg, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, msg); + CHECK_ARG(env, result); + + v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); + RETURN_STATUS_IF_FALSE(env, message_value->IsString(), JSVM_STRING_EXPECTED); + + v8::Local error_obj = + v8::Exception::TypeError(message_value.As()); + STATUS_CALL(set_error_code(env, error_obj, code, nullptr)); + + *result = v8impl::JsValueFromV8LocalValue(error_obj); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateRangeError(JSVM_Env env, + JSVM_Value code, + JSVM_Value msg, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, msg); + CHECK_ARG(env, result); + + v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); + RETURN_STATUS_IF_FALSE(env, message_value->IsString(), JSVM_STRING_EXPECTED); + + v8::Local error_obj = + v8::Exception::RangeError(message_value.As()); + STATUS_CALL(set_error_code(env, error_obj, code, nullptr)); + + *result = v8impl::JsValueFromV8LocalValue(error_obj); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateSyntaxError(JSVM_Env env, + JSVM_Value code, + JSVM_Value msg, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, msg); + CHECK_ARG(env, result); + + v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); + RETURN_STATUS_IF_FALSE(env, message_value->IsString(), JSVM_STRING_EXPECTED); + + v8::Local error_obj = + v8::Exception::SyntaxError(message_value.As()); + STATUS_CALL(set_error_code(env, error_obj, code, nullptr)); + + *result = v8impl::JsValueFromV8LocalValue(error_obj); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_Typeof(JSVM_Env env, + JSVM_Value value, + JSVM_ValueType* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local v = v8impl::V8LocalValueFromJsValue(value); + + if (v->IsNumber()) { + *result = JSVM_NUMBER; + } else if (v->IsBigInt()) { + *result = JSVM_BIGINT; + } else if (v->IsString()) { + *result = JSVM_STRING; + } else if (v->IsFunction()) { + // This test has to come before IsObject because IsFunction + // implies IsObject + *result = JSVM_FUNCTION; + } else if (v->IsExternal()) { + // This test has to come before IsObject because IsExternal + // implies IsObject + *result = JSVM_EXTERNAL; + } else if (v->IsObject()) { + *result = JSVM_OBJECT; + } else if (v->IsBoolean()) { + *result = JSVM_BOOLEAN; + } else if (v->IsUndefined()) { + *result = JSVM_UNDEFINED; + } else if (v->IsSymbol()) { + *result = JSVM_SYMBOL; + } else if (v->IsNull()) { + *result = JSVM_NULL; + } else { + // Should not get here unless V8 has added some new kind of value. + return jsvm_set_last_error(env, JSVM_INVALID_ARG); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetUndefined(JSVM_Env env, JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue(v8::Undefined(env->isolate)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetNull(JSVM_Env env, JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue(v8::Null(env->isolate)); + + return jsvm_clear_last_error(env); +} + +// Gets all callback info in a single call. (Ugly, but faster.) +JSVM_Status JSVM_CDECL OH_JSVM_GetCbInfo( + JSVM_Env env, // [in] JSVM environment handle + JSVM_CallbackInfo cbinfo, // [in] Opaque callback-info handle + size_t* argc, // [in-out] Specifies the size of the provided argv array + // and receives the actual count of args. + JSVM_Value* argv, // [out] Array of values + JSVM_Value* thisArg, // [out] Receives the JS 'this' arg for the call + void** data) { // [out] Receives the data pointer for the callback. + CHECK_ENV(env); + CHECK_ARG(env, cbinfo); + + v8impl::CallbackWrapper* info = + reinterpret_cast(cbinfo); + + if (argv != nullptr) { + CHECK_ARG(env, argc); + info->Args(argv, *argc); + } + if (argc != nullptr) { + *argc = info->ArgsLength(); + } + if (thisArg != nullptr) { + *thisArg = info->This(); + } + if (data != nullptr) { + *data = info->Data(); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetNewTarget(JSVM_Env env, + JSVM_CallbackInfo cbinfo, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, cbinfo); + CHECK_ARG(env, result); + + v8impl::CallbackWrapper* info = + reinterpret_cast(cbinfo); + + *result = info->GetNewTarget(); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CallFunction(JSVM_Env env, + JSVM_Value recv, + JSVM_Value func, + size_t argc, + const JSVM_Value* argv, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, recv); + if (argc > 0) { + CHECK_ARG(env, argv); + } + + v8::Local context = env->context(); + + v8::Local v8recv = v8impl::V8LocalValueFromJsValue(recv); + + v8::Local v8func; + CHECK_TO_FUNCTION(env, v8func, func); + + auto maybe = v8func->Call( + context, + v8recv, + argc, + reinterpret_cast*>(const_cast(argv))); + + if (try_catch.HasCaught()) { + return jsvm_set_last_error(env, JSVM_PENDING_EXCEPTION); + } else { + if (result != nullptr) { + CHECK_MAYBE_EMPTY(env, maybe, JSVM_GENERIC_FAILURE); + *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); + } + return jsvm_clear_last_error(env); + } +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetGlobal(JSVM_Env env, JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue(env->context()->Global()); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_Throw(JSVM_Env env, JSVM_Value error) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, error); + + v8::Isolate* isolate = env->isolate; + + isolate->ThrowException(v8impl::V8LocalValueFromJsValue(error)); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ThrowError(JSVM_Env env, + const char* code, + const char* msg) { + JSVM_PREAMBLE(env); + + v8::Isolate* isolate = env->isolate; + v8::Local str; + CHECK_NEW_FROM_UTF8(env, str, msg); + + v8::Local error_obj = v8::Exception::Error(str); + STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); + + isolate->ThrowException(error_obj); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ThrowTypeError(JSVM_Env env, + const char* code, + const char* msg) { + JSVM_PREAMBLE(env); + + v8::Isolate* isolate = env->isolate; + v8::Local str; + CHECK_NEW_FROM_UTF8(env, str, msg); + + v8::Local error_obj = v8::Exception::TypeError(str); + STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); + + isolate->ThrowException(error_obj); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ThrowRangeError(JSVM_Env env, + const char* code, + const char* msg) { + JSVM_PREAMBLE(env); + + v8::Isolate* isolate = env->isolate; + v8::Local str; + CHECK_NEW_FROM_UTF8(env, str, msg); + + v8::Local error_obj = v8::Exception::RangeError(str); + STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); + + isolate->ThrowException(error_obj); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ThrowSyntaxError(JSVM_Env env, + const char* code, + const char* msg) { + JSVM_PREAMBLE(env); + + v8::Isolate* isolate = env->isolate; + v8::Local str; + CHECK_NEW_FROM_UTF8(env, str, msg); + + v8::Local error_obj = v8::Exception::SyntaxError(str); + STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); + + isolate->ThrowException(error_obj); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsError(JSVM_Env env, + JSVM_Value value, + bool* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot + // throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsNativeError(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueDouble(JSVM_Env env, + JSVM_Value value, + double* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsNumber(), JSVM_NUMBER_EXPECTED); + + *result = val.As()->Value(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueInt32(JSVM_Env env, + JSVM_Value value, + int32_t* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + if (val->IsInt32()) { + *result = val.As()->Value(); + } else { + RETURN_STATUS_IF_FALSE(env, val->IsNumber(), JSVM_NUMBER_EXPECTED); + + // Empty context: https://github.com/nodejs/node/issues/14379 + v8::Local context; + *result = val->Int32Value(context).FromJust(); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueUint32(JSVM_Env env, + JSVM_Value value, + uint32_t* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + if (val->IsUint32()) { + *result = val.As()->Value(); + } else { + RETURN_STATUS_IF_FALSE(env, val->IsNumber(), JSVM_NUMBER_EXPECTED); + + // Empty context: https://github.com/nodejs/node/issues/14379 + v8::Local context; + *result = val->Uint32Value(context).FromJust(); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueInt64(JSVM_Env env, + JSVM_Value value, + int64_t* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + // This is still a fast path very likely to be taken. + if (val->IsInt32()) { + *result = val.As()->Value(); + return jsvm_clear_last_error(env); + } + + RETURN_STATUS_IF_FALSE(env, val->IsNumber(), JSVM_NUMBER_EXPECTED); + + // v8::Value::IntegerValue() converts NaN, +Inf, and -Inf to INT64_MIN, + // inconsistent with v8::Value::Int32Value() which converts those values to 0. + // Special-case all non-finite values to match that behavior. + double doubleValue = val.As()->Value(); + if (std::isfinite(doubleValue)) { + // Empty context: https://github.com/nodejs/node/issues/14379 + v8::Local context; + *result = val->IntegerValue(context).FromJust(); + } else { + *result = 0; + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueBigintInt64(JSVM_Env env, + JSVM_Value value, + int64_t* result, + bool* lossless) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + CHECK_ARG(env, lossless); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), JSVM_BIGINT_EXPECTED); + + *result = val.As()->Int64Value(lossless); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueBigintUint64(JSVM_Env env, + JSVM_Value value, + uint64_t* result, + bool* lossless) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + CHECK_ARG(env, lossless); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), JSVM_BIGINT_EXPECTED); + + *result = val.As()->Uint64Value(lossless); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueBigintWords(JSVM_Env env, + JSVM_Value value, + int* signBit, + size_t* wordCount, + uint64_t* words) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, wordCount); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), JSVM_BIGINT_EXPECTED); + + v8::Local big = val.As(); + + int word_count_int = *wordCount; + + if (signBit == nullptr && words == nullptr) { + word_count_int = big->WordCount(); + } else { + CHECK_ARG(env, signBit); + CHECK_ARG(env, words); + big->ToWordsArray(signBit, &word_count_int, words); + } + + *wordCount = word_count_int; + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueBool(JSVM_Env env, + JSVM_Value value, + bool* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsBoolean(), JSVM_BOOLEAN_EXPECTED); + + *result = val.As()->Value(); + + return jsvm_clear_last_error(env); +} + +// Copies a JavaScript string into a LATIN-1 string buffer. The result is the +// number of bytes (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in bytes) +// via the result parameter. +// The result argument is optional unless buf is NULL. +JSVM_Status JSVM_CDECL OH_JSVM_GetValueStringLatin1( + JSVM_Env env, JSVM_Value value, char* buf, size_t bufsize, size_t* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsString(), JSVM_STRING_EXPECTED); + + if (!buf) { + CHECK_ARG(env, result); + *result = val.As()->Length(); + } else if (bufsize != 0) { + int copied = + val.As()->WriteOneByte(env->isolate, + reinterpret_cast(buf), + 0, + bufsize - 1, + v8::String::NO_NULL_TERMINATION); + + buf[copied] = '\0'; + if (result != nullptr) { + *result = copied; + } + } else if (result != nullptr) { + *result = 0; + } + + return jsvm_clear_last_error(env); +} + +// Copies a JavaScript string into a UTF-8 string buffer. The result is the +// number of bytes (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in bytes) +// via the result parameter. +// The result argument is optional unless buf is NULL. +JSVM_Status JSVM_CDECL OH_JSVM_GetValueStringUtf8( + JSVM_Env env, JSVM_Value value, char* buf, size_t bufsize, size_t* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsString(), JSVM_STRING_EXPECTED); + + if (!buf) { + CHECK_ARG(env, result); + *result = val.As()->Utf8Length(env->isolate); + } else if (bufsize != 0) { + int copied = val.As()->WriteUtf8( + env->isolate, + buf, + bufsize - 1, + nullptr, + v8::String::REPLACE_INVALID_UTF8 | v8::String::NO_NULL_TERMINATION); + + buf[copied] = '\0'; + if (result != nullptr) { + *result = copied; + } + } else if (result != nullptr) { + *result = 0; + } + + return jsvm_clear_last_error(env); +} + +// Copies a JavaScript string into a UTF-16 string buffer. The result is the +// number of 2-byte code units (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in 2-byte +// code units) via the result parameter. +// The result argument is optional unless buf is NULL. +JSVM_Status JSVM_CDECL OH_JSVM_GetValueStringUtf16(JSVM_Env env, + JSVM_Value value, + char16_t* buf, + size_t bufsize, + size_t* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsString(), JSVM_STRING_EXPECTED); + + if (!buf) { + CHECK_ARG(env, result); + // V8 assumes UTF-16 length is the same as the number of characters. + *result = val.As()->Length(); + } else if (bufsize != 0) { + int copied = val.As()->Write(env->isolate, + reinterpret_cast(buf), + 0, + bufsize - 1, + v8::String::NO_NULL_TERMINATION); + + buf[copied] = '\0'; + if (result != nullptr) { + *result = copied; + } + } else if (result != nullptr) { + *result = 0; + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CoerceToBool(JSVM_Env env, + JSVM_Value value, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + v8::Local b = + v8impl::V8LocalValueFromJsValue(value)->ToBoolean(isolate); + *result = v8impl::JsValueFromV8LocalValue(b); + return GET_RETURN_STATUS(env); +} + +#define GEN_COERCE_FUNCTION(UpperCaseName, MixedCaseName, LowerCaseName) \ + JSVM_Status JSVM_CDECL OH_JSVM_CoerceTo##MixedCaseName( \ + JSVM_Env env, JSVM_Value value, JSVM_Value* result) { \ + JSVM_PREAMBLE(env); \ + CHECK_ARG(env, value); \ + CHECK_ARG(env, result); \ + \ + v8::Local context = env->context(); \ + v8::Local str; \ + \ + CHECK_TO_##UpperCaseName(env, context, str, value); \ + \ + *result = v8impl::JsValueFromV8LocalValue(str); \ + return GET_RETURN_STATUS(env); \ + } + +GEN_COERCE_FUNCTION(NUMBER, Number, number) +GEN_COERCE_FUNCTION(OBJECT, Object, object) +GEN_COERCE_FUNCTION(STRING, String, string) +GEN_COERCE_FUNCTION(BIGINT, BigInt, bigint) + +#undef GEN_COERCE_FUNCTION + +JSVM_Status JSVM_CDECL OH_JSVM_Wrap(JSVM_Env env, + JSVM_Value jsObject, + void* nativeObject, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Ref* result) { + return v8impl::Wrap( + env, jsObject, nativeObject, finalizeCb, finalizeHint, result); +} + +JSVM_Status JSVM_CDECL OH_JSVM_Unwrap(JSVM_Env env, + JSVM_Value obj, + void** result) { + return v8impl::Unwrap(env, obj, result, v8impl::KeepWrap); +} + +JSVM_Status JSVM_CDECL OH_JSVM_RemoveWrap(JSVM_Env env, + JSVM_Value obj, + void** result) { + return v8impl::Unwrap(env, obj, result, v8impl::RemoveWrap); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateExternal(JSVM_Env env, + void* data, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + + v8::Local external_value = v8::External::New(isolate, data); + + if (finalizeCb) { + // The Reference object will delete itself after invoking the finalizer + // callback. + v8impl::Reference::New(env, + external_value, + 0, + v8impl::Ownership::kRuntime, + finalizeCb, + data, + finalizeHint); + } + + *result = v8impl::JsValueFromV8LocalValue(external_value); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_TypeTagObject(JSVM_Env env, + JSVM_Value object, + const JSVM_TypeTag* typeTag) { + JSVM_PREAMBLE(env); + v8::Local context = env->context(); + v8::Local obj; + CHECK_TO_OBJECT_WITH_PREAMBLE(env, context, obj, object); + CHECK_ARG_WITH_PREAMBLE(env, typeTag); + + auto key = JSVM_PRIVATE_KEY(env->isolate, type_tag); + auto maybe_has = obj->HasPrivate(context, key); + CHECK_MAYBE_NOTHING_WITH_PREAMBLE(env, maybe_has, JSVM_GENERIC_FAILURE); + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE( + env, !maybe_has.FromJust(), JSVM_INVALID_ARG); + + auto tag = v8::BigInt::NewFromWords( + context, 0, 2, reinterpret_cast(typeTag)); + CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, tag, JSVM_GENERIC_FAILURE); + + auto maybe_set = obj->SetPrivate(context, key, tag.ToLocalChecked()); + CHECK_MAYBE_NOTHING_WITH_PREAMBLE(env, maybe_set, JSVM_GENERIC_FAILURE); + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE( + env, maybe_set.FromJust(), JSVM_GENERIC_FAILURE); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CheckObjectTypeTag(JSVM_Env env, + JSVM_Value object, + const JSVM_TypeTag* typeTag, + bool* result) { + JSVM_PREAMBLE(env); + v8::Local context = env->context(); + v8::Local obj; + CHECK_TO_OBJECT_WITH_PREAMBLE(env, context, obj, object); + CHECK_ARG_WITH_PREAMBLE(env, typeTag); + CHECK_ARG_WITH_PREAMBLE(env, result); + + auto maybe_value = + obj->GetPrivate(context, JSVM_PRIVATE_KEY(env->isolate, type_tag)); + CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe_value, JSVM_GENERIC_FAILURE); + v8::Local val = maybe_value.ToLocalChecked(); + + // We consider the type check to have failed unless we reach the line below + // where we set whether the type check succeeded or not based on the + // comparison of the two type tags. + *result = false; + if (val->IsBigInt()) { + int sign; + int size = 2; + JSVM_TypeTag tag; + val.As()->ToWordsArray( + &sign, &size, reinterpret_cast(&tag)); + if (sign == 0) { + if (size == 2) { + *result = + (tag.lower == typeTag->lower && tag.upper == typeTag->upper); + } else if (size == 1) { + *result = (tag.lower == typeTag->lower && 0 == typeTag->upper); + } else if (size == 0) { + *result = (0 == typeTag->lower && 0 == typeTag->upper); + } + } + } + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetValueExternal(JSVM_Env env, + JSVM_Value value, + void** result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsExternal(), JSVM_INVALID_ARG); + + v8::Local external_value = val.As(); + *result = external_value->Value(); + + return jsvm_clear_last_error(env); +} + +// Set initialRefcount to 0 for a weak reference, >0 for a strong reference. +JSVM_Status JSVM_CDECL OH_JSVM_CreateReference(JSVM_Env env, + JSVM_Value value, + uint32_t initialRefcount, + JSVM_Ref* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local v8_value = v8impl::V8LocalValueFromJsValue(value); + v8impl::Reference* reference = v8impl::Reference::New( + env, v8_value, initialRefcount, v8impl::Ownership::kUserland); + + *result = reinterpret_cast(reference); + return jsvm_clear_last_error(env); +} + +// Deletes a reference. The referenced value is released, and may be GC'd unless +// there are other references to it. +JSVM_Status JSVM_CDECL OH_JSVM_DeleteReference(JSVM_Env env, JSVM_Ref ref) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, ref); + + reinterpret_cast(ref)->Delete(); + + return jsvm_clear_last_error(env); +} + +// Increments the reference count, optionally returning the resulting count. +// After this call the reference will be a strong reference because its +// refcount is >0, and the referenced object is effectively "pinned". +// Calling this when the refcount is 0 and the object is unavailable +// results in an error. +JSVM_Status JSVM_CDECL OH_JSVM_ReferenceRef(JSVM_Env env, + JSVM_Ref ref, + uint32_t* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, ref); + + v8impl::Reference* reference = reinterpret_cast(ref); + if (reference->HasDeletedByUser()) { + return jsvm_set_last_error(env, JSVM_GENERIC_FAILURE); + } + uint32_t count = reference->Ref(); + + if (result != nullptr) { + *result = count; + } + + return jsvm_clear_last_error(env); +} + +// Decrements the reference count, optionally returning the resulting count. If +// the result is 0 the reference is now weak and the object may be GC'd at any +// time if there are no other references. Calling this when the refcount is +// already 0 results in an error. +JSVM_Status JSVM_CDECL OH_JSVM_ReferenceUnref(JSVM_Env env, + JSVM_Ref ref, + uint32_t* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, ref); + + v8impl::Reference* reference = reinterpret_cast(ref); + + if (reference->RefCount() == 0 || reference->HasDeletedByUser()) { + return jsvm_set_last_error(env, JSVM_GENERIC_FAILURE); + } + + uint32_t count = reference->Unref(); + + if (result != nullptr) { + *result = count; + } + + return jsvm_clear_last_error(env); +} + +// Attempts to get a referenced value. If the reference is weak, the value might +// no longer be available, in that case the call is still successful but the +// result is NULL. +JSVM_Status JSVM_CDECL OH_JSVM_GetReferenceValue(JSVM_Env env, + JSVM_Ref ref, + JSVM_Value* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, ref); + CHECK_ARG(env, result); + + v8impl::Reference* reference = reinterpret_cast(ref); + *result = v8impl::JsValueFromV8LocalValue(reference->Get()); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_OpenHandleScope(JSVM_Env env, + JSVM_HandleScope* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsHandleScopeFromV8HandleScope( + new v8impl::HandleScopeWrapper(env->isolate)); + env->open_handle_scopes++; + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CloseHandleScope(JSVM_Env env, + JSVM_HandleScope scope) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, scope); + if (env->open_handle_scopes == 0) { + return JSVM_HANDLE_SCOPE_MISMATCH; + } + + env->ReleaseJsvmData(); + env->open_handle_scopes--; + delete v8impl::V8HandleScopeFromJsHandleScope(scope); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_OpenEscapableHandleScope( + JSVM_Env env, JSVM_EscapableHandleScope* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsEscapableHandleScopeFromV8EscapableHandleScope( + new v8impl::EscapableHandleScopeWrapper(env->isolate)); + env->open_handle_scopes++; + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CloseEscapableHandleScope( + JSVM_Env env, JSVM_EscapableHandleScope scope) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, scope); + if (env->open_handle_scopes == 0) { + return JSVM_HANDLE_SCOPE_MISMATCH; + } + + delete v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope(scope); + env->open_handle_scopes--; + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_EscapeHandle(JSVM_Env env, + JSVM_EscapableHandleScope scope, + JSVM_Value escapee, + JSVM_Value* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, scope); + CHECK_ARG(env, escapee); + CHECK_ARG(env, result); + + v8impl::EscapableHandleScopeWrapper* s = + v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope(scope); + if (!s->escape_called()) { + *result = v8impl::JsValueFromV8LocalValue( + s->Escape(v8impl::V8LocalValueFromJsValue(escapee))); + return jsvm_clear_last_error(env); + } + return jsvm_set_last_error(env, JSVM_ESCAPE_CALLED_TWICE); +} + +JSVM_Status JSVM_CDECL OH_JSVM_NewInstance(JSVM_Env env, + JSVM_Value constructor, + size_t argc, + const JSVM_Value* argv, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, constructor); + if (argc > 0) { + CHECK_ARG(env, argv); + } + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + v8::Local ctor; + CHECK_TO_FUNCTION(env, ctor, constructor); + + auto maybe = ctor->NewInstance( + context, + argc, + reinterpret_cast*>(const_cast(argv))); + + CHECK_MAYBE_EMPTY(env, maybe, JSVM_PENDING_EXCEPTION); + + *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_Instanceof(JSVM_Env env, + JSVM_Value object, + JSVM_Value constructor, + bool* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, object); + CHECK_ARG(env, result); + + *result = false; + + v8::Local ctor; + v8::Local context = env->context(); + + CHECK_TO_OBJECT(env, context, ctor, constructor); + + if (!ctor->IsFunction()) { + OH_JSVM_ThrowTypeError( + env, "ERR_NAPI_CONS_FUNCTION", "Constructor must be a function"); + + return jsvm_set_last_error(env, JSVM_FUNCTION_EXPECTED); + } + + JSVM_Status status = JSVM_GENERIC_FAILURE; + + v8::Local val = v8impl::V8LocalValueFromJsValue(object); + auto maybe_result = val->InstanceOf(context, ctor); + CHECK_MAYBE_NOTHING(env, maybe_result, status); + *result = maybe_result.FromJust(); + return GET_RETURN_STATUS(env); +} + +// Methods to support catching exceptions +JSVM_Status JSVM_CDECL OH_JSVM_IsExceptionPending(JSVM_Env env, bool* result) { + // JSVM_PREAMBLE is not used here: this function must execute when there is a + // pending exception. + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = !env->last_exception.IsEmpty(); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetAndClearLastException(JSVM_Env env, + JSVM_Value* result) { + // JSVM_PREAMBLE is not used here: this function must execute when there is a + // pending exception. + CHECK_ENV(env); + CHECK_ARG(env, result); + + if (env->last_exception.IsEmpty()) { + return OH_JSVM_GetUndefined(env, result); + } else { + *result = v8impl::JsValueFromV8LocalValue( + v8::Local::New(env->isolate, env->last_exception)); + env->last_exception.Reset(); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsArraybuffer(JSVM_Env env, + JSVM_Value value, + bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsArrayBuffer(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateArraybuffer(JSVM_Env env, + size_t byteLength, + void** data, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + v8::Local buffer = + v8::ArrayBuffer::New(isolate, byteLength); + + // Optionally return a pointer to the buffer's data, to avoid another call to + // retrieve it. + if (data != nullptr) { + *data = buffer->Data(); + } + + *result = v8impl::JsValueFromV8LocalValue(buffer); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_AllocateArrayBufferBackingStoreData(size_t byteLength, + JSVM_InitializedFlag initialized, + void **data) { + if (!data) { + return JSVM_INVALID_ARG; + } + auto allocator = v8impl::GetOrCreateDefaultArrayBufferAllocator(); + *data = (initialized == JSVM_ZERO_INITIALIZED) ? + allocator->Allocate(byteLength) : + allocator->AllocateUninitialized(byteLength); + return *data ? JSVM_OK : JSVM_GENERIC_FAILURE; +} + +JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void *data) { + if (!data) { + return JSVM_INVALID_ARG; + } + auto allocator = v8impl::GetOrCreateDefaultArrayBufferAllocator(); + allocator->Free(data, JSVM_AUTO_LENGTH); + return JSVM_OK; +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateArrayBufferFromBackingStoreData(JSVM_Env env, + void *data, + size_t byteLength, + size_t offset, + size_t slicedByteLength, + JSVM_Value *result) { + CHECK_ENV(env); + JSVM_PREAMBLE(env); + CHECK_ARG(env, data); + CHECK_ARG(env, result); + CHECK_ARG_NOT_ZERO(env, byteLength); + CHECK_ARG_NOT_ZERO(env, slicedByteLength); + void *dataPtr = static_cast(data) + offset; + auto backingStoreSize = slicedByteLength; + RETURN_STATUS_IF_FALSE(env, offset + slicedByteLength <= byteLength, JSVM_INVALID_ARG); + auto backingStore = v8::ArrayBuffer::NewBackingStore( + dataPtr, backingStoreSize, v8::BackingStore::EmptyDeleter, nullptr); + v8::Local arrayBuffer = + v8::ArrayBuffer::New(env->isolate, std::move(backingStore)); + *result = v8impl::JsValueFromV8LocalValue(arrayBuffer); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateExternal_buffer(JSVM_Env env, + size_t length, + void* data, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + +#if defined(V8_ENABLE_SANDBOX) + return jsvm_set_last_error(env, JSVM_NO_EXTERNAL_BUFFERS_ALLOWED); +#endif + + v8::Isolate* isolate = env->isolate; + + // The finalizer object will delete itself after invoking the callback. + v8impl::BufferFinalizer* finalizer = + v8impl::BufferFinalizer::New(env, finalizeCb, nullptr, finalizeHint); + + std::shared_ptr backingStore = v8::ArrayBuffer::NewBackingStore(data, length, [](void* data, size_t length, + void* deleter_data) { + v8impl::BufferFinalizer::FinalizeBufferCallback(static_cast(data), deleter_data); + }, finalizer); + v8::Local ab = v8::ArrayBuffer::New(isolate, backingStore); + +//cjh v8::MaybeLocal maybe = +// node::Buffer::New(isolate, +// static_cast(data), +// length, +// v8impl::BufferFinalizer::FinalizeBufferCallback, +// finalizer); +// +// CHECK_MAYBE_EMPTY(env, maybe, JSVM_GENERIC_FAILURE); + + *result = v8impl::JsValueFromV8LocalValue(ab);//cjh maybe.ToLocalChecked()); + return GET_RETURN_STATUS(env); + // Tell coverity that 'finalizer' should not be freed when we return + // as it will be deleted when the buffer to which it is associated + // is finalized. + // coverity[leaked_storage] +} + +JSVM_Status JSVM_CDECL +OH_JSVM_CreateExternalArraybuffer(JSVM_Env env, + void* externalData, + size_t byteLength, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Value* result) { + // The API contract here is that the cleanup function runs on the JS thread, + // and is able to use JSVM_Env. Implementing that properly is hard, so use the + // `Buffer` variant for easier implementation. + JSVM_Value buffer; + STATUS_CALL(OH_JSVM_CreateExternal_buffer( + env, byteLength, externalData, finalizeCb, finalizeHint, &buffer)); + return OH_JSVM_GetTypedarrayInfo( + env, buffer, nullptr, nullptr, nullptr, result, nullptr); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetArraybufferInfo(JSVM_Env env, + JSVM_Value arraybuffer, + void** data, + size_t* byteLength) { + CHECK_ENV(env); + CHECK_ARG(env, arraybuffer); + + v8::Local value = v8impl::V8LocalValueFromJsValue(arraybuffer); + RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), JSVM_INVALID_ARG); + + v8::Local ab = value.As(); + + if (data != nullptr) { + *data = ab->Data(); + } + + if (byteLength != nullptr) { + *byteLength = ab->ByteLength(); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsTypedarray(JSVM_Env env, + JSVM_Value value, + bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsTypedArray(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateTypedarray(JSVM_Env env, + JSVM_TypedarrayType type, + size_t length, + JSVM_Value arraybuffer, + size_t byteOffset, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, arraybuffer); + CHECK_ARG(env, result); + + v8::Local value = v8impl::V8LocalValueFromJsValue(arraybuffer); + RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), JSVM_INVALID_ARG); + + v8::Local buffer = value.As(); + v8::Local typedArray; + + switch (type) { + case JSVM_INT8_ARRAY: + CREATE_TYPED_ARRAY( + env, Int8Array, 1, buffer, byteOffset, length, typedArray); + break; + case JSVM_UINT8_ARRAY: + CREATE_TYPED_ARRAY( + env, Uint8Array, 1, buffer, byteOffset, length, typedArray); + break; + case JSVM_UINT8_CLAMPED_ARRAY: + CREATE_TYPED_ARRAY( + env, Uint8ClampedArray, 1, buffer, byteOffset, length, typedArray); + break; + case JSVM_INT16_ARRAY: + CREATE_TYPED_ARRAY( + env, Int16Array, 2, buffer, byteOffset, length, typedArray); + break; + case JSVM_UINT16_ARRAY: + CREATE_TYPED_ARRAY( + env, Uint16Array, 2, buffer, byteOffset, length, typedArray); + break; + case JSVM_INT32_ARRAY: + CREATE_TYPED_ARRAY( + env, Int32Array, 4, buffer, byteOffset, length, typedArray); + break; + case JSVM_UINT32_ARRAY: + CREATE_TYPED_ARRAY( + env, Uint32Array, 4, buffer, byteOffset, length, typedArray); + break; + case JSVM_FLOAT32_ARRAY: + CREATE_TYPED_ARRAY( + env, Float32Array, 4, buffer, byteOffset, length, typedArray); + break; + case JSVM_FLOAT64_ARRAY: + CREATE_TYPED_ARRAY( + env, Float64Array, 8, buffer, byteOffset, length, typedArray); + break; + case JSVM_BIGINT64_ARRAY: + CREATE_TYPED_ARRAY( + env, BigInt64Array, 8, buffer, byteOffset, length, typedArray); + break; + case JSVM_BIGUINT64_ARRAY: + CREATE_TYPED_ARRAY( + env, BigUint64Array, 8, buffer, byteOffset, length, typedArray); + break; + default: + return jsvm_set_last_error(env, JSVM_INVALID_ARG); + } + + *result = v8impl::JsValueFromV8LocalValue(typedArray); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetTypedarrayInfo(JSVM_Env env, + JSVM_Value typedarray, + JSVM_TypedarrayType* type, + size_t* length, + void** data, + JSVM_Value* arraybuffer, + size_t* byteOffset) { + CHECK_ENV(env); + CHECK_ARG(env, typedarray); + + v8::Local value = v8impl::V8LocalValueFromJsValue(typedarray); + RETURN_STATUS_IF_FALSE(env, value->IsTypedArray(), JSVM_INVALID_ARG); + + v8::Local array = value.As(); + + if (type != nullptr) { + if (value->IsInt8Array()) { + *type = JSVM_INT8_ARRAY; + } else if (value->IsUint8Array()) { + *type = JSVM_UINT8_ARRAY; + } else if (value->IsUint8ClampedArray()) { + *type = JSVM_UINT8_CLAMPED_ARRAY; + } else if (value->IsInt16Array()) { + *type = JSVM_INT16_ARRAY; + } else if (value->IsUint16Array()) { + *type = JSVM_UINT16_ARRAY; + } else if (value->IsInt32Array()) { + *type = JSVM_INT32_ARRAY; + } else if (value->IsUint32Array()) { + *type = JSVM_UINT32_ARRAY; + } else if (value->IsFloat32Array()) { + *type = JSVM_FLOAT32_ARRAY; + } else if (value->IsFloat64Array()) { + *type = JSVM_FLOAT64_ARRAY; + } else if (value->IsBigInt64Array()) { + *type = JSVM_BIGINT64_ARRAY; + } else if (value->IsBigUint64Array()) { + *type = JSVM_BIGUINT64_ARRAY; + } + } + + if (length != nullptr) { + *length = array->Length(); + } + + v8::Local buffer; + if (data != nullptr || arraybuffer != nullptr) { + // Calling Buffer() may have the side effect of allocating the buffer, + // so only do this when it’s needed. + buffer = array->Buffer(); + } + + if (data != nullptr) { + *data = static_cast(buffer->Data()) + array->ByteOffset(); + } + + if (arraybuffer != nullptr) { + *arraybuffer = v8impl::JsValueFromV8LocalValue(buffer); + } + + if (byteOffset != nullptr) { + *byteOffset = array->ByteOffset(); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateDataview(JSVM_Env env, + size_t byteLength, + JSVM_Value arraybuffer, + size_t byteOffset, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, arraybuffer); + CHECK_ARG(env, result); + + v8::Local value = v8impl::V8LocalValueFromJsValue(arraybuffer); + RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), JSVM_INVALID_ARG); + + v8::Local buffer = value.As(); + if (byteLength + byteOffset > buffer->ByteLength()) { + OH_JSVM_ThrowRangeError(env, + "ERR_JSVM_INVALID_DATAVIEW_ARGS", + "byteOffset + byteLength should be less than or " + "equal to the size in bytes of the array passed in"); + return jsvm_set_last_error(env, JSVM_PENDING_EXCEPTION); + } + v8::Local DataView = + v8::DataView::New(buffer, byteOffset, byteLength); + + *result = v8impl::JsValueFromV8LocalValue(DataView); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsDataview(JSVM_Env env, + JSVM_Value value, + bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsDataView(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetDataviewInfo(JSVM_Env env, + JSVM_Value dataview, + size_t* byteLength, + void** data, + JSVM_Value* arraybuffer, + size_t* byteOffset) { + CHECK_ENV(env); + CHECK_ARG(env, dataview); + + v8::Local value = v8impl::V8LocalValueFromJsValue(dataview); + RETURN_STATUS_IF_FALSE(env, value->IsDataView(), JSVM_INVALID_ARG); + + v8::Local array = value.As(); + + if (byteLength != nullptr) { + *byteLength = array->ByteLength(); + } + + v8::Local buffer; + if (data != nullptr || arraybuffer != nullptr) { + // Calling Buffer() may have the side effect of allocating the buffer, + // so only do this when it’s needed. + buffer = array->Buffer(); + } + + if (data != nullptr) { + *data = static_cast(buffer->Data()) + array->ByteOffset(); + } + + if (arraybuffer != nullptr) { + *arraybuffer = v8impl::JsValueFromV8LocalValue(buffer); + } + + if (byteOffset != nullptr) { + *byteOffset = array->ByteOffset(); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetVersion(JSVM_Env env, uint32_t* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + *result = NAPI_VERSION; + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreatePromise(JSVM_Env env, + JSVM_Deferred* deferred, + JSVM_Value* promise) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, deferred); + CHECK_ARG(env, promise); + + auto maybe = v8::Promise::Resolver::New(env->context()); + CHECK_MAYBE_EMPTY(env, maybe, JSVM_GENERIC_FAILURE); + + auto v8_resolver = maybe.ToLocalChecked(); + auto v8_deferred = new v8impl::Persistent(); + v8_deferred->Reset(env->isolate, v8_resolver); + + *deferred = v8impl::JsDeferredFromNodePersistent(v8_deferred); + *promise = v8impl::JsValueFromV8LocalValue(v8_resolver->GetPromise()); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ResolveDeferred(JSVM_Env env, + JSVM_Deferred deferred, + JSVM_Value resolution) { + return v8impl::ConcludeDeferred(env, deferred, resolution, true); +} + +JSVM_Status JSVM_CDECL OH_JSVM_RejectDeferred(JSVM_Env env, + JSVM_Deferred deferred, + JSVM_Value resolution) { + return v8impl::ConcludeDeferred(env, deferred, resolution, false); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsPromise(JSVM_Env env, + JSVM_Value value, + bool* is_promise) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, is_promise); + + *is_promise = v8impl::V8LocalValueFromJsValue(value)->IsPromise(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateDate(JSVM_Env env, + double time, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::MaybeLocal maybe_date = v8::Date::New(env->context(), time); + CHECK_MAYBE_EMPTY(env, maybe_date, JSVM_GENERIC_FAILURE); + + *result = v8impl::JsValueFromV8LocalValue(maybe_date.ToLocalChecked()); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsDate(JSVM_Env env, + JSVM_Value value, + bool* isDate) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isDate); + + *isDate = v8impl::V8LocalValueFromJsValue(value)->IsDate(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetDateValue(JSVM_Env env, + JSVM_Value value, + double* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsDate(), JSVM_DATE_EXPECTED); + + v8::Local date = val.As(); + *result = date->ValueOf(); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_AddFinalizer(JSVM_Env env, + JSVM_Value jsObject, + void* finalizeData, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Ref* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, jsObject); + CHECK_ARG(env, finalizeCb); + + v8::Local v8_value = v8impl::V8LocalValueFromJsValue(jsObject); + RETURN_STATUS_IF_FALSE(env, v8_value->IsObject(), JSVM_INVALID_ARG); + + // Create a self-deleting reference if the optional out-param result is not + // set. + v8impl::Ownership ownership = result == nullptr + ? v8impl::Ownership::kRuntime + : v8impl::Ownership::kUserland; + v8impl::Reference* reference = v8impl::Reference::New( + env, v8_value, 0, ownership, finalizeCb, finalizeData, finalizeHint); + + if (result != nullptr) { + *result = reinterpret_cast(reference); + } + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_AdjustExternalMemory(JSVM_Env env, + int64_t changeInBytes, + int64_t* adjustedValue) { + CHECK_ENV(env); + CHECK_ARG(env, adjustedValue); + + *adjustedValue = + env->isolate->AdjustAmountOfExternalAllocatedMemory(changeInBytes); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_SetInstanceData(JSVM_Env env, + void* data, + JSVM_Finalize finalizeCb, + void* finalizeHint) { + CHECK_ENV(env); + + v8impl::RefBase* old_data = static_cast(env->instance_data); + if (old_data != nullptr) { + // Our contract so far has been to not finalize any old data there may be. + // So we simply delete it. + delete old_data; + } + + env->instance_data = v8impl::RefBase::New( + env, 0, v8impl::Ownership::kRuntime, finalizeCb, data, finalizeHint); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_GetInstanceData(JSVM_Env env, void** data) { + CHECK_ENV(env); + CHECK_ARG(env, data); + + v8impl::RefBase* idata = static_cast(env->instance_data); + + *data = (idata == nullptr ? nullptr : idata->Data()); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_DetachArraybuffer(JSVM_Env env, + JSVM_Value arraybuffer) { + CHECK_ENV(env); + CHECK_ARG(env, arraybuffer); + + v8::Local value = v8impl::V8LocalValueFromJsValue(arraybuffer); + RETURN_STATUS_IF_FALSE( + env, value->IsArrayBuffer() || value->IsSharedArrayBuffer(), JSVM_ARRAYBUFFER_EXPECTED); + + v8::Local it = value.As(); + RETURN_STATUS_IF_FALSE( + env, it->IsDetachable(), JSVM_DETACHABLE_ARRAYBUFFER_EXPECTED); + + it->Detach(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsDetachedArraybuffer(JSVM_Env env, + JSVM_Value arraybuffer, + bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, arraybuffer); + CHECK_ARG(env, result); + + v8::Local value = v8impl::V8LocalValueFromJsValue(arraybuffer); + + *result = + value->IsArrayBuffer() && value.As()->WasDetached(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL +OH_JSVM_DefineClassWithPropertyHandler(JSVM_Env env, + const char* utf8name, + size_t length, + JSVM_Callback constructor, + size_t propertyCount, + const JSVM_PropertyDescriptor* properties, + JSVM_PropertyHandlerCfg propertyHandlerCfg, + JSVM_Callback callAsFunctionCallback, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + CHECK_ARG(env, constructor); + CHECK_ARG(env, constructor->callback); + CHECK_ARG(env, propertyHandlerCfg); + + if (propertyCount > 0) { + CHECK_ARG(env, properties); + } + + v8::Isolate* isolate = env->isolate; + v8::EscapableHandleScope scope(isolate); + v8::Local tpl; + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, constructor, &tpl)); + + v8::Local name_string; + CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); + tpl->SetClassName(name_string); + + size_t static_property_count = 0; + for (size_t i = 0; i < propertyCount; i++) { + const JSVM_PropertyDescriptor* p = properties + i; + + if ((p->attributes & JSVM_STATIC) != 0) { // attributes + // Static properties are handled separately below. + static_property_count++; + continue; + } + + v8::Local property_name; + STATUS_CALL(v8impl::V8NameFromPropertyDescriptor(env, p, &property_name)); + v8::PropertyAttribute attributes = v8impl::V8PropertyAttributesFromDescriptor(p); + + // This code is similar to that in OH_JSVM_DefineProperties(); the + // difference is it applies to a template instead of an object, + // and preferred PropertyAttribute for lack of PropertyDescriptor + // support on ObjectTemplate. + if (p->getter != nullptr || p->setter != nullptr) { + v8::Local getter_tpl; + v8::Local setter_tpl; + if (p->getter != nullptr) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->getter, &getter_tpl)); + } + if (p->setter != nullptr) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->setter, &setter_tpl)); + } + + tpl->PrototypeTemplate()->SetAccessorProperty(property_name, + getter_tpl, + setter_tpl, + attributes, + v8::AccessControl::DEFAULT); + } else if (p->method != nullptr) { + v8::Local t; + if (p->attributes & JSVM_NO_RECEIVER_CHECK) { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->method, &t)); + } else { + STATUS_CALL(v8impl::FunctionCallbackWrapper::NewTemplate( + env, p->method, &t, v8::Signature::New(isolate, tpl))); + } + + tpl->PrototypeTemplate()->Set(property_name, t, attributes); + } else { + v8::Local value = v8impl::V8LocalValueFromJsValue(p->value); + tpl->PrototypeTemplate()->Set(property_name, value, attributes); + } + } + + /* register property handler for instance object */ + v8impl::JSVM_PropertyHandlerCfgStruct* propertyHandleCfg = v8impl::CreatePropertyCfg(env, propertyHandlerCfg); + if (propertyHandleCfg == nullptr) { + return JSVM_Status::JSVM_GENERIC_FAILURE; + } + v8::Local cbdata = v8impl::CallbackBundle::New(env, propertyHandleCfg); + + // register named property handler + v8::NamedPropertyHandlerConfiguration namedPropertyHandler; + if (propertyHandlerCfg->genericNamedPropertyGetterCallback) { + namedPropertyHandler.getter = v8impl::PropertyCallbackWrapper::NameGetterInvoke; + } + if (propertyHandlerCfg->genericNamedPropertySetterCallback) { + namedPropertyHandler.setter = v8impl::PropertyCallbackWrapper::NameSetterInvoke; + } + if (propertyHandlerCfg->genericNamedPropertyDeleterCallback) { + namedPropertyHandler.deleter = v8impl::PropertyCallbackWrapper::NameDeleterInvoke; + } + if (propertyHandlerCfg->genericNamedPropertyEnumeratorCallback) { + namedPropertyHandler.enumerator = v8impl::PropertyCallbackWrapper::NameEnumeratorInvoke; + } + namedPropertyHandler.data = cbdata; + tpl->InstanceTemplate()->SetHandler(namedPropertyHandler); + + // register indexed property handle + v8::IndexedPropertyHandlerConfiguration indexPropertyHandler; + if (propertyHandlerCfg->genericIndexedPropertyGetterCallback) { + indexPropertyHandler.getter = v8impl::PropertyCallbackWrapper::IndexGetterInvoke; + } + if (propertyHandlerCfg->genericIndexedPropertySetterCallback) { + indexPropertyHandler.setter = v8impl::PropertyCallbackWrapper::IndexSetterInvoke; + } + if (propertyHandlerCfg->genericIndexedPropertyDeleterCallback) { + indexPropertyHandler.deleter = v8impl::PropertyCallbackWrapper::IndexDeleterInvoke; + } + if (propertyHandlerCfg->genericIndexedPropertyEnumeratorCallback) { + indexPropertyHandler.enumerator = v8impl::PropertyCallbackWrapper::IndexEnumeratorInvoke; + } + indexPropertyHandler.data = cbdata; + tpl->InstanceTemplate()->SetHandler(indexPropertyHandler); + + // register call as function + if (callAsFunctionCallback && callAsFunctionCallback->callback) { + v8::Local funcCbdata = v8impl::CallbackBundle::New(env, callAsFunctionCallback); + tpl->InstanceTemplate()->SetCallAsFunctionHandler(v8impl::FunctionCallbackWrapper::Invoke, funcCbdata); + } + + v8::Local context = env->context(); + *result = v8impl::JsValueFromV8LocalValue( + scope.Escape(tpl->GetFunction(context).ToLocalChecked())); + + v8impl::Reference::New(env, v8impl::V8LocalValueFromJsValue(*result), 0, v8impl::Ownership::kRuntime, + v8impl::CfgFinalizedCallback, propertyHandleCfg, nullptr); + + if (static_property_count > 0) { + std::vector static_descriptors; + static_descriptors.reserve(static_property_count); + + for (size_t i = 0; i < propertyCount; i++) { + const JSVM_PropertyDescriptor* p = properties + i; + if ((p->attributes & JSVM_STATIC) != 0) { + static_descriptors.push_back(*p); + } + } + + STATUS_CALL(OH_JSVM_DefineProperties( + env, *result, static_descriptors.size(), static_descriptors.data())); + } + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsLocked(JSVM_Env env, + bool* isLocked) { + CHECK_ENV(env); + CHECK_ARG(env, isLocked); + + *isLocked = v8::Locker::IsLocked(env->isolate); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_AcquireLock(JSVM_Env env) { + CHECK_ENV(env); + + bool isLocked = v8::Locker::IsLocked(env->isolate); + if (!isLocked) { + env->locker = new v8::Locker(env->isolate); + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ReleaseLock(JSVM_Env env) { + CHECK_ENV(env); + + bool isLocked = v8::Locker::IsLocked(env->isolate); + if (isLocked && env->locker != nullptr) { + delete env->locker; + env->locker = nullptr; + } + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsCallable(JSVM_Env env, + JSVM_Value value, + bool* isCallable) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isCallable); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + *isCallable = val->IsFunction(); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsUndefined(JSVM_Env env, + JSVM_Value value, + bool* isUndefined) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isUndefined); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isUndefined = val->IsUndefined(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsNull(JSVM_Env env, + JSVM_Value value, + bool* isNull) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isNull); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isNull = val->IsNull(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsNullOrUndefined(JSVM_Env env, + JSVM_Value value, + bool* isNullOrUndefined) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isNullOrUndefined); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isNullOrUndefined = val->IsNullOrUndefined(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsBoolean(JSVM_Env env, + JSVM_Value value, + bool* isBoolean) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isBoolean); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isBoolean = val->IsBoolean(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsNumber(JSVM_Env env, + JSVM_Value value, + bool* isNumber) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isNumber); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isNumber = val->IsNumber(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsString(JSVM_Env env, + JSVM_Value value, + bool* isString) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isString); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isString = val->IsString(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsSymbol(JSVM_Env env, + JSVM_Value value, + bool* isSymbol) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isSymbol); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isSymbol = val->IsSymbol(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsFunction(JSVM_Env env, + JSVM_Value value, + bool* isFunction) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isFunction); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isFunction = val->IsFunction(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsObject(JSVM_Env env, + JSVM_Value value, + bool* isObject) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isObject); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isObject = val->IsObject(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsBigInt(JSVM_Env env, + JSVM_Value value, + bool* isBigInt) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isBigInt); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isBigInt = val->IsBigInt(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsConstructor(JSVM_Env env, + JSVM_Value value, + bool* isConstructor) +{ + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isConstructor); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + if (!val->IsObject()) { + *isConstructor = false; + return jsvm_clear_last_error(env); + } + v8::Local obj = val.As(); + *isConstructor = obj->IsConstructor(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateRegExp(JSVM_Env env, + JSVM_Value value, + JSVM_RegExpFlags flags, + JSVM_Value* result) +{ + JSVM_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local pattern = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, pattern->IsString(), JSVM_STRING_EXPECTED); + v8::Local context = env->context(); + v8::MaybeLocal regExp = v8::RegExp::New(context, pattern.As(), + static_cast(flags)); + CHECK_MAYBE_EMPTY(env, regExp, JSVM_GENERIC_FAILURE); + *result = v8impl::JsValueFromV8LocalValue(regExp.ToLocalChecked()); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateMap(JSVM_Env env, JSVM_Value* result) +{ + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue(v8::Map::New(env->isolate)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsMap(JSVM_Env env, + JSVM_Value value, + bool* isMap) +{ + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isMap); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + *isMap = val->IsMap(); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_RetainScript(JSVM_Env env, JSVM_Script script) { + CHECK_ENV(env); + auto jsvmData = reinterpret_cast(script); + + RETURN_STATUS_IF_FALSE(env, jsvmData && !jsvmData->isGlobal, JSVM_INVALID_ARG); + + jsvmData->taggedPointer = v8::Global( + env->isolate, jsvmData->ToV8Local(env->isolate)); + + jsvmData->isGlobal = true; + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ReleaseScript(JSVM_Env env, JSVM_Script script) { + CHECK_ENV(env); + auto jsvmData = reinterpret_cast(script); + + RETURN_STATUS_IF_FALSE(env, jsvmData && jsvmData->isGlobal, JSVM_INVALID_ARG); + + std::get>(jsvmData->taggedPointer).Reset(); + delete jsvmData; + return jsvm_clear_last_error(env); +} + +//cjh int FindAvailablePort() { +// constexpr int startPort = 9229; +// constexpr int endPort = 9999; +// constexpr int invalidPort = -1; +// int sockfd = -1; +// +// for (auto port = startPort; port <= endPort; ++port) { +// sockfd = socket(AF_INET, SOCK_STREAM, 0); +// if (sockfd < 0) { +// continue; +// } +// struct sockaddr_in addr; +// addr.sin_family = AF_INET; +// addr.sin_addr.s_addr = htonl(INADDR_ANY); +// addr.sin_port = htons(port); +// +// if (bind(sockfd, reinterpret_cast(&addr), sizeof(addr)) < 0) { +// close(sockfd); +// if (errno == EADDRINUSE) { +// continue; +// } else { +// break; +// } +// } +// close(sockfd); +// return port; +// } +// return invalidPort; +//} +// +//JSVM_Status JSVM_CDECL OH_JSVM_OpenInspectorWithName(JSVM_Env env, +// int pid, +// const char* name) { +// JSVM_PREAMBLE(env); +// RETURN_STATUS_IF_FALSE(env, !name || strlen(name) < SIZE_MAX, JSVM_INVALID_ARG); +// RETURN_STATUS_IF_FALSE(env, pid >= 0, JSVM_INVALID_ARG); +// std::string path(name ? name : "jsvm"); +// auto port = FindAvailablePort(); +// auto hostPort = +// std::make_shared>("localhost", port, pid); +// env->inspector_agent()->Start(path, hostPort, true, false); +// return GET_RETURN_STATUS(env); +//} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateSet(JSVM_Env env, + JSVM_Value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue(v8::Set::New(env->isolate)); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsSet(JSVM_Env env, + JSVM_Value value, + bool* isSet) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, isSet); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *isSet = val->IsSet(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ObjectGetPrototypeOf(JSVM_Env env, + JSVM_Value object, + JSVM_Value* result) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local val = obj->GetPrototype(); + *result = v8impl::JsValueFromV8LocalValue(val); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ObjectSetPrototypeOf(JSVM_Env env, + JSVM_Value object, + JSVM_Value prototype) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, prototype); + + v8::Local context = env->context(); + + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local type = v8impl::V8LocalValueFromJsValue(prototype); + RETURN_STATUS_IF_FALSE(env, type->IsObject(), JSVM_INVALID_ARG); + v8::Maybe set_maybe = obj->SetPrototype(context, type); + + RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), JSVM_GENERIC_FAILURE); + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CompileWasmModule(JSVM_Env env, + const uint8_t *wasmBytecode, + size_t wasmBytecodeLength, + const uint8_t *cacheData, + size_t cacheDataLength, + bool *cacheRejected, + JSVM_Value *wasmModule) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, wasmBytecode); + RETURN_STATUS_IF_FALSE(env, wasmBytecodeLength > 0, JSVM_INVALID_ARG); + v8::MaybeLocal maybe_module; + if (cacheData == nullptr) { + maybe_module = v8::WasmModuleObject::Compile(env->isolate, {wasmBytecode, wasmBytecodeLength}); + } else { + assert(false);//cjh + RETURN_STATUS_IF_FALSE(env, cacheDataLength > 0, JSVM_INVALID_ARG); + bool rejected; +//cjh maybe_module = v8::WasmModuleObject::DeserializeOrCompile( +// env->isolate, {wasmBytecode, wasmBytecodeLength}, {cacheData, cacheDataLength}, rejected); + if (cacheRejected != nullptr) { + *cacheRejected = rejected; + } + } + // To avoid the status code caused by exception being override, check exception once v8 API finished + if (try_catch.HasCaught()) { + return jsvm_set_last_error(env, JSVM_PENDING_EXCEPTION); + } + CHECK_MAYBE_EMPTY(env, maybe_module, JSVM_GENERIC_FAILURE); + *wasmModule = v8impl::JsValueFromV8LocalValue(maybe_module.ToLocalChecked()); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CompileWasmFunction(JSVM_Env env, + JSVM_Value wasmModule, + uint32_t functionIndex, + JSVM_WasmOptLevel optLevel) { + assert(false);//cjh +//cjh JSVM_PREAMBLE(env); +// CHECK_ARG(env, wasmModule); +// v8::Local val = v8impl::V8LocalValueFromJsValue(wasmModule); +// RETURN_STATUS_IF_FALSE(env, val->IsWasmModuleObject(), JSVM_INVALID_ARG); +// +// v8::Local v8WasmModule = val.As(); +// v8::WasmExecutionTier tier = v8::WasmExecutionTier::kNone; +// if (optLevel == JSVM_WASM_OPT_BASELINE) { +// // v8 liftoff has bug, keep BASELINE same as HIGH. +// tier = v8::WasmExecutionTier::kTurbofan; +// } else if (optLevel == JSVM_WASM_OPT_HIGH) { +// tier = v8::WasmExecutionTier::kTurbofan; +// } else { +// // Unsupported optLevel +// return jsvm_set_last_error(env, JSVM_INVALID_ARG); +// } +// bool compileSuccess = v8WasmModule->CompileFunction(env->isolate, functionIndex, tier); +// // To avoid the status code caused by exception being override, check exception once v8 API finished +// if (try_catch.HasCaught()) { +// return jsvm_set_last_error(env, JSVM_PENDING_EXCEPTION); +// } +// RETURN_STATUS_IF_FALSE(env, compileSuccess, JSVM_GENERIC_FAILURE); + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_IsWasmModuleObject(JSVM_Env env, + JSVM_Value value, + bool* result) { + // Omit JSVM_PREAMBLE and GET_RETURN_STATUS because V8 + // calls here cannot throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsWasmModuleObject(); + + return jsvm_clear_last_error(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_CreateWasmCache(JSVM_Env env, + JSVM_Value wasmModule, + const uint8_t** data, + size_t* length) { + JSVM_PREAMBLE(env); + CHECK_ARG(env, wasmModule); + CHECK_ARG(env, data); + CHECK_ARG(env, length); + + v8::Local val = v8impl::V8LocalValueFromJsValue(wasmModule); + RETURN_STATUS_IF_FALSE(env, val->IsWasmModuleObject(), JSVM_INVALID_ARG); + + v8::Local v8WasmModule = val.As(); + v8::CompiledWasmModule compiledWasmModule = v8WasmModule->GetCompiledModule(); + v8::OwnedBuffer serialized_bytes = compiledWasmModule.Serialize(); + // To avoid the status code caused by exception being override, check exception once v8 API finished + if (try_catch.HasCaught()) { + return jsvm_set_last_error(env, JSVM_PENDING_EXCEPTION); + } + // If buffer size is 0, create wasm cache failed. + RETURN_STATUS_IF_FALSE(env, serialized_bytes.size > 0, JSVM_GENERIC_FAILURE); + *data = serialized_bytes.buffer.get(); + *length = serialized_bytes.size; + // Release the ownership of buffer, OH_JSVM_ReleaseCache must be called explicitly to release the buffer + serialized_bytes.buffer.release(); + + return GET_RETURN_STATUS(env); +} + +JSVM_Status JSVM_CDECL OH_JSVM_ReleaseCache(JSVM_Env env, + const uint8_t* cacheData, + JSVM_CacheType cacheType) { + CHECK_ENV(env); + CHECK_ARG(env, cacheData); + if (cacheType == JSVM_CACHE_TYPE_JS) { + // The release behavior MUST match the memory allocation of OH_JSVM_CreateCodeCache. + delete[] cacheData; + } else if (cacheType == JSVM_CACHE_TYPE_WASM) { + // The release behavior MUST match the memory allocation of OH_JSVM_CreateWasmCache. + delete[] cacheData; + } else { + // Unsupported cacheType + return jsvm_set_last_error(env, JSVM_INVALID_ARG); + } + return jsvm_clear_last_error(env); +} diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.h new file mode 100644 index 0000000000..c9a9a6c04f --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.h @@ -0,0 +1,658 @@ +#ifndef SRC_JS_NATIVE_API_V8_H_ +#define SRC_JS_NATIVE_API_V8_H_ + +#include +#include +#include +#include +#include "jsvm_types.h" +#include "js_native_api_v8_internals.h" +#include "callback_queue.h" + +#ifdef TARGET_OHOS +#include +extern "C" void ReportData(uint32_t resType, int64_t value, + const std::unordered_map& mapPayLoad); +#endif + +inline JSVM_Status jsvm_clear_last_error(JSVM_Env env); + +namespace v8impl { + +class RefTracker { + public: + RefTracker() {} + virtual ~RefTracker() {} + virtual void Finalize() {} + + typedef RefTracker RefList; + + inline void Link(RefList* list) { + prev_ = list; + next_ = list->next_; + if (next_ != nullptr) { + next_->prev_ = this; + } + list->next_ = this; + } + + inline void Unlink() { + if (prev_ != nullptr) { + prev_->next_ = next_; + } + if (next_ != nullptr) { + next_->prev_ = prev_; + } + prev_ = nullptr; + next_ = nullptr; + } + + static void FinalizeAll(RefList* list) { + while (list->next_ != nullptr) { + list->next_->Finalize(); + } + } + + private: + RefList* next_ = nullptr; + RefList* prev_ = nullptr; +}; + +class Finalizer; +class Agent; +} // end of namespace v8impl + +struct JSVM_Data__ { + public: + using SourcePtr = std::variant, v8::Global>; + using DataType = enum { kJsvmScript }; + + template + JSVM_Data__(T ptr, bool retained, DataType type = kJsvmScript) + : taggedPointer(ptr), + isGlobal(retained), + type(type) {} + + template + v8::Local ToV8Local(v8::Isolate *isolate) { + if (isGlobal) { + return v8::Local::New(isolate, std::get>(taggedPointer)); + } else { + return std::get>(taggedPointer); + } + } + + SourcePtr taggedPointer; + bool isGlobal = false; + DataType type; +}; + +struct JSVM_Env__ { + explicit JSVM_Env__(v8::Local context, + int32_t module_api_version) + : isolate(context->GetIsolate()), + context_persistent(isolate, context), + module_api_version(module_api_version) { + jsvm_clear_last_error(this); + } + + // Constructor for creating partial env. + explicit JSVM_Env__(v8::Isolate* isolate, int32_t module_api_version); + +//cjh template +// inline void RequestInterrupt(Fn&& cb) { +// auto callback = native_immediates_interrupts_.CreateCallback( +// std::move(cb), node::CallbackFlags::kRefed); +// { +// node::Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_); +// native_immediates_interrupts_.Push(std::move(callback)); +// } +// isolate->RequestInterrupt([](v8::Isolate* isolate, void* data) { +// static_cast(data)->RunAndClearInterrupts(); +// }, this); +// } +// +// void RunAndClearInterrupts(); +// +// v8impl::Agent* inspector_agent() { return inspector_agent_; } + + v8::Platform* platform(); + + inline v8::Local context() const { + return v8impl::PersistentToLocal::Strong(context_persistent); + } + + inline void Ref() { refs++; } + inline void Unref() { + if (--refs == 0) DeleteMe(); + } + + virtual bool can_call_into_js() const { return true; } + + static inline void HandleThrow(JSVM_Env env, v8::Local value) { + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); + } + + // i.e. whether v8 exited or is about to exit + inline bool terminatedOrTerminating() { + return this->isolate->IsExecutionTerminating() || !can_call_into_js(); + } + + // v8 uses a special exception to indicate termination, the + // `handle_exception` callback should identify such case using + // terminatedOrTerminating() before actually handle the exception + template + inline void CallIntoModule(T&& call, U&& handle_exception = HandleThrow) { + int open_handle_scopes_before = open_handle_scopes; + int open_callback_scopes_before = open_callback_scopes; + jsvm_clear_last_error(this); + call(this); + CHECK_EQ(open_handle_scopes, open_handle_scopes_before); + CHECK_EQ(open_callback_scopes, open_callback_scopes_before); + if (!last_exception.IsEmpty()) { + handle_exception(this, last_exception.Get(this->isolate)); + last_exception.Reset(); + } + } + + // Call finalizer immediately. + virtual void CallFinalizer(JSVM_Finalize cb, void* data, void* hint) { + v8::HandleScope handle_scope(isolate); + CallIntoModule([&](JSVM_Env env) { cb(env, data, hint); }); + } + + // Invoke finalizer from V8 garbage collector. + void InvokeFinalizerFromGC(v8impl::RefTracker* finalizer); + + // Enqueue the finalizer to the JSVM_Env's own queue of the second pass + // weak callback. + // Implementation should drain the queue at the time it is safe to call + // into JavaScript. + virtual void EnqueueFinalizer(v8impl::RefTracker* finalizer) { + pending_finalizers.emplace(finalizer); + } + + // Remove the finalizer from the scheduled second pass weak callback queue. + // The finalizer can be deleted after this call. + virtual void DequeueFinalizer(v8impl::RefTracker* finalizer) { + pending_finalizers.erase(finalizer); + } + + virtual void DeleteMe(); + + void CheckGCAccess() { + if (in_gc_finalizer) { + v8impl::OnFatalError( + nullptr, + "Finalizer is calling a function that may affect GC state.\n" + "The finalizers are run directly from GC and must not affect GC " + "state.\n" + "Use `node_api_post_finalizer` from inside of the finalizer to work " + "around this issue.\n" + "It schedules the call as a new task in the event loop."); + } + } + + template + JSVM_Data__ *NewJsvmData(T srcPtr, JSVM_Data__::DataType type = JSVM_Data__::kJsvmScript) { + if (dataStack.empty() || open_handle_scopes != dataStack.top().first) { + dataStack.emplace(open_handle_scopes, std::vector()); + } + auto newData = new JSVM_Data__(srcPtr, false, type); + dataStack.top().second.push_back(newData); + return newData; + } + + void ReleaseJsvmData() { + if (dataStack.empty() || open_handle_scopes != dataStack.top().first) { + return; + } + for (auto data : dataStack.top().second) { + if (!data->isGlobal) { + delete data; + } + } + dataStack.pop(); + } + + v8::Isolate* const isolate; // Shortcut for context()->GetIsolate() + v8impl::Persistent context_persistent; + + v8impl::Persistent last_exception; + + // We store references in two different lists, depending on whether they have + // `JSVM_Finalizer` callbacks, because we must first finalize the ones that + // have such a callback. See `~JSVM_Env__()` above for details. + v8impl::RefTracker::RefList reflist; + v8impl::RefTracker::RefList finalizing_reflist; + // The invocation order of the finalizers is not determined. + std::unordered_set pending_finalizers; + JSVM_ExtendedErrorInfo last_error; + int open_handle_scopes = 0; + int open_callback_scopes = 0; + int refs = 1; + void* instance_data = nullptr; + int32_t module_api_version = NODE_API_DEFAULT_MODULE_API_VERSION; + bool in_gc_finalizer = false; + v8::Locker* locker = nullptr; + std::stack>> dataStack; + + private: + v8impl::Agent* inspector_agent_; + typedef node::CallbackQueue NativeImmediateQueue; +//cjh node::Mutex native_immediates_threadsafe_mutex_; + std::mutex native_immediates_threadsafe_mutex_; + NativeImmediateQueue native_immediates_interrupts_; + + protected: + // Should not be deleted directly. Delete with `JSVM_Env__::DeleteMe()` + // instead. + virtual ~JSVM_Env__() = default; +}; + +inline JSVM_Status jsvm_clear_last_error(JSVM_Env env) { + env->last_error.errorCode = JSVM_OK; + env->last_error.engineErrorCode = 0; + env->last_error.engineReserved = nullptr; + env->last_error.errorMessage = nullptr; + return JSVM_OK; +} + +inline JSVM_Status jsvm_set_last_error(JSVM_Env env, + JSVM_Status errorCode, + uint32_t engineErrorCode = 0, + void* engineReserved = nullptr) { + env->last_error.errorCode = errorCode; + env->last_error.engineErrorCode = engineErrorCode; + env->last_error.engineReserved = engineReserved; + return errorCode; +} + +#define RETURN_STATUS_IF_FALSE(env, condition, status) \ + do { \ + if (!(condition)) { \ + return jsvm_set_last_error((env), (status)); \ + } \ + } while (0) + +#define RETURN_STATUS_IF_FALSE_WITH_PREAMBLE(env, condition, status) \ + do { \ + if (!(condition)) { \ + return jsvm_set_last_error( \ + (env), try_catch.HasCaught() ? JSVM_PENDING_EXCEPTION : (status)); \ + } \ + } while (0) + +#define CHECK_ENV(env) \ + do { \ + if ((env) == nullptr) { \ + return JSVM_INVALID_ARG; \ + } \ + } while (0) + +#define CHECK_ENV_NOT_IN_GC(env) \ + do { \ + CHECK_ENV((env)); \ + (env)->CheckGCAccess(); \ + } while (0) + +#define CHECK_ARG(env, arg) \ + RETURN_STATUS_IF_FALSE((env), ((arg) != nullptr), JSVM_INVALID_ARG) + +#define CHECK_ARG_NOT_ZERO(env, arg) \ + RETURN_STATUS_IF_FALSE((env), ((arg) != 0), JSVM_INVALID_ARG) + +#define CHECK_ARG_WITH_PREAMBLE(env, arg) \ + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE( \ + (env), ((arg) != nullptr), JSVM_INVALID_ARG) + +#define CHECK_MAYBE_EMPTY(env, maybe, status) \ + RETURN_STATUS_IF_FALSE((env), !((maybe).IsEmpty()), (status)) + +#define CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe, status) \ + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsEmpty()), (status)) + +// JSVM_PREAMBLE is not wrapped in do..while: try_catch must have function scope +#define JSVM_PREAMBLE(env) \ + CHECK_ENV((env)); \ + RETURN_STATUS_IF_FALSE( \ + (env), (env)->last_exception.IsEmpty(), JSVM_PENDING_EXCEPTION); \ + RETURN_STATUS_IF_FALSE((env), \ + (env)->can_call_into_js(), \ + (env->module_api_version == JSVM_VERSION_EXPERIMENTAL \ + ? JSVM_CANNOT_RUN_JS \ + : JSVM_PENDING_EXCEPTION)); \ + jsvm_clear_last_error((env)); \ + v8impl::TryCatch try_catch((env)) + +#define CHECK_TO_TYPE(env, type, context, result, src, status) \ + do { \ + CHECK_ARG((env), (src)); \ + auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ + CHECK_MAYBE_EMPTY((env), maybe, (status)); \ + (result) = maybe.ToLocalChecked(); \ + } while (0) + +#define CHECK_TO_TYPE_WITH_PREAMBLE(env, type, context, result, src, status) \ + do { \ + CHECK_ARG_WITH_PREAMBLE((env), (src)); \ + auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ + CHECK_MAYBE_EMPTY_WITH_PREAMBLE((env), maybe, (status)); \ + (result) = maybe.ToLocalChecked(); \ + } while (0) + +#define CHECK_TO_FUNCTION(env, result, src) \ + do { \ + CHECK_ARG((env), (src)); \ + v8::Local v8value = v8impl::V8LocalValueFromJsValue((src)); \ + RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), JSVM_INVALID_ARG); \ + (result) = v8value.As(); \ + } while (0) + +#define CHECK_TO_OBJECT(env, context, result, src) \ + CHECK_TO_TYPE((env), Object, (context), (result), (src), JSVM_OBJECT_EXPECTED) + +#define CHECK_TO_BIGINT(env, context, result, src) \ + CHECK_TO_TYPE((env), BigInt, (context), (result), (src), JSVM_BIGINT_EXPECTED) + +#define CHECK_TO_OBJECT_WITH_PREAMBLE(env, context, result, src) \ + CHECK_TO_TYPE_WITH_PREAMBLE( \ + (env), Object, (context), (result), (src), JSVM_OBJECT_EXPECTED) + +#define CHECK_TO_STRING(env, context, result, src) \ + CHECK_TO_TYPE((env), String, (context), (result), (src), JSVM_STRING_EXPECTED) + +#define GET_RETURN_STATUS(env) \ + (!try_catch.HasCaught() \ + ? JSVM_OK \ + : jsvm_set_last_error((env), JSVM_PENDING_EXCEPTION)) + +#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \ + do { \ + if (!(condition)) { \ + OH_JSVM_ThrowRangeError((env), (error), (message)); \ + return jsvm_set_last_error((env), JSVM_GENERIC_FAILURE); \ + } \ + } while (0) + +#define CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe, status) \ + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsEmpty()), (status)) + +#define STATUS_CALL(call) \ + do { \ + JSVM_Status status = (call); \ + if (status != JSVM_OK) return status; \ + } while (0) + +namespace v8impl { + +//=== Conversion between V8 Handles and JSVM_Value ======================== + +// This asserts v8::Local<> will always be implemented with a single +// pointer field so that we can pass it around as a void*. +static_assert(sizeof(v8::Local) == sizeof(JSVM_Value), + "Cannot convert between v8::Local and JSVM_Value"); + +inline JSVM_Value JsValueFromV8LocalValue(v8::Local local) { + return reinterpret_cast(*local); +} + +inline v8::Local V8LocalValueFromJsValue(JSVM_Value v) { + v8::Local local; + memcpy(static_cast(&local), &v, sizeof(v)); + return local; +} + +// Adapter for JSVM_Finalize callbacks. +class Finalizer { + protected: + Finalizer(JSVM_Env env, + JSVM_Finalize finalize_callback, + void* finalize_data, + void* finalize_hint) + : env_(env), + finalize_callback_(finalize_callback), + finalize_data_(finalize_data), + finalize_hint_(finalize_hint) {} + + virtual ~Finalizer() = default; + + public: + static Finalizer* New(JSVM_Env env, + JSVM_Finalize finalize_callback = nullptr, + void* finalize_data = nullptr, + void* finalize_hint = nullptr) { + return new Finalizer(env, finalize_callback, finalize_data, finalize_hint); + } + + JSVM_Finalize callback() { return finalize_callback_; } + void* data() { return finalize_data_; } + void* hint() { return finalize_hint_; } + + void ResetFinalizer(); + + protected: + JSVM_Env env_; + JSVM_Finalize finalize_callback_; + void* finalize_data_; + void* finalize_hint_; +}; + +class TryCatch : public v8::TryCatch { + public: + explicit TryCatch(JSVM_Env env) : v8::TryCatch(env->isolate), _env(env) {} + + ~TryCatch() { + if (HasCaught()) { + _env->last_exception.Reset(_env->isolate, Exception()); + } + } + + private: + JSVM_Env _env; +}; + +// Ownership of a reference. +enum class Ownership { + // The reference is owned by the runtime. No userland call is needed to + // destruct the reference. + kRuntime, + // The reference is owned by the userland. User code is responsible to delete + // the reference with appropriate node-api calls. + kUserland, +}; + +// Wrapper around Finalizer that can be tracked. +class TrackedFinalizer : public Finalizer, public RefTracker { + protected: + TrackedFinalizer(JSVM_Env env, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint); + + public: + static TrackedFinalizer* New(JSVM_Env env, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint); + ~TrackedFinalizer() override; + + protected: + void Finalize() override; + void FinalizeCore(bool deleteMe); +}; + +// Wrapper around Finalizer that implements reference counting. +class RefBase : public TrackedFinalizer { + protected: + RefBase(JSVM_Env env, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint); + + public: + static RefBase* New(JSVM_Env env, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint); + + void* Data(); + uint32_t Ref(); + uint32_t Unref(); + uint32_t RefCount(); + + Ownership ownership() { return ownership_; } + + protected: + void Finalize() override; + + private: + uint32_t refcount_; + Ownership ownership_; +}; + +// Wrapper around v8impl::Persistent. +class Reference : public RefBase { + protected: + template + Reference(JSVM_Env env, v8::Local value, Args&&... args); + + public: + static Reference* New(JSVM_Env env, + v8::Local value, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback = nullptr, + void* finalizeData = nullptr, + void* finalizeHint = nullptr); + + virtual ~Reference(); + bool HasDeletedByUser() { + return deleted_by_user; + } + uint32_t Ref(); + uint32_t Unref(); + v8::Local Get(); + void Delete(); + + protected: + void Finalize() override; + + private: + static void WeakCallback(const v8::WeakCallbackInfo& data); + + void SetWeak(); + + v8impl::Persistent persistent_; + bool can_be_weak_; + bool deleted_by_user; + bool wait_callback; + bool deleted = false; + int counter = 0; + std::string createStack; +}; + +typedef JSVM_Value (* GetterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value); +typedef JSVM_Value (* SetterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value, JSVM_Value); +typedef JSVM_Value (* DeleterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value); +typedef JSVM_Value (* EnumeratorCallback)(JSVM_Env, JSVM_Value, JSVM_Value); + +struct JSVM_PropertyHandlerCfgStruct { + GetterCallback namedGetterCallback_; + SetterCallback namedSetterCallback_; + DeleterCallback nameDeleterCallback_; + EnumeratorCallback namedEnumeratorCallback_; + GetterCallback indexedGetterCallback_; + SetterCallback indexedSetterCallback_; + DeleterCallback indexedDeleterCallback_; + EnumeratorCallback indexedEnumeratorCallback_; + JSVM_Ref namedPropertyData_; + JSVM_Ref indexedPropertyData_; +}; + +inline JSVM_PropertyHandlerCfgStruct* CreatePropertyCfg(JSVM_Env env, JSVM_PropertyHandlerCfg propertyCfg) +{ + JSVM_PropertyHandlerCfgStruct* newPropertyCfg = new JSVM_PropertyHandlerCfgStruct; + if (newPropertyCfg != nullptr && propertyCfg != nullptr) { + newPropertyCfg->namedGetterCallback_ = propertyCfg->genericNamedPropertyGetterCallback; + newPropertyCfg->namedSetterCallback_ = propertyCfg->genericNamedPropertySetterCallback; + newPropertyCfg->nameDeleterCallback_ = propertyCfg->genericNamedPropertyDeleterCallback; + newPropertyCfg->namedEnumeratorCallback_ = propertyCfg->genericNamedPropertyEnumeratorCallback; + newPropertyCfg->indexedGetterCallback_ = propertyCfg->genericIndexedPropertyGetterCallback; + newPropertyCfg->indexedSetterCallback_ = propertyCfg->genericIndexedPropertySetterCallback; + newPropertyCfg->indexedDeleterCallback_ = propertyCfg->genericIndexedPropertyDeleterCallback; + newPropertyCfg->indexedEnumeratorCallback_ = propertyCfg->genericIndexedPropertyEnumeratorCallback; + newPropertyCfg->namedPropertyData_ = nullptr; + newPropertyCfg->indexedPropertyData_ = nullptr; + if (propertyCfg->namedPropertyData != nullptr) { + v8::Local v8_value = v8impl::V8LocalValueFromJsValue(propertyCfg->namedPropertyData); + v8impl::Reference* reference = v8impl::Reference::New(env, v8_value, 1, v8impl::Ownership::kUserland); + newPropertyCfg->namedPropertyData_ = reinterpret_cast(reference); + } + + if (propertyCfg->indexedPropertyData != nullptr) { + v8::Local v8_value = v8impl::V8LocalValueFromJsValue(propertyCfg->indexedPropertyData); + v8impl::Reference* reference = v8impl::Reference::New(env, v8_value, 1, v8impl::Ownership::kUserland); + newPropertyCfg->indexedPropertyData_ = reinterpret_cast(reference); + } + } + + return newPropertyCfg; +} + +inline void CfgFinalizedCallback(JSVM_Env env, void* finalizeData, void* finalizeHint) +{ + auto cfg = reinterpret_cast(finalizeData); + if (cfg->namedPropertyData_ != nullptr) { + delete reinterpret_cast(cfg->namedPropertyData_); + } + if (cfg->indexedPropertyData_ != nullptr) { + delete reinterpret_cast(cfg->indexedPropertyData_); + } + delete cfg; +} + +#ifdef TARGET_OHOS +namespace ResourceSchedule { +namespace ResType { +enum : uint32_t { + RES_TYPE_REPORT_KEY_THREAD = 39 +}; + +enum ReportChangeStatus : int64_t { + CREATE = 0, + REMOVE = 1 +}; + +enum ThreadRole : int64_t { + USER_INTERACT = 0, + NORMAL_DISPLAY = 1, + IMPORTANT_DISPLAY = 2, + NORMAL_AUDIO = 3, + IMPORTANT_AUDIO = 4, + IMAGE_DECODE = 5 +}; +} + +static inline void ReportKeyThread(uid_t uid, pid_t pid, pid_t tid, ResType::ThreadRole role) +{ + std::unordered_map payLoad = { + {"uid", std::to_string(uid)}, + {"pid", std::to_string(pid)}, + {"tid", std::to_string(tid)}, + {"role", std::to_string(role)}}; + ReportData(v8impl::ResourceSchedule::ResType::RES_TYPE_REPORT_KEY_THREAD, + v8impl::ResourceSchedule::ResType::ReportChangeStatus::CREATE, payLoad); +} +} +#endif +} // end of namespace v8impl + +#endif // SRC_JS_NATIVE_API_V8_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8_internals.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8_internals.h new file mode 100644 index 0000000000..9347b4bc37 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8_internals.h @@ -0,0 +1,47 @@ +#ifndef SRC_JS_NATIVE_API_V8_INTERNALS_H_ +#define SRC_JS_NATIVE_API_V8_INTERNALS_H_ + +// The V8 implementation of N-API, including `js_native_api_v8.h` uses certain +// idioms which require definition here. For example, it uses a variant of +// persistent references which need not be reset in the constructor. It is the +// responsibility of this file to define these idioms. Optionally, this file +// may also define `NAPI_VERSION` and set it to the version of N-API to be +// exposed. + +// In the case of the Node.js implementation of N-API some of the idioms are +// imported directly from Node.js by including `node_internals.h` below. Others +// are bridged to remove references to the `node` namespace. `node_version.h`, +// included below, defines `NAPI_VERSION`. + +#include "node_version.h" + +//cjh #include "env.h" +//cjh #include "gtest/gtest_prod.h" +// #include "node_errors.h" +// #include "node_internals.h" + +#include "util.h" + +#define JSVM_ARRAYSIZE(array) node::arraysize((array)) + +#define JSVM_FIXED_ONE_BYTE_STRING(isolate, string) \ + node::FIXED_ONE_BYTE_STRING((isolate), (string)) + +#define JSVM_PRIVATE_KEY(isolate, suffix) \ + (v8impl::GetIsolateData(isolate)->jsvm_##suffix##_key.Get(isolate)) + +namespace v8impl { + +template +using Persistent = v8::Global; + +using PersistentToLocal = node::PersistentToLocal; + +inline void OnFatalError(const char* location, + const char* message) { +//cjh node::OnFatalError(location, message); +} + +} // end of namespace v8impl + +#endif // SRC_JS_NATIVE_API_V8_INTERNALS_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm.h new file mode 100644 index 0000000000..7c8728af60 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm.h @@ -0,0 +1,2856 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_RUNTIME_JSVM_JSVM_H +#define ARK_RUNTIME_JSVM_JSVM_H + +/** + * @addtogroup JSVM + * @{ + * + * @brief Provides the standard JavaScript engine capabilities. + * + * Provides API to Provide independent, standard, and complete JavaScript engine capabilities for developers, + * including managing the engine lifecycle, compiling and running JS code, implementing JS/C++ cross language calls, + * and taking snapshots. + * + * @since 11 + */ + +/** + * @file jsvm.h + * + * @brief Provides the JSVM API define. + * + * Provides API to Provide independent, standard, and complete JavaScript engine capabilities for developers, + * including managing the engine lifecycle, compiling and running JS code, implementing JS/C++ cross language calls, + * and taking snapshots. + * @library libjsvm.so + * @syscap SystemCapability.ArkCompiler.JSVM + * @since 11 + */ + +// This file needs to be compatible with C compilers. +#include // NOLINT(modernize-deprecated-headers) +#include // NOLINT(modernize-deprecated-headers) + +// Use INT_MAX, this should only be consumed by the pre-processor anyway. +#define JSVM_VERSION_EXPERIMENTAL 2147483647 +#ifndef JSVM_VERSION +#ifdef JSVM_EXPERIMENTAL +#define JSVM_VERSION JSVM_VERSION_EXPERIMENTAL +#else +// The baseline version for JSVM-API. +// The JSVM_VERSION controls which version will be used by default when +// compilling a native addon. If the addon developer specifically wants to use +// functions available in a new version of JSVM-API that is not yet ported in all +// LTS versions, they can set JSVM_VERSION knowing that they have specifically +// depended on that version. +#define JSVM_VERSION 8 +#endif +#endif + +#include "jsvm_types.h" + +#ifndef JSVM_EXTERN +#ifdef _WIN32 +/** + * @brief externally visible. + * + * @since 11 + */ +#define JSVM_EXTERN __declspec(dllexport) +#elif defined(__wasm__) +#define JSVM_EXTERN \ + __attribute__((visibility("default"))) \ + __attribute__((__import_module__("jsvm"))) +#else +#define JSVM_EXTERN __attribute__((visibility("default"))) +#endif +#endif + +/** + * @brief auto length. + * + * @since 11 + */ +#define JSVM_AUTO_LENGTH SIZE_MAX + +#ifdef __cplusplus +#define EXTERN_C_START extern "C" { +#define EXTERN_C_END } +#else +#define EXTERN_C_START +#define EXTERN_C_END +#endif + +EXTERN_C_START + +/** + * @brief Init a JavaScript vm. + * + * @param options: The options for initialize the JavaScript VM. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_Init(const JSVM_InitOptions* options); + +/** + * @brief This API create a new VM instance. + * + * @param options: The options for create the VM instance. + * @param result: The new VM instance. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateVM(const JSVM_CreateVMOptions* options, + JSVM_VM* result); + +/** + * @brief Destroys VM instance. + * + * @param vm: The VM instance to be Destroyed. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DestroyVM(JSVM_VM vm); + +/** + * @brief This API open a new VM scope for the VM instance. + * + * @param vm: The VM instance to open scope for. + * @param result: The new VM scope. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_OpenVMScope(JSVM_VM vm, + JSVM_VMScope* result); + +/** + * @brief This function close the VM scope for the VM instance. + * + * @param vm: The VM instance to close scope for. + * @param scope: The VM scope to be closed. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CloseVMScope(JSVM_VM vm, + JSVM_VMScope scope); + +/** + * @brief This function create a new environment with optional properties for the context of the new environment. + * + * @param vm: The VM instance that the env will be created in. + * @param propertyCount: The number of elements in the properties array. + * @param properties: The array of property descriptor. + * @param result: The new environment created. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateEnv(JSVM_VM vm, + size_t propertyCount, + const JSVM_PropertyDescriptor* properties, + JSVM_Env* result); + +/** + * @brief This function create a new environment from the start snapshot of the vm. + * + * @param vm: The VM instance that the env will be created in. + * @param index: The index of the environment in the snapshot. + * @param result: The new environment created. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateEnvFromSnapshot(JSVM_VM vm, + size_t index, + JSVM_Env* result); + +/** + * @brief This function destroys the environment. + * + * @param env: The environment to be destroyed. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DestroyEnv(JSVM_Env env); + +/** + * @brief This function open a new environment scope. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param result: The new environment scope. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_OpenEnvScope(JSVM_Env env, + JSVM_EnvScope* result); + +/** + * @brief This function closes the environment scope of the environment. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param scope: The environment scope to be closed. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CloseEnvScope(JSVM_Env env, + JSVM_EnvScope scope); + +/** + * @brief This function retrieves the VM instance of the given environment. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param result: The VM instance of the environment. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetVM(JSVM_Env env, + JSVM_VM* result); + +/** + * @brief This function compiles a string of JavaScript code and returns the compiled script. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param script: A JavaScript string containing the script yo be compiled. + * @param cachedData: Optional code cache data for the script. + * @param cacheDataLength: The length of cachedData array. + * @param eagerCompile: Whether to compile the script eagerly. + * @param cacheRejected: Whether the code cache rejected by compilation. + * @param result: The compiled script. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CompileScript(JSVM_Env env, + JSVM_Value script, + const uint8_t* cachedData, + size_t cacheDataLength, + bool eagerCompile, + bool* cacheRejected, + JSVM_Script* result); + +/** + * @brief This function compiles a string of JavaScript code with the source code information + * and returns the compiled script. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param script: A JavaScript string containing the script to be compiled. + * @param cachedData: Optional code cache data for the script. + * @param cacheDataLength: The length of cachedData array. + * @param eagerCompile: Whether to compile the script eagerly. + * @param cacheRejected: Whether the code cache rejected by compilation. + * @param origin: The information of source code. + * @param result: The compiled script. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CompileScriptWithOrigin(JSVM_Env env, + JSVM_Value script, + const uint8_t* cachedData, + size_t cacheDataLength, + bool eagerCompile, + bool* cacheRejected, + JSVM_ScriptOrigin* origin, + JSVM_Script* result); + +/** + * @brief This function compiles a string of JavaScript code with the source code information + * and returns the compiled script. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param script: A JavaScript string containing the script to be compiled. + * @param optionCount: length of option array. + * @param options: Compile options to be passed. + * @param result: The compiled script. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CompileScriptWithOptions(JSVM_Env env, + JSVM_Value script, + size_t optionCount, + JSVM_CompileOptions options[], + JSVM_Script* result); + +/** + * @brief This function creates code cache for the compiled script. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param script: A compiled script to create code cache for. + * @param data: The data of the code cache. + * @param length: The length of the code cache data. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateCodeCache(JSVM_Env env, + JSVM_Script script, + const uint8_t** data, + size_t* length); + +/** + * @brief This function executes a string of JavaScript code and returns its result with the following caveats: + * Unlike eval, this function does not allow the script to access the current lexical scope, and therefore also + * does not allow to access the module scope, meaning that pseudo-globals such as require will not be available. + * The script can access the global scope. Function and var declarations in the script will be added to the + * global object. Variable declarations made using let and const will be visible globally, but will not be added + * to the global object.The value of this is global within the script. + * + * @param env: The environment that the API is invoked under. + * @param script: A JavaScript string containing the script to execute. + * @param result: The value resulting from having executed the script. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_RunScript(JSVM_Env env, + JSVM_Script script, + JSVM_Value* result); + +/** + * @brief This API associates data with the currently running JSVM environment. data can later be retrieved + * using OH_JSVM_GetInstanceData(). + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param data: The data item to make available to bindings of this instance. + * @param finalizeCb: The function to call when the environment is being torn down. The function receives + * data so that it might free it. JSVM_Finalize provides more details. + * @param finalizeHint: Optional hint to pass to the finalize callback during collection. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_SetInstanceData(JSVM_Env env, + void* data, + JSVM_Finalize finalizeCb, + void* finalizeHint); + +/** + * @brief This API retrieves data that was previously associated with the currently running JSVM environment + * via OH_JSVM_SetInstanceData(). If no data is set, the call will succeed and data will be set to NULL. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param data: The data item that was previously associated with the currently running JSVM environment by + * a call to OH_JSVM_SetInstanceData(). + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetInstanceData(JSVM_Env env, + void** data); + +/** + * @brief This API retrieves a JSVM_ExtendedErrorInfo structure with information about the last error that + * occurred. + * + * @param env: The environment that the JSVM-API call is invoked under. + * @param result: The JSVM_ExtendedErrorInfo structure with more information about the error. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetLastErrorInfo(JSVM_Env env, + const JSVM_ExtendedErrorInfo** result); + +/** + * @brief This API throws the JavaScript value provided. + * + * @param env: The environment that the API is invoked under. + * @param error: The JavaScript value to be thrown. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_Throw(JSVM_Env env, + JSVM_Value error); + +/** + * @brief This API throws a JavaScript Error with the text provided. + * + * @param env: The environment that the API is invoked under. + * @param code: Optional error code to be set on the error. + * @param msg: C string representing the text to be associated with the error. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ThrowError(JSVM_Env env, + const char* code, + const char* msg); + +/** + * @brief This API throws a JavaScript TypeError with the text provided. + * + * @param env: The environment that the API is invoked under. + * @param code: Optional error code to be set on the error. + * @param msg: C string representing the text to be associated with the error. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ThrowTypeError(JSVM_Env env, + const char* code, + const char* msg); + +/** + * @brief This API throws a JavaScript RangeError with the text provided. + * + * @param env: The environment that the API is invoked under. + * @param code: Optional error code to be set on the error. + * @param msg: C string representing the text to be associated with the error. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ThrowRangeError(JSVM_Env env, + const char* code, + const char* msg); + +/** + * @brief This API throws a JavaScript SyntaxError with the text provided. + * + * @param env: The environment that the API is invoked under. + * @param code: Optional error code to be set on the error. + * @param msg: C string representing the text to be associated with the error. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ThrowSyntaxError(JSVM_Env env, + const char* code, + const char* msg); + +/** + * @brief This API queries a JSVM_Value to check if it represents an error object. + * + * @param env: The environment that the API is invoked under. + * @param value: The JSVM_Value to be checked. + * @param result: Boolean value that is set to true if JSVM_Value represents an error, + * false otherwise. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsError(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief This API returns a JavaScript Error with the text provided. + * + * @param env: The environment that the API is invoked under. + * @param code: Optional JSVM_Value with the string for the error code to be associated with the error. + * @param msg: JSVM_Value that references a JavaScript string to be used as the message for the Error. + * @param result: JSVM_Value representing the error created. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateError(JSVM_Env env, + JSVM_Value code, + JSVM_Value msg, + JSVM_Value* result); + +/** + * @brief This API returns a JavaScript TypeError with the text provided. + * + * @param env: The environment that the API is invoked under. + * @param code: Optional JSVM_Value with the string for the error code to be associated with the error. + * @param msg: JSVM_Value that references a JavaScript string to be used as the message for the Error. + * @param result: JSVM_Value representing the error created. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateTypeError(JSVM_Env env, + JSVM_Value code, + JSVM_Value msg, + JSVM_Value* result); + +/** + * @brief This API returns a JavaScript RangeError with the text provided. + * + * @param env: The environment that the API is invoked under. + * @param code: Optional JSVM_Value with the string for the error code to be associated with the error. + * @param msg: JSVM_Value that references a JavaScript string to be used as the message for the Error. + * @param result: JSVM_Value representing the error created. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateRangeError(JSVM_Env env, + JSVM_Value code, + JSVM_Value msg, + JSVM_Value* result); + +/** + * @brief This API returns a JavaScript SyntaxError with the text provided. + * + * @param env: The environment that the API is invoked under. + * @param code: Optional JSVM_Value with the string for the error code to be associated with the error. + * @param msg: JSVM_Value that references a JavaScript string to be used as the message for the Error. + * @param result: JSVM_Value representing the error created. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateSyntaxError(JSVM_Env env, + JSVM_Value code, + JSVM_Value msg, + JSVM_Value* result); + +/** + * @brief This API returns a JavaScript exception if one is pending, NULL otherwise. + * + * @param env: The environment that the API is invoked under. + * @param result: The exception if one is pending, NULL otherwise. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetAndClearLastException(JSVM_Env env, + JSVM_Value* result); + +/** + * @brief This API returns true if an exception is pending, false otherwise. + * + * @param env: The environment that the API is invoked under. + * @param result: Boolean value that is set to true if an exception is pending. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsExceptionPending(JSVM_Env env, + bool* result); + +/** + * @brief This API opens a new scope. + * + * @param env: The environment that the API is invoked under. + * @param result: JSVM_Value representing the new scope. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_OpenHandleScope(JSVM_Env env, + JSVM_HandleScope* result); + +/** + * @brief This API closes the scope passed in. Scopes must be closed in the reverse + * order from which they were created. + * + * @param env: The environment that the API is invoked under. + * @param scope: JSVM_Value representing the scope to be closed. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CloseHandleScope(JSVM_Env env, + JSVM_HandleScope scope); + +/** + * @brief This API opens a new scope from which one object can be promoted to the outer scope. + * + * @param env: The environment that the API is invoked under. + * @param result: JSVM_Value representing the new scope. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_OpenEscapableHandleScope(JSVM_Env env, + JSVM_EscapableHandleScope* result); + +/** + * @brief This API closes the scope passed in. Scopes must be closed in the reverse order + * from which they were created. + * + * @param env: The environment that the API is invoked under. + * @param scope: JSVM_Value representing the scope to be closed. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CloseEscapableHandleScope(JSVM_Env env, + JSVM_EscapableHandleScope scope); + +/** + * @brief This API promotes the handle to the JavaScript object so that it is valid for the lifetime + * of the outer scope. It can only be called once per scope. If it is called more than once an error + * will be returned. + * + * @param env: The environment that the API is invoked under. + * @param scope: JSVM_Value representing the current scope. + * @param escapee: JSVM_Value representing the JavaScript Object to be escaped. + * @param result: JSVM_Value representing the handle to the escaped Object in the outer scope. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_EscapeHandle(JSVM_Env env, + JSVM_EscapableHandleScope scope, + JSVM_Value escapee, + JSVM_Value* result); + +/** + * @brief This API creates a new reference with the specified reference count to the value passed in. + * + * @param env: The environment that the API is invoked under. + * @param value: The JSVM_Value for which a reference is being created. + * @param initialRefcount: Initial reference count for the new reference. + * @param result: JSVM_Ref pointing to the new reference. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateReference(JSVM_Env env, + JSVM_Value value, + uint32_t initialRefcount, + JSVM_Ref* result); + +/** + * @brief this API deletes the reference passed in. + * + * @param env: The environment that the API is invoked under. + * @param ref: JSVM_Ref to be deleted. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DeleteReference(JSVM_Env env, + JSVM_Ref ref); + +/** + * @brief his API increments the reference count for the reference passed in and + * returns the resulting reference count. + * + * @param env: The environment that the API is invoked under. + * @param ref: JSVM_Ref for which the reference count will be incremented. + * @param result: The new reference count. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ReferenceRef(JSVM_Env env, + JSVM_Ref ref, + uint32_t* result); + +/** + * @brief This API decrements the reference count for the reference passed in and + * returns the resulting reference count. + * + * @param env: The environment that the API is invoked under. + * @param ref: JSVM_Ref for which the reference count will be decremented. + * @param result: The new reference count. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ReferenceUnref(JSVM_Env env, + JSVM_Ref ref, + uint32_t* result); + +/** + * @brief If still valid, this API returns the JSVM_Value representing the + * JavaScript value associated with the JSVM_Ref. Otherwise, result will be NULL. + * + * @param env: The environment that the API is invoked under. + * @param ref: The JSVM_Ref for which the corresponding value is being requested. + * @param result: The JSVM_Value referenced by the JSVM_Ref. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetReferenceValue(JSVM_Env env, + JSVM_Ref ref, + JSVM_Value* result); + +/** + * @brief This API returns a JSVM-API value corresponding to a JavaScript Array type. + * + * @param env: The environment that the API is invoked under. + * @param result: A JSVM_Value representing a JavaScript Array. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateArray(JSVM_Env env, + JSVM_Value* result); + + +/** + * @brief This API returns a JSVM-API value corresponding to a JavaScript Array type. The Array's length property + * is set to the passed-in length parameter. However, the underlying buffer is not guaranteed to be pre-allocated + * by the VM when the array is created. That behavior is left to the underlying VM implementation. + * + * @param env: The environment that the API is invoked under. + * @param length: The initial length of the Array. + * @param result: A JSVM_Value representing a JavaScript Array. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateArrayWithLength(JSVM_Env env, + size_t length, + JSVM_Value* result); + +/** + * @brief This API returns a JSVM-API value corresponding to a JavaScript ArrayBuffer. ArrayBuffers are used to + * represent fixed-length binary data buffers. They are normally used as a backing-buffer for TypedArray objects. + * The ArrayBuffer allocated will have an underlying byte buffer whose size is determined by the length parameter + * that's passed in. The underlying buffer is optionally returned back to the caller in case the caller wants to + * directly manipulate the buffer. This buffer can only be written to directly from native code. To write to this + * buffer from JavaScript, a typed array or DataView object would need to be created. + * + * @param env: The environment that the API is invoked under. + * @param byteLength: The length in bytes of the array buffer to create. + * @param data: Pointer to the underlying byte buffer of the ArrayBuffer.data can optionally be ignored by passing NULL. + * @param result: A JSVM_Value representing a JavaScript Array. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateArraybuffer(JSVM_Env env, + size_t byteLength, + void** data, + JSVM_Value* result); + +/** + * @brief This API allocate the memory of array buffer backing store. + * + * @param byteLength: size of backing store memory. + * @param initialized: initialization status of the backing store memory. + * @param data: pointer that recieve the backing store memory pointer. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if allocation succeed.\n + * Returns {@link JSVM_INVALID_ARG } if data is null pointer.\n + * Returns {@link JSVM_GENERIC_FAILURE } if allocation failed.\n + * @since 12 + */ +JSVM_Status JSVM_CDECL OH_JSVM_AllocateArrayBufferBackingStoreData(size_t byteLength, + JSVM_InitializedFlag initialized, + void **data); + +/** + * @brief This API release the memory of an array buffer backing store. + * + * @param data: pointer to the backing store memory. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if run succeed.\n + * Returns {@link JSVM_INVALID_ARG } if data is null pointer.\n + * @since 12 + */ +JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void *data); + +/** + * @brief This API create an array buffer using the backing store data. + * + * @param env: The environment that the API is invoked under. + * @param data: pointer to the backing store memory. + * @param backingStoreSize: size of backing store memory. + * @param offset: start position of the array buffer in the backing store memory. + * @param arrayBufferSize: size of the array buffer. + * @param result: pointer that recieve the array buffer. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if creation succeed.\n + * Returns {@link JSVM_INVALID_ARG } if any of the following condition reached:\n + * 1. offset + arrayBufferSize > backingStoreSize\n + * 2. backingStoreSize or arrayBufferSize equals zero + * 3. data or result is null pointer + * @since 12 + */ +JSVM_Status JSVM_CDECL OH_JSVM_CreateArrayBufferFromBackingStoreData(JSVM_Env env, + void *data, + size_t backingStoreSize, + size_t offset, + size_t arrayBufferSize, + JSVM_Value *result); + +/** + * @brief This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification. + * This API allocates a JavaScript Date object. + * + * @param env: The environment that the API is invoked under. + * @param time: ECMAScript time value in milliseconds since 01 January, 1970 UTC. + * @param result: A JSVM_Value representing a JavaScript Date. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateDate(JSVM_Env env, + double time, + JSVM_Value* result); + +/** + * @brief This API allocates a JavaScript value with external data attached to it. This is used to pass external + * data through JavaScript code, so it can be retrieved later by native code using OH_JSVM_GetValueExternal. + * The API adds a JSVM_Finalize callback which will be called when the JavaScript object just created has been garbage + * collected.The created value is not an object, and therefore does not support additional properties. It is considered + * a distinct value type: calling OH_JSVM_Typeof() with an external value yields JSVM_EXTERNAL. + * + * @param env: The environment that the API is invoked under. + * @param data: Raw pointer to the external data. + * @param finalizeCb: Optional callback to call when the external value is being collected. JSVM_Finalize provides + * more details. + * @param finalizeHint: Optional hint to pass to the finalize callback during collection. + * @param result: A JSVM_Value representing an external value. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateExternal(JSVM_Env env, + void* data, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Value* result); + +/** + * @brief This API allocates a default JavaScript Object. It is the equivalent of doing new Object() in JavaScript. + * + * @param env: The environment that the API is invoked under. + * @param result: A JSVM_Value representing a JavaScript Object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateObject(JSVM_Env env, + JSVM_Value* result); + +/** + * @brief This API creates a JavaScript symbol value from a UTF8-encoded C string. + * + * @param env: The environment that the API is invoked under. + * @param description: Optional JSVM_Value which refers to a JavaScript string to be set as the description + * for the symbol. + * @param result: A JSVM_Value representing a JavaScript symbol. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateSymbol(JSVM_Env env, + JSVM_Value description, + JSVM_Value* result); + +/** + * @brief This API searches in the global registry for an existing symbol with the given description. + * If the symbol already exists it will be returned, otherwise a new symbol will be created in the registry. + * + * @param env: The environment that the API is invoked under. + * @param utf8description: UTF-8 C string representing the text to be used as the description for the symbol. + * @param length: The length of the description string in bytes, or JSVM_AUTO_LENGTH if it is null-terminated. + * @param result: A JSVM_Value representing a JavaScript symbol. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_SymbolFor(JSVM_Env env, + const char* utf8description, + size_t length, + JSVM_Value* result); + +/** + * @brief This API creates a JavaScript TypedArray object over an existing ArrayBuffer. TypedArray + * objects provide an array-like view over an underlying data buffer where each element has the + * same underlying binary scalar datatype.It's required that (length * size_of_element) + byte_offset should + * be <= the size in bytes of the array passed in. If not, a RangeError exception is raised. + * + * @param env: The environment that the API is invoked under. + * @param type: Scalar datatype of the elements within the TypedArray. + * @param length: Number of elements in the TypedArray. + * @param arraybuffer: ArrayBuffer underlying the typed array. + * @param byteOffset: The byte offset within the ArrayBuffer from which to start projecting the TypedArray. + * @param result: A JSVM_Value representing a JavaScript TypedArray + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateTypedarray(JSVM_Env env, + JSVM_TypedarrayType type, + size_t length, + JSVM_Value arraybuffer, + size_t byteOffset, + JSVM_Value* result); + +/** + * @brief This API creates a JavaScript DataView object over an existing ArrayBuffer. DataView + * objects provide an array-like view over an underlying data buffer, but one which allows items + * of different size and type in the ArrayBuffer.It is required that byte_length + byte_offset is + * less than or equal to the size in bytes of the array passed in. If not, a RangeError exception + * is raised. + * + * @param env: The environment that the API is invoked under. + * @param length: Number of elements in the DataView. + * @param arraybuffer: ArrayBuffer underlying the DataView. + * @param byteOffset: The byte offset within the ArrayBuffer from which to start projecting the DataView. + * @param result:A JSVM_Value representing a JavaScript DataView. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateDataview(JSVM_Env env, + size_t length, + JSVM_Value arraybuffer, + size_t byteOffset, + JSVM_Value* result); + +/** + * @brief This API is used to convert from the C int32_t type to the JavaScript number type. + * + * @param env: The environment that the API is invoked under. + * @param value: Integer value to be represented in JavaScript. + * @param result: A JSVM_Value representing a JavaScript number. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateInt32(JSVM_Env env, + int32_t value, + JSVM_Value* result); + +/** + * @brief This API is used to convert from the C uint32_t type to the JavaScript number type. + * + * @param env: The environment that the API is invoked under. + * @param value: Unsigned integer value to be represented in JavaScript. + * @param result: A JSVM_Value representing a JavaScript number. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateUint32(JSVM_Env env, + uint32_t value, + JSVM_Value* result); + +/** + * @brief This API is used to convert from the C int64_t type to the JavaScript number type. + * + * @param env: The environment that the API is invoked under. + * @param value: Integer value to be represented in JavaScript. + * @param result: A JSVM_Value representing a JavaScript number. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateInt64(JSVM_Env env, + int64_t value, + JSVM_Value* result); + +/** + * @brief This API is used to convert from the C double type to the JavaScript number type. + * + * @param env: The environment that the API is invoked under. + * @param value: Double-precision value to be represented in JavaScript. + * @param result: A JSVM_Value representing a JavaScript number. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateDouble(JSVM_Env env, + double value, + JSVM_Value* result); + +/** + * @brief This API converts the C int64_t type to the JavaScript BigInt type. + * + * @param env: The environment that the API is invoked under. + * @param value: Integer value to be represented in JavaScript. + * @param result: A JSVM_Value representing a JavaScript BigInt. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateBigintInt64(JSVM_Env env, + int64_t value, + JSVM_Value* result); + +/** + * @brief This API converts the C uint64_t type to the JavaScript BigInt type. + * + * @param env: The environment that the API is invoked under. + * @param value: Unsigned integer value to be represented in JavaScript. + * @param result: A JSVM_Value representing a JavaScript BigInt. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateBigintUint64(JSVM_Env env, + uint64_t value, + JSVM_Value* result); + +/** + * @brief This API converts an array of unsigned 64-bit words into a single BigInt value. + * The resulting BigInt is calculated as: (–1)sign_bit (words[0] × (264)0 + words[1] × (264)1 + …) + * + * @param env: The environment that the API is invoked under. + * @param signBit: Determines if the resulting BigInt will be positive or negative. + * @param wordCount: The length of the words array. + * @param words: An array of uint64_t little-endian 64-bit words. + * @param result: A JSVM_Value representing a JavaScript BigInt. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateBigintWords(JSVM_Env env, + int signBit, + size_t wordCount, + const uint64_t* words, + JSVM_Value* result); + +/** + * @brief This API creates a JavaScript string value from an ISO-8859-1-encoded C + * string. The native string is copied. + * + * @param env: The environment that the API is invoked under. + * @param str: Character buffer representing an ISO-8859-1-encoded string. + * @param length: The length of the string in bytes, or JSVM_AUTO_LENGTH if it is null-terminated. + * @param result: A JSVM_Value representing a JavaScript string. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateStringLatin1(JSVM_Env env, + const char* str, + size_t length, + JSVM_Value* result); + +/** + * @brief This API creates a JavaScript string value from a UTF16-LE-encoded C + * string. The native string is copied. + * + * @param env: The environment that the API is invoked under. + * @param str: Character buffer representing a UTF16-LE-encoded string. + * @param length: The length of the string in two-byte code units, or JSVM_AUTO_LENGTH + * if it is null-terminated. + * @param result: A JSVM_Value representing a JavaScript string. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateStringUtf16(JSVM_Env env, + const char16_t* str, + size_t length, + JSVM_Value* result); + +/** + * @brief This API creates a JavaScript string value from a UTF8-encoded C + * string. The native string is copied. + * + * @param env: The environment that the API is invoked under. + * @param str: Character buffer representing a UTF8-encoded string. + * @param length: The length of the string in bytes, or JSVM_AUTO_LENGTH if it is null-terminated. + * @param result: A JSVM_Value representing a JavaScript string. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateStringUtf8(JSVM_Env env, + const char* str, + size_t length, + JSVM_Value* result); + +/** + * @brief This API returns the length of an array. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing the JavaScript Array whose length is being queried. + * @param result: uint32 representing length of the array. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetArrayLength(JSVM_Env env, + JSVM_Value value, + uint32_t* result); + +/** + * @brief This API is used to retrieve the underlying data buffer of an ArrayBuffer and its length. + * + * @param env: The environment that the API is invoked under. + * @param arraybuffer: JSVM_Value representing the ArrayBuffer being queried. + * @param data: The underlying data buffer of the ArrayBuffer. If byte_length is 0, this may be NULL + * or any other pointer value. + * @param byteLength: Length in bytes of the underlying data buffer. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetArraybufferInfo(JSVM_Env env, + JSVM_Value arraybuffer, + void** data, + size_t* byteLength); + +/** + * @brief This API returns the length of an array. + * + * @param env: The environment that the API is invoked under. + * @param object: JSVM_Value representing JavaScript Object whose prototype to return. This returns + * the equivalent of Object.getPrototypeOf (which is not the same as the function's prototype property). + * @param result: JSVM_Value representing prototype of the given object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetPrototype(JSVM_Env env, + JSVM_Value object, + JSVM_Value* result); + +/** + * @brief This API returns various properties of a typed array. + * + * @param env: The environment that the API is invoked under. + * @param typedarray: JSVM_Value representing the TypedArray whose properties to query. + * @param type: Scalar datatype of the elements within the TypedArray. + * @param length: The number of elements in the TypedArray. + * @param data: The data buffer underlying the TypedArray adjusted by the byte_offset value so that it + * points to the first element in the TypedArray. If the length of the array is 0, this may be NULL or + * any other pointer value. + * @param arraybuffer: The ArrayBuffer underlying the TypedArray. + * @param byteOffset: The byte offset within the underlying native array at which the first element of + * the arrays is located. The value for the data parameter has already been adjusted so that data points + * to the first element in the array. Therefore, the first byte of the native array would be at data - byte_offset. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetTypedarrayInfo(JSVM_Env env, + JSVM_Value typedarray, + JSVM_TypedarrayType* type, + size_t* length, + void** data, + JSVM_Value* arraybuffer, + size_t* byteOffset); + +/** + * @brief Any of the out parameters may be NULL if that property is unneeded. + * This API returns various properties of a DataView. + * + * @param env: The environment that the API is invoked under. + * @param dataview: JSVM_Value representing the DataView whose properties to query. + * @param bytelength: Number of bytes in the DataView. + * @param data: The data buffer underlying the DataView. + * If byte_length is 0, this may be NULL or any other pointer value. + * @param arraybuffer: ArrayBuffer underlying the DataView. + * @param byteOffset: The byte offset within the data buffer from which to start projecting the DataView. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetDataviewInfo(JSVM_Env env, + JSVM_Value dataview, + size_t* bytelength, + void** data, + JSVM_Value* arraybuffer, + size_t* byteOffset); + +/** + * @brief Returns JSVM_OK if the API succeeded. If a non-date JSVM_Value is + * passed in it returns JSVM_date_expected.This API returns the C double + * primitive of time value for the given JavaScript Date. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing a JavaScript Date. + * @param result: Time value as a double represented as milliseconds + * since midnight at the beginning of 01 January, 1970 UTC. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetDateValue(JSVM_Env env, + JSVM_Value value, + double* result); + +/** + * @brief This API returns the C boolean primitive equivalent of the given JavaScript Boolean. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript Boolean. + * @param result: C boolean primitive equivalent of the given JavaScript Boolean. + * @return Returns JSVM_OK if the API succeeded. + * If a non-boolean JSVM_Value is passed in it returns JSVM_BOOLEAN_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueBool(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief This API returns the C double primitive equivalent of the given JavaScript number. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript number. + * @param result: C double primitive equivalent of the given JavaScript number. + * @return Returns JSVM_OK if the API succeeded. + * If a non-number JSVM_Value is passed in it returns JSVM_NUMBER_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueDouble(JSVM_Env env, + JSVM_Value value, + double* result); + +/** + * @brief This API returns the C int64_t primitive equivalent of the given JavaScript BigInt. + * If needed it will truncate the value, setting lossless to false. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript BigInt. + * @param result: C int64_t primitive equivalent of the given JavaScript BigInt. + * @param lossless: Indicates whether the BigInt value was converted losslessly. + * @return Returns JSVM_OK if the API succeeded. If a non-BigInt is passed in it returns JSVM_BIGINT_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueBigintInt64(JSVM_Env env, + JSVM_Value value, + int64_t* result, + bool* lossless); + +/** + * @brief This API returns the C uint64_t primitive equivalent of the given JavaScript BigInt. + * If needed it will truncate the value, setting lossless to false. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript BigInt. + * @param result: C uint64_t primitive equivalent of the given JavaScript BigInt. + * @param lossless: Indicates whether the BigInt value was converted losslessly. + * @return Returns JSVM_OK if the API succeeded. If a non-BigInt is passed in it returns JSVM_BIGINT_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueBigintUint64(JSVM_Env env, + JSVM_Value value, + uint64_t* result, + bool* lossless); + +/** + * @brief This API converts a single BigInt value into a sign bit, 64-bit little-endian array, and the number + * of elements in the array. signBit and words may be both set to NULL, in order to get only wordCount. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript BigInt. + * @param signBit: Integer representing if the JavaScript BigInt is positive or negative. + * @param wordCount: Must be initialized to the length of the words array. Upon return, it will be set to + * the actual number of words that would be needed to store this BigInt. + * @param words: Pointer to a pre-allocated 64-bit word array. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueBigintWords(JSVM_Env env, + JSVM_Value value, + int* signBit, + size_t* wordCount, + uint64_t* words); + +/** + * @brief This API retrieves the external data pointer that was previously passed to OH_JSVM_CreateExternal(). + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript external value. + * @param result: Pointer to the data wrapped by the JavaScript external value. + * @return Returns JSVM_OK if the API succeeded. If a non-external JSVM_Value is passed in it returns JSVM_INVALID_ARG. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueExternal(JSVM_Env env, + JSVM_Value value, + void** result); + +/** + * @brief This API returns the C int32 primitive equivalent of the given JavaScript number. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript number. + * @param result: C int32 primitive equivalent of the given JavaScript number. + * @return Returns JSVM_OK if the API succeeded. If a non-number JSVM_Value is passed in JSVM_NUMBER_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueInt32(JSVM_Env env, + JSVM_Value value, + int32_t* result); + +/** + * @brief This API returns the C int64 primitive equivalent of the given JavaScript number. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript number. + * @param result: C int64 primitive equivalent of the given JavaScript number. + * @return Returns JSVM_OK if the API succeeded. If a non-number JSVM_Value is passed in JSVM_NUMBER_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueInt64(JSVM_Env env, + JSVM_Value value, + int64_t* result); + +/** + * @brief This API returns the ISO-8859-1-encoded string corresponding the value passed in. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript string. + * @param buf: Buffer to write the ISO-8859-1-encoded string into. If NULL is passed in, the + * length of the string in bytes and excluding the null terminator is returned in result. + * @param bufsize: Size of the destination buffer. When this value is insufficient, the returned string + * is truncated and null-terminated. + * @param result: Number of bytes copied into the buffer, excluding the null terminator. + * @return Returns JSVM_OK if the API succeeded. If a non-number JSVM_Value is passed in JSVM_NUMBER_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueStringLatin1(JSVM_Env env, + JSVM_Value value, + char* buf, + size_t bufsize, + size_t* result); + +/** + * @brief This API returns the UTF8-encoded string corresponding the value passed in. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript string. + * @param buf: Buffer to write the UTF8-encoded string into. If NULL is passed in, the length + * of the string in bytes and excluding the null terminator is returned in result. + * @param bufsize: Size of the destination buffer. When this value is insufficient, the returned + * string is truncated and null-terminated. + * @param result: Number of bytes copied into the buffer, excluding the null terminator. + * @return Returns JSVM_OK if the API succeeded. If a non-number JSVM_Value is passed in JSVM_NUMBER_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueStringUtf8(JSVM_Env env, + JSVM_Value value, + char* buf, + size_t bufsize, + size_t* result); + +/** + * @brief This API returns the UTF16-encoded string corresponding the value passed in. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript string. + * @param buf: Buffer to write the UTF16-LE-encoded string into. If NULL is passed in, + * the length of the string in 2-byte code units and excluding the null terminator is returned. + * @param bufsize: Size of the destination buffer. When this value is insufficient, + * the returned string is truncated and null-terminated. + * @param result: Number of 2-byte code units copied into the buffer, excluding the null terminator. + * @return Returns JSVM_OK if the API succeeded. If a non-number JSVM_Value is passed in JSVM_NUMBER_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueStringUtf16(JSVM_Env env, + JSVM_Value value, + char16_t* buf, + size_t bufsize, + size_t* result); + +/** + * @brief This API returns the C primitive equivalent of the given JSVM_Value as a uint32_t. + * + * @param env: The environment that the API is invoked under. + * @param value: JSVM_Value representing JavaScript number. + * @param result: C primitive equivalent of the given JSVM_Value as a uint32_t. + * @return Returns JSVM_OK if the API succeeded. + * If a non-number JSVM_Value is passed in it returns JSVM_NUMBER_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetValueUint32(JSVM_Env env, + JSVM_Value value, + uint32_t* result); + +/** + * @brief This API is used to return the JavaScript singleton object that is used to represent the given boolean value. + * + * @param env: The environment that the API is invoked under. + * @param value: The value of the boolean to retrieve. + * @param result: JSVM_Value representing JavaScript Boolean singleton to retrieve. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetBoolean(JSVM_Env env, + bool value, + JSVM_Value* result); + +/** + * @brief This API returns the global object. + * + * @param env: The environment that the API is invoked under. + * @param result: JSVM_Value representing JavaScript global object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetGlobal(JSVM_Env env, + JSVM_Value* result); + +/** + * @brief This API returns the null object. + * + * @param env: The environment that the API is invoked under. + * @param result: JSVM_Value representing JavaScript null object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetNull(JSVM_Env env, + JSVM_Value* result); + +/** + * @brief This API returns the Undefined object. + * + * @param env: The environment that the API is invoked under. + * @param result: JSVM_Value representing JavaScript Undefined value. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetUndefined(JSVM_Env env, + JSVM_Value* result); + +/** + * @brief This API implements the abstract operation ToBoolean() + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to coerce. + * @param result: JSVM_Value representing the coerced JavaScript Boolean. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CoerceToBool(JSVM_Env env, + JSVM_Value value, + JSVM_Value* result); + +/** + * @brief This API implements the abstract operation ToNumber() as defined. This + * function potentially runs JS code if the passed-in value is an object. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to coerce. + * @param result: JSVM_Value representing the coerced JavaScript number. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CoerceToNumber(JSVM_Env env, + JSVM_Value value, + JSVM_Value* result); + +/** + * @brief This API implements the abstract operation ToObject(). + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to coerce. + * @param result: JSVM_Value representing the coerced JavaScript Object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CoerceToObject(JSVM_Env env, + JSVM_Value value, + JSVM_Value* result); + +/** + * @brief This API implements the abstract operation ToString().This + * function potentially runs JS code if the passed-in value is an object. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to coerce. + * @param result: JSVM_Value representing the coerced JavaScript string. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CoerceToString(JSVM_Env env, + JSVM_Value value, + JSVM_Value* result); + +/** + * @brief This API represents behavior similar to invoking the typeof Operator + * on the object as defined. However, there are some differences:It has support + * for detecting an External value.It detects null as a separate type, while + * ECMAScript typeof would detect object.If value has a type that is invalid, + * an error is returned. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value whose type to query. + * @param result: The type of the JavaScript value. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_Typeof(JSVM_Env env, + JSVM_Value value, + JSVM_ValueType* result); + +/** + * @brief This API represents invoking the instanceof Operator on the object. + * + * @param env: The environment that the API is invoked under. + * @param object: The JavaScript value to check. + * @param constructor: The JavaScript function object of the constructor function + * to check against. + * @param result: Boolean that is set to true if object instanceof constructor is true. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_Instanceof(JSVM_Env env, + JSVM_Value object, + JSVM_Value constructor, + bool* result); + +/** + * @brief This API represents invoking the IsArray operation on the object + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param result: Whether the given object is an array. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsArray(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief This API checks if the Object passed in is an array buffer. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param result: Whether the given object is an ArrayBuffer. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsArraybuffer(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief This API checks if the Object passed in is a date. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param result: Whether the given JSVM_Value represents a JavaScript Date object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsDate(JSVM_Env env, + JSVM_Value value, + bool* isDate); + +/** + * @brief This API checks if the Object passed in is a typed array. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param result: Whether the given JSVM_Value represents a TypedArray. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsTypedarray(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief This API checks if the Object passed in is a DataView. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param result: Whether the given JSVM_Value represents a DataView. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsDataview(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief This API represents the invocation of the Strict Equality algorithm. + * Returns true only when both the type and value are equal. + * + * @param env: The environment that the API is invoked under. + * @param lhs: The JavaScript value to check. + * @param rhs: The JavaScript value to check against. + * @param result: Whether the two JSVM_Value objects are equal. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_StrictEquals(JSVM_Env env, + JSVM_Value lhs, + JSVM_Value rhs, + bool* result); + +/** + * @brief This API represents the invocation of the Relaxed Equality algorithm. + * Returns true as long as the values are equal, regardless of type. + * + * @param env: The environment that the API is invoked under. + * @param lhs: The JavaScript value to check. + * @param rhs: The JavaScript value to check against. + * @param result: Whether the two JSVM_Value objects are relaxed equal. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_Equals(JSVM_Env env, + JSVM_Value lhs, + JSVM_Value rhs, + bool* result); + +/** + * @brief This API represents the invocation of the ArrayBuffer detach operation. + * + * @param env: The environment that the API is invoked under. + * @param arraybuffer: The JavaScript ArrayBuffer to be detached. + * @return Returns JSVM_OK if the API succeeded.If a non-detachable ArrayBuffer + * is passed in it returns JSVM_DETACHABLE_ARRAYBUFFER_EXPECTED. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DetachArraybuffer(JSVM_Env env, + JSVM_Value arraybuffer); + +/** + * @brief This API represents the invocation of the ArrayBuffer IsDetachedBuffer operation. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript ArrayBuffer to be checked. + * @param result: Whether the arraybuffer is detached. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsDetachedArraybuffer(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief This API returns the names of the enumerable properties of object as an array of + * strings. The properties of object whose key is a symbol will not be included. + * + * @param env: The environment that the API is invoked under. + * @param object: The object from which to retrieve the properties. + * @param result: A JSVM_Value representing an array of JavaScript values that represent + * the property names of the object. The API can be used to iterate over result using + * OH_JSVM_GetArrayLength and OH_JSVM_GetElement. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetPropertyNames(JSVM_Env env, + JSVM_Value object, + JSVM_Value* result); + +/** + * @brief This API returns an array containing the names of the available properties + * of this object. + * + * @param env: The environment that the API is invoked under. + * @param object: The object from which to retrieve the properties. + * @param keyMode: Whether to retrieve prototype properties as well. + * @param keyFilter: Which properties to retrieve (enumerable/readable/writable). + * @param keyConversion: Whether to convert numbered property keys to strings. + * @param result: result: A JSVM_Value representing an array of JavaScript values + * that represent the property names of the object. OH_JSVM_GetArrayLength and + * OH_JSVM_GetElement can be used to iterate over result. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetAllPropertyNames(JSVM_Env env, + JSVM_Value object, + JSVM_KeyCollectionMode keyMode, + JSVM_KeyFilter keyFilter, + JSVM_KeyConversion keyConversion, + JSVM_Value* result); + +/** + * @brief This API set a property on the Object passed in. + * + * @param env: The environment that the API is invoked under. + * @param object: The object on which to set the property. + * @param key: The name of the property to set. + * @param value: The property value. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_SetProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + JSVM_Value value); + +/** + * @brief This API gets the requested property from the Object passed in. + * + * @param env: The environment that the API is invoked under. + * @param object: The object from which to retrieve the property. + * @param key: The name of the property to retrieve. + * @param result: The value of the property. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + JSVM_Value* result); + +/** + * @brief This API checks if the Object passed in has the named property. + * + * @param env: The environment that the API is invoked under. + * @param object: The object to query. + * @param key: The name of the property whose existence to check. + * @param result: Whether the property exists on the object or not. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_HasProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + bool* result); + +/** + * @brief This API attempts to delete the key own property from object. + * + * @param env: The environment that the API is invoked under. + * @param object: The object to query. + * @param key: The name of the property to delete. + * @param result: Whether the property deletion succeeded or not. result + * can optionally be ignored by passing NULL. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DeleteProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + bool* result); + +/** + * @brief This API checks if the Object passed in has the named own property. + * key must be a string or a symbol, or an error will be thrown. JSVM-API will + * not perform any conversion between data types. + * + * @param env: The environment that the API is invoked under. + * @param object: The object to query. + * @param key: The name of the own property whose existence to check. + * @param result: Whether the own property exists on the object or not. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_HasOwnProperty(JSVM_Env env, + JSVM_Value object, + JSVM_Value key, + bool* result); + +/** + * @brief This method is equivalent to calling OH_JSVM_SetProperty with + * a JSVM_Value created from the string passed in as utf8Name. + * + * @param env: The environment that the API is invoked under. + * @param object: The object on which to set the property. + * @param utf8Name: The name of the property to set. + * @param value: The property value. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_SetNamedProperty(JSVM_Env env, + JSVM_Value object, + const char* utf8name, + JSVM_Value value); + +/** + * @brief This method is equivalent to calling OH_JSVM_SetProperty with + * a JSVM_Value created from the string passed in as utf8Name. + * + * @param env: The environment that the API is invoked under. + * @param object: The object from which to retrieve the property. + * @param utf8Name: The name of the property to get. + * @param result: The value of the property. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetNamedProperty(JSVM_Env env, + JSVM_Value object, + const char* utf8name, + JSVM_Value* result); + +/** + * @brief This method is equivalent to calling OH_JSVM_SetProperty with + * a JSVM_Value created from the string passed in as utf8Name. + * + * @param env: The environment that the API is invoked under. + * @param object: The object to query. + * @param utf8Name: The name of the property whose existence to check. + * @param result: Whether the property exists on the object or not. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_HasNamedProperty(JSVM_Env env, + JSVM_Value object, + const char* utf8name, + bool* result); + +/** + * @brief This API sets an element on the Object passed in. + * + * @param env: The environment that the API is invoked under. + * @param object: The object from which to set the properties. + * @param index: The index of the property to set. + * @param value: The property value. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_SetElement(JSVM_Env env, + JSVM_Value object, + uint32_t index, + JSVM_Value value); + +/** + * @brief This API gets the element at the requested index. + * + * @param env: The environment that the API is invoked under. + * @param object: The object from which to retrieve the property. + * @param index: The index of the property to get. + * @param result: The value of the property. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetElement(JSVM_Env env, + JSVM_Value object, + uint32_t index, + JSVM_Value* result); + +/** + * @brief This API returns if the Object passed in has an element + * at the requested index. + * + * @param env: The environment that the API is invoked under. + * @param object: The object to query. + * @param index: The index of the property whose existence to check. + * @param result: Whether the property exists on the object or not. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_HasElement(JSVM_Env env, + JSVM_Value object, + uint32_t index, + bool* result); + +/** + * @brief This API attempts to delete the specified index from object. + * + * @param env: The environment that the API is invoked under. + * @param object: The object to query. + * @param index: The index of the property to delete. + * @param result: Whether the element deletion succeeded or not. result + * can optionally be ignored by passing NULL. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DeleteElement(JSVM_Env env, + JSVM_Value object, + uint32_t index, + bool* result); + +/** + * @brief This method allows the efficient definition of multiple properties + * on a given object. The properties are defined using property descriptors. + * Given an array of such property descriptors, this API will set the properties + * on the object one at a time, as defined by DefineOwnProperty(). + * + * @param env: The environment that the API is invoked under. + * @param object: The object from which to retrieve the properties. + * @param propertyCount: The number of elements in the properties array. + * @param properties: The array of property descriptors. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DefineProperties(JSVM_Env env, + JSVM_Value object, + size_t propertyCount, + const JSVM_PropertyDescriptor* properties); + +/** + * @brief This method freezes a given object. This prevents new properties + * from being added to it, existing properties from being removed, prevents + * changing the enumerability, configurability, or writability of existing + * properties, and prevents the values of existing properties from being changed. + * It also prevents the object's prototype from being changed. + * + * @param env: The environment that the API is invoked under. + * @param object: The object to freeze. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ObjectFreeze(JSVM_Env env, + JSVM_Value object); + +/** + * @brief This method seals a given object. This prevents new properties + * from being added to it, as well as marking all existing properties as non-configurable. + * + * @param env: The environment that the API is invoked under. + * @param object: The object to seal. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ObjectSeal(JSVM_Env env, + JSVM_Value object); + +/** + * @brief This method allows a JavaScript function object to be called from + * a native add-on. This is the primary mechanism of calling back from the + * add-on's native code into JavaScript. + * + * @param env: The environment that the API is invoked under. + * @param recv: The this value passed to the called function. + * @param func: JSVM_Value representing the JavaScript function to be invoked. + * @param argc: The count of elements in the argv array. + * @param argv: Array of JSVM_values representing JavaScript values passed in as arguments to the function. + * @param result: JSVM_Value representing the JavaScript object returned. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CallFunction(JSVM_Env env, + JSVM_Value recv, + JSVM_Value func, + size_t argc, + const JSVM_Value* argv, + JSVM_Value* result); + + /** + * @brief This API allows an add-on author to create a function object in native + * code. This is the primary mechanism to allow calling into the add-on's native + * code from JavaScript.The newly created function is not automatically visible + * from script after this call. Instead, a property must be explicitly set on any + * object that is visible to JavaScript, in order for the function to be accessible + * from script. + * + * @param env: The environment that the API is invoked under. + * @param utf8Name: Optional name of the function encoded as UTF8. This is visible + * within JavaScript as the new function object's name property. + * @param length: The length of the utf8name in bytes, or JSVM_AUTO_LENGTH if it + * is null-terminated. + * @param cb: The native function which should be called when this function + * object is invoked and data. JSVM_Callback provides more details. + * @param result: JSVM_Value representing the JavaScript function object for the newly + * created function. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateFunction(JSVM_Env env, + const char* utf8name, + size_t length, + JSVM_Callback cb, + JSVM_Value* result); + + /** + * @brief This method is used within a callback function to retrieve details about + * the call like the arguments and the this pointer from a given callback info. + * + * @param env: The environment that the API is invoked under. + * @param cbinfo: The callback info passed into the callback function. + * @param argc: Specifies the length of the provided argv array and receives the + * actual count of arguments. argc can optionally be ignored by passing NULL. + * @param argv: C array of JSVM_values to which the arguments will be copied. If + * there are more arguments than the provided count, only the requested number of + * arguments are copied. If there are fewer arguments provided than claimed, the + * rest of argv is filled with JSVM_Value values that represent undefined. argv + * can optionally be ignored by passing NULL. + * @param thisArg: Receives the JavaScript this argument for the call. thisArg + * can optionally be ignored by passing NULL. + * @param data: Receives the data pointer for the callback. data can optionally + * be ignored by passing NULL. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetCbInfo(JSVM_Env env, + JSVM_CallbackInfo cbinfo, + size_t* argc, + JSVM_Value* argv, + JSVM_Value* thisArg, + void** data); + +/** + * @brief This API returns the new.target of the constructor call. If the + * current callback is not a constructor call, the result is NULL. + * + * @param env: The environment that the API is invoked under. + * @param cbinfo: The callback info passed into the callback function. + * @param result: The new.target of the constructor call. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetNewTarget(JSVM_Env env, + JSVM_CallbackInfo cbinfo, + JSVM_Value* result); + +/** + * @brief his method is used to instantiate a new JavaScript value using + * a given JSVM_Value that represents the constructor for the object. + * + * @param env: The environment that the API is invoked under. + * @param constructor: JSVM_Value representing the JavaScript function to be invoked as a constructor. + * @param argc: The count of elements in the argv array. + * @param argv: Array of JavaScript values as JSVM_Value representing the arguments to + * the constructor. If argc is zero this parameter may be omitted by passing in NULL. + * @param result: JSVM_Value representing the JavaScript object returned, which + * in this case is the constructed object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_NewInstance(JSVM_Env env, + JSVM_Value constructor, + size_t argc, + const JSVM_Value* argv, + JSVM_Value* result); + +/** + * @brief When wrapping a C++ class, the C++ constructor callback passed via constructor + * should be a static method on the class that calls the actual class constructor, then + * wraps the new C++ instance in a JavaScript object, and returns the wrapper object. + * + * @param env: The environment that the API is invoked under. + * @param utf8name: Name of the JavaScript constructor function. For clarity, it is + * recommended to use the C++ class name when wrapping a C++ class. + * @param length: The length of the utf8name in bytes, or JSVM_AUTO_LENGTH if it + * is null-terminated. + * @param constructor: Struct include callback function that handles constructing instances of the class. + * When wrapping a C++ class, this method must be a static member with the JSVM_Callback.callback + * signature. A C++ class constructor cannot be used. + * Include Optional data to be passed to the constructor callback as the data + * property of the callback info. JSVM_Callback provides more details. + * @param propertyCount: Number of items in the properties array argument. + * @param properties: Array of property descriptors describing static and instance data + * properties, accessors, and methods on the class See JSVM_PropertyDescriptor. + * @param result: A JSVM_Value representing the constructor function for the class. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DefineClass(JSVM_Env env, + const char* utf8name, + size_t length, + JSVM_Callback constructor, + size_t propertyCount, + const JSVM_PropertyDescriptor* properties, + JSVM_Value* result); + +/** + * @brief Wraps a native instance in a JavaScript object. The native instance can + * be retrieved later using OH_JSVM_Unwrap(). + * + * @param env: The environment that the API is invoked under. + * @param jsObject: The JavaScript object that will be the wrapper for the native object. + * @param nativeObject: The native instance that will be wrapped in the JavaScript object. + * @param finalizeCb: Optional native callback that can be used to free the native instance + * when the JavaScript object has been garbage-collected. + * @param finalizeHint: Optional contextual hint that is passed to the finalize callback. + * properties, accessors, and methods on the class See JSVM_PropertyDescriptor. + * @param result: Optional reference to the wrapped object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_Wrap(JSVM_Env env, + JSVM_Value jsObject, + void* nativeObject, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Ref* result); + +/** + * @brief When JavaScript code invokes a method or property accessor on the class, the corresponding + * JSVM_Callback is invoked. If the callback is for an instance method or accessor, then the this + * argument to the callback is the wrapper object; the wrapped C++ instance that is the target of + * the call can be obtained then by calling OH_JSVM_Unwrap() on the wrapper object. + * + * @param env: The environment that the API is invoked under. + * @param jsObject: The object associated with the native instance. + * @param result: Pointer to the wrapped native instance. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_Unwrap(JSVM_Env env, + JSVM_Value jsObject, + void** result); + +/** + * @brief Retrieves a native instance that was previously wrapped in the JavaScript object jsObject + * using OH_JSVM_Wrap() and removes the wrapping. If a finalize callback was associated with the wrapping, + * it will no longer be called when the JavaScript object becomes garbage-collected. + * + * @param env: The environment that the API is invoked under. + * @param jsObject: The object associated with the native instance. + * @param result: Pointer to the wrapped native instance. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_RemoveWrap(JSVM_Env env, + JSVM_Value jsObject, + void** result); + +/** + * @brief Associates the value of the typeTag pointer with the JavaScript object or external. + * OH_JSVM_CheckObjectTypeTag() can then be used to compare the tag that was attached to the + * object with one owned by the addon to ensure that the object has the right type. + * If the object already has an associated type tag, this API will return JSVM_INVALID_ARG. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript object or external to be marked. + * @param typeTag: The tag with which the object is to be marked. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_TypeTagObject(JSVM_Env env, + JSVM_Value value, + const JSVM_TypeTag* typeTag); + +/** + * @brief Compares the pointer given as typeTag with any that can be found on js object. + * If no tag is found on js object or, if a tag is found but it does not match typeTag, + * then result is set to false. If a tag is found and it matches typeTag, then result is set to true. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript object or external whose type tag to examine. + * @param typeTag: The tag with which to compare any tag found on the object. + * @param result: Whether the type tag given matched the type tag on the object. false is also returned + * if no type tag was found on the object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CheckObjectTypeTag(JSVM_Env env, + JSVM_Value value, + const JSVM_TypeTag* typeTag, + bool* result); + +/** + * @brief This API can be called multiple times on a single JavaScript object. + * + * @param env: The environment that the API is invoked under. + * @param jsObject: The JavaScript object to which the native data will be attached. + * @param finalizeData: Optional data to be passed to finalizeCb. + * @param finalizeCb: Native callback that will be used to free the native data when the + * JavaScript object has been garbage-collected. JSVM_Finalize provides more details. + * @param finalizeHint: Optional contextual hint that is passed to the finalize callback. + * @param result: Optional reference to the JavaScript object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_AddFinalizer(JSVM_Env env, + JSVM_Value jsObject, + void* finalizeData, + JSVM_Finalize finalizeCb, + void* finalizeHint, + JSVM_Ref* result); + +/** + * @brief This API returns the highest JSVM-API version supported by the JSVM runtime. + * + * JSVM-API is planned to be additive such that newer releases of JSVM may support additional + * API functions. In order to allow an addon to use a newer function when running with versions + * of JSVM that support it, while providing fallback behavior when running with JSVM + * versions that don't support it. + * @param env: The environment that the API is invoked under. + * @param result: The highest version of JSVM-API supported. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetVersion(JSVM_Env env, + uint32_t* result); + +/** + * @brief Return information of the VM. + * + * @param result: The information of the VM. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetVMInfo(JSVM_VMInfo* result); + +/** + * @brief This function gives V8 an indication of the amount of externally + * allocated memory that is kept alive by JavaScript objects (i.e. a JavaScript + * object that points to its own memory allocated by a native addon). Registering + * externally allocated memory will trigger global garbage collections more often + * than it would otherwise. + * + * @param env: The environment that the API is invoked under. + * @param changeInBytes: The change in externally allocated memory that is kept + * alive by JavaScript objects. + * @param result: The adjusted value + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_AdjustExternalMemory(JSVM_Env env, + int64_t changeInBytes, + int64_t* result); + +/** + * @brief This function notifies the VM that the system is running low on memory + * and optionally triggers a garbage collection. + * + * @param env: The environment that the API is invoked under. + * @param level: The memory pressure level set to the current VM. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_MemoryPressureNotification(JSVM_Env env, + JSVM_MemoryPressureLevel level); + +/** + * @brief This API creates a deferred object and a JavaScript promise. + * + * @param env: The environment that the API is invoked under. + * @param deferred: A newly created deferred object which can later be + * passed to OH_JSVM_ResolveDeferred() or OH_JSVM_RejectDeferred() to resolve + * resp. reject the associated promise. + * @param promise: The JavaScript promise associated with the deferred object. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreatePromise(JSVM_Env env, + JSVM_Deferred* deferred, + JSVM_Value* promise); + +/** + * @brief This API resolves a JavaScript promise by way of the deferred object with + * which it is associated. Thus, it can only be used to resolve JavaScript promises + * for which the corresponding deferred object is available. This effectively means + * that the promise must have been created using OH_JSVM_CreatePromise() and the deferred + * object returned from that call must have been retained in order to be passed to this API. + * + * @param env: The environment that the API is invoked under. + * @param deferred: The deferred object whose associated promise to resolve. + * @param resolution: The value with which to resolve the promise. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ResolveDeferred(JSVM_Env env, + JSVM_Deferred deferred, + JSVM_Value resolution); + +/** + * @brief This API rejects a JavaScript promise by way of the deferred object with + * which it is associated. Thus, it can only be used to reject JavaScript promises + * for which the corresponding deferred object is available. This effectively means + * that the promise must have been created using OH_JSVM_CreatePromise() and the deferred + * object returned from that call must have been retained in order to be passed to this API. + * + * @param env: The environment that the API is invoked under. + * @param deferred: The deferred object whose associated promise to resolve. + * @param rejection: The value with which to reject the promise. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_RejectDeferred(JSVM_Env env, + JSVM_Deferred deferred, + JSVM_Value rejection); + +/** + * @brief This API return indicating whether promise is a native promise object. + * @param env: The environment that the API is invoked under. + * @param value: The value to examine + * @param isPromise: Flag indicating whether promise is a native promise object + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsPromise(JSVM_Env env, + JSVM_Value value, + bool* isPromise); + +/** + * @brief This API parses a JSON string and returns it as value if successful. + * @param env: The environment that the API is invoked under. + * @param jsonString: The string to parse. + * @param result: The parse value if successful. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_JsonParse(JSVM_Env env, + JSVM_Value jsonString, + JSVM_Value* result); + +/** + * @brief This API stringifies the object and returns it as string if successful. + * @param env: The environment that the API is invoked under. + * @param jsonObject: The object to stringify. + * @param result: The string if successfully stringified. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_JsonStringify(JSVM_Env env, + JSVM_Value jsonObject, + JSVM_Value* result); + +/** + * @brief This API create the startup snapshot of the VM. + * @param vm: The environment that the API is invoked under. + * @param contextCount: The object to stringify. + * @param contexts: The array of contexts to add to the snapshot. + * @param blobData: The snapshot data. + * @param blobSize: The size of snapshot data. + * @return Returns JSVM_OK if the API succeeded. + * @since 11 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateSnapshot(JSVM_VM vm, + size_t contextCount, + const JSVM_Env* contexts, + const char** blobData, + size_t* blobSize); + +/** + * @brief This function returns a set of statistics data of the heap of the VM. + * + * @param vm: The VM whose heap statistics are returned. + * @param result: The heap statistics data. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_GetHeapStatistics(JSVM_VM vm, + JSVM_HeapStatistics* result); + +/** + * @brief This function creates and starts a CPU profiler. + * + * @param vm: The VM to start CPU profiler for. + * @param result: The pointer to the CPU profiler. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_StartCpuProfiler(JSVM_VM vm, + JSVM_CpuProfiler* result); + +/** + * @brief This function stops the CPU profiler and output to the stream. + * + * @param vm: THe VM to start CPU profiler for. + * @param profiler: The CPU profiler to stop. + * @param stream: The output stream callback for receiving the data. + * @param streamData: Optional data to be passed to the stream callback. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_StopCpuProfiler(JSVM_VM vm, + JSVM_CpuProfiler profiler, + JSVM_OutputStream stream, + void* streamData); + +/** + * @brief This funciton takes the current heap snapshot and output to the stream. + * + * @param vm: The VM whose heap snapshot is taken. + * @param stream: The output stream callback for receiving the data. + * @param streamData: Optional data to be passed to the stream callback. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_TakeHeapSnapshot(JSVM_VM vm, + JSVM_OutputStream stream, + void* streamData); + +/** + * @brief This functiong activates insepctor on host and port. + * + * @param env: The environment that the API is invoked under. + * @param host: The host to listen to for inspector connections. + * @param port: The port to listen to for inspector connections. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_OpenInspector(JSVM_Env env, + const char* host, + uint16_t port); + +/** + * @brief This function attempts to close all remaining inspector connections. + * + * @param env: The environment that the API is invoked under. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CloseInspector(JSVM_Env env); + +/** + * @brief This function will block until a client (existing or connected later) + * has sent Runtime.runIfWaitingForDebugger command. + * + * @param env: The environment that the API is invoked under. + * @param breakNextLine: Whether break on the next line of JavaScript code. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_WaitForDebugger(JSVM_Env env, + bool breakNextLine); + +/** + * @brief When packaging C++classes, the C++constructor callback passed through the constructor + * triggers the corresponding callback function when getter, setter, call, and other + * behaviors occur on the instance object, handles the user's custom behavior, and then wraps + * the new C++instance in a JavaScript object and returns the wrapper object. + * + * @param env: The environment that the API is invoked under. + * @param utf8name: Name of the JavaScript constructor function. For clarity, it is + * recommended to use the C++ class name when wrapping a C++ class. + * @param length: The length of the utf8name in bytes, or JSVM_AUTO_LENGTH if it + * is null-terminated. + * @param constructor: Struct include callback function that handles constructing instances of the class. + * When wrapping a C++ class, this method must be a static member with the JSVM_Callback.callback + * signature. A C++ class constructor cannot be used. + * Include Optional data to be passed to the constructor callback as the data + * property of the callback info. JSVM_Callback provides more details. + * @param propertyCount: Number of items in the properties array argument. + * @param properties: Array of property descriptors describing static and instance data + * properties, accessors, and methods on the class See JSVM_PropertyDescriptor. + * @param propertyHandlerCfg: The instance object triggers the corresponding callback function. + * @param callAsFunctionCallback: Calling an instance object as a function will trigger this callback. + * @param result: A JSVM_Value representing the constructor function for the class. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_DefineClassWithPropertyHandler(JSVM_Env env, + const char* utf8name, + size_t length, + JSVM_Callback constructor, + size_t propertyCount, + const JSVM_PropertyDescriptor* properties, + JSVM_PropertyHandlerCfg propertyHandlerCfg, + JSVM_Callback callAsFunctionCallback, + JSVM_Value* result); + +/** + * @brief Determines whether the current thread holds the lock for the specified environment. + * Only threads that hold locks can use the environment. + * + * @param env: The environment that the API is invoked under. + * @param isLocked: Flag indicating whether the current thread holds the lock for the specified environment. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsLocked(JSVM_Env env, + bool* isLocked); + +/** + * @brief Acquire the lock for the specified environment. Only threads that hold locks can use the environment. + * + * @param env: The environment that the API is invoked under. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_AcquireLock(JSVM_Env env); + +/** + * @brief Release the lock for the specified environment. Only threads that hold locks can use the environment. + * + * @param env: The environment that the API is invoked under. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ReleaseLock(JSVM_Env env); + +/** + * @brief Starts the running of the task queue inside the VM. + * This task queue can be executed by an external event loop. + * + * @param env: The VM instance on which to start the task queue. + * @param result: Whether the task queue was successfully started. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_PumpMessageLoop(JSVM_VM vm, + bool* result); + +/** + * @brief Check to see if there are any microtasks waiting in the queue, and if there are, execute them. + * + * @param env: The VM instance on which to check microtasks. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_PerformMicrotaskCheckpoint(JSVM_VM vm); + +/** + * @brief This API checks if the value passed in is callable. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isCallable: Whether the given value is callable. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsCallable(JSVM_Env env, + JSVM_Value value, + bool* isCallable); +/** + * @brief This API checks if the value passed in is undefined. + * This equals to `value === undefined` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isUndefined: Whether the given value is Undefined. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsUndefined(JSVM_Env env, + JSVM_Value value, + bool* isUndefined); + +/** + * @brief This API checks if the value passed in is a null object. + * This equals to `value === null` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isNull: Whether the given value is Null. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsNull(JSVM_Env env, + JSVM_Value value, + bool* isNull); + +/** + * @brief This API checks if the value passed in is either a null or an undefined object. + * This is equivalent to `value == null` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isNullOrUndefined: Whether the given value is Null or Undefined. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsNullOrUndefined(JSVM_Env env, + JSVM_Value value, + bool* isNullOrUndefined); + +/** + * @brief This API checks if the value passed in is a boolean. + * This equals to `typeof value === 'boolean'` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isBoolean: Whether the given value is Boolean. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsBoolean(JSVM_Env env, + JSVM_Value value, + bool* isBoolean); + +/** + * @brief This API checks if the value passed in is a number. + * This equals to `typeof value === 'number'` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isNumber: Whether the given value is Number. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsNumber(JSVM_Env env, + JSVM_Value value, + bool* isNumber); + +/** + * @brief This API checks if the value passed in is a string. + * This equals to `typeof value === 'string'` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isString: Whether the given value is String. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsString(JSVM_Env env, + JSVM_Value value, + bool* isString); + +/** + * @brief This API checks if the value passed in is a symbol. + * This equals to `typeof value === 'symbol'` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isSymbol: Whether the given value is Symbol. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsSymbol(JSVM_Env env, + JSVM_Value value, + bool* isSymbol); + +/** + * @brief This API checks if the value passed in is a function. + * This equals to `typeof value === 'function'` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isFunction: Whether the given value is Function. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsFunction(JSVM_Env env, + JSVM_Value value, + bool* isFunction); + +/** + * @brief This API checks if the value passed in is an object. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isObject: Whether the given value is Object. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsObject(JSVM_Env env, + JSVM_Value value, + bool* isObject); + +/** + * @brief This API checks if the value passed in is a bigInt. + * This equals to `typeof value === 'bigint'` in JS. + * + * @param env: The VM instance on which to check microtasks. + * @param value: The JavaScript value to check. + * @param isBigInt: Whether the given value is BigInt. + * @return Only returns JSVM_OK, because this API will not trigger any exception. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsBigInt(JSVM_Env env, + JSVM_Value value, + bool* isBigInt); + +/** + * @brief This API implements the abstract operation `ToBigInt()`. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to coerce. + * @param result: JSVM_Value representing the coerced JavaScript BigInt. + * @return Returns JSVM_OK if the API succeeded. Returns JSVM_BIGINT_EXPECTED if the + * JavaScript value fails to coerce. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CoerceToBigInt(JSVM_Env env, + JSVM_Value value, + JSVM_Value* result); + +/** + * @brief This API checks if the value passed in is a JavaScript RegExp object. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param result: Whether the given value is RegExp. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsRegExp(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief Creates a function with a given script as its body. + * + * @param env: The environment that the API is invoked under. + * @param funcName: A string containing the function's name. Pass NULL to create an anonymous function. + * @param length: The length of the funcName in bytes, or JSVM_AUTO_LENGTH if it + * is null-terminated. + * @param argc: The count of elements in the argv array. + * @param argv: Array of JSVM_Values representing JavaScript strings passed in as arguments to the function. + * @param script: A JavaScript string containing the script to use as the function's body. + * @param result: JSVM_Value representing the JavaScript function object for the newly + * created function. + * @return Returns JSVM_OK if the API succeeded. Returns JSVM_GENERIC_FAILURE if the input script fails to + * be compiled. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateFunctionWithScript(JSVM_Env env, + const char* funcName, + size_t length, + size_t argc, + const JSVM_Value* argv, + JSVM_Value script, + JSVM_Value* result); + +/** + * @brief This API checks if the value passed in is a constructor. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param isConstructor: Whether the given value is Constructor. + * @return Returns JSVM_OK if the API succeeded. Returns JSVM_INVALID_ARG if the API failed. + * @since 12 + */ +JSVM_Status JSVM_CDECL OH_JSVM_IsConstructor(JSVM_Env env, + JSVM_Value value, + bool* isConstructor); + +/** + * @brief This API returns the JavaScript value of the regular expression + * corresponding to the input. + * The interface may throw an exception. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript string to convert to a regular expression. + * @param flags: Regular expression flag bits. + * @param result: A JSVM_Value representing a JavaScript RegExp. + * @return Only returns JSVM function's result code. + * {@link JSVM_OK } If the API succeeded.\n + * {@link JSVM_INVALID_ARG } If the input parameter is invalid.\n + * {@link JSVM_STRING_EXPECTED } If the value of 'value' is not a string.\n + * {@link JSVM_GENERIC_FAILURE } If create RegExp failed.\n + * {@link JSVM_PENDING_EXCEPTION } If the API throws an exception during runtime.\n + * @since 12 + */ +JSVM_Status JSVM_CDECL OH_JSVM_CreateRegExp(JSVM_Env env, + JSVM_Value value, + JSVM_RegExpFlags flags, + JSVM_Value* result); + +/** + * @brief This API returns a JSVM-API value corresponding to a JavaScript Map type. + * + * @param env: The environment that the API is invoked under. + * @param result: A JSVM_Value representing a JavaScript Map. + * @return Returns JSVM_OK if the API succeeded. Returns JSVM_INVALID_ARG if the API failed. + * @since 12 + */ +JSVM_Status JSVM_CDECL OH_JSVM_CreateMap(JSVM_Env env, JSVM_Value* result); + +/** + * @brief This API checks if the value passed in is a Map. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param isMap: Whether the given value is Map. + * @return Returns JSVM_OK if the API succeeded. Returns JSVM_INVALID_ARG if the API failed. + * @since 12 + */ +JSVM_Status JSVM_CDECL OH_JSVM_IsMap(JSVM_Env env, + JSVM_Value value, + bool* isMap); + +/** + * @brief This API returns a JSVM-API value corresponding to a JavaScript Set type. + * + * @param env: The environment that the API is invoked under. + * @param result: A JSVM_Value representing a JavaScript Set. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateSet(JSVM_Env env, + JSVM_Value* result); + +/** + * @brief This API checks if the value passed in is a Set. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param isSet: Whether the given value is Set. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsSet(JSVM_Env env, + JSVM_Value value, + bool* isSet); + +/** + * @brief This API returns the Object prototype. + * + * @param env: The environment that the API is invoked under. + * @param object: JSVM_Value representing JavaScript Object whose prototype to return. + * @param result: JSVM_Value representing prototype of the given object. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ObjectGetPrototypeOf(JSVM_Env env, + JSVM_Value object, + JSVM_Value* result); + +/** + * @brief This API set the prototype on the Object passed in. + * + * @param env: The environment that the API is invoked under. + * @param object: The object on which to set the prototype. + * @param prototype: The prototype value. + * @return Returns JSVM_OK if the API succeeded. + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ObjectSetPrototypeOf(JSVM_Env env, + JSVM_Value object, + JSVM_Value prototype); + +/** + * @brief This function keep persistently save a JSVM_Script and extend its lifecycle + * beyond the current scope. + * + * @param env: The environment that the API is invoked under. + * @param script: A JavaScript string containing the script to be retained. + * @return Returns JSVM functions result code + * {@link JSVM_OK } if the API succeeded. \n + * {@link JSVM_INVALID_ARG } if the script is empty or already retained. \n + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_RetainScript(JSVM_Env env, JSVM_Script script); + +/** + * @brief This function release the script retained by OH_JSVM_RetainScript + * + * @param env: The environment that the API is invoked under. + * @param script: A JavaScript string containing the script to be retained. + * @return Returns JSVM functions result code + * {@link JSVM_OK } if the API succeeded. \n + * {@link JSVM_INVALID_ARG } if the script is empty or not retained. \n + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ReleaseScript(JSVM_Env env, JSVM_Script script); + +/** + * @brief This function activates insepctor with pid and alias it. + * + * @param env: The environment that the API is invoked under. + * @param pid: A process id to identify the inspector connection. + * @param name: An alias for the inspector that under a specific pid. + * default name is jsvm if a nullptr is passed in. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if the function executed successfully.\n + * Returns {@link JSVM_PENDING_EXCEPTION } if an exception occurs.\n + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_OpenInspectorWithName(JSVM_Env env, + int pid, + const char* name); + +/** + * @brief Compile WebAssembly bytecode into a WebAssembly module. + * If WebAssembly cache provided, deserialization will be performed. + * + * @param env: The environment that the API is invoked under. + * @param wasmBytecode: WebAssembly bytecode. + * @param wasmBytecodeLength: WebAssembly bytecode length in byte. + * @param cacheData: Optional WebAssembly cache. + * @param cacheDataLength: Optional WebAssembly cache length in byte. + * @param cacheRejected: Output parameter representing whether the provided cacheData is rejected. + * @param wasmModule: Output parameter representing compiled WebAssembly module. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if the function executed successfully.\n + * Returns {@link JSVM_INVALID_ARG } if any of env, wasmBytecode is NULL, or data length is invalid.\n + * Returns {@link JSVM_GENERIC_FAILURE } if compile failed.\n + * Returns {@link JSVM_PENDING_EXCEPTION } if an exception occurs.\n + * + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CompileWasmModule(JSVM_Env env, + const uint8_t *wasmBytecode, + size_t wasmBytecodeLength, + const uint8_t *cacheData, + size_t cacheDataLength, + bool *cacheRejected, + JSVM_Value *wasmModule); + +/** + * @brief Compile the function with the specified index in the WebAssembly module + * into the specified optimization level. + * + * @param env: The environment that the API is invoked under. + * @param wasmModule: The WebAssembly module to which the function to compiled belongs. + * @param functionIndex: The index of the function to be compiled, should never be out of range. + * @param optLevel: Optimization level the function will be compiled with. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if the function executed successfully.\n + * Returns {@link JSVM_INVALID_ARG } if env is NULL, or wasmModule is NULL or is not a WebAssembly module.\n + * Returns {@link JSVM_GENERIC_FAILURE } if functionIndex out of range or compile failed.\n + * Returns {@link JSVM_PENDING_EXCEPTION } if an exception occurs.\n + * + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CompileWasmFunction(JSVM_Env env, + JSVM_Value wasmModule, + uint32_t functionIndex, + JSVM_WasmOptLevel optLevel); + +/** + * @brief Check whether the given JSVM_Value is a WebAssembly module. + * + * @param env: The environment that the API is invoked under. + * @param value: The JavaScript value to check. + * @param result: Whether the given value is a WebAssembly module. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if the function executed successfully.\n + * Returns {@link JSVM_INVALID_ARG } if any of the input arguments is NULL.\n + * + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_IsWasmModuleObject(JSVM_Env env, + JSVM_Value value, + bool* result); + +/** + * @brief Create cache for compiled WebAssembly module. + * + * @param env: The environment that the API is invoked under. + * @param wasmModule: The compiled WebAssembly module. + * @param data: Output parameter representing generated WebAssembly module cache. + * @param length: Output parameter representing byte length of generated WebAssembly module cache. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if the function executed successfully.\n + * Returns {@link JSVM_INVALID_ARG } if any of the input arguments is NULL.\n + * Returns {@link JSVM_GENERIC_FAILURE } if create wasm cache failed.\n + * + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_CreateWasmCache(JSVM_Env env, + JSVM_Value wasmModule, + const uint8_t** data, + size_t* length); + +/** + * @brief Release cache data with specified cache type. + * + * @param env: The environment that the API is invoked under. + * @param cacheData: The cache data to be released, double free is undefined behaviors. + * @param cacheType: The type of cache data. + * @return Returns JSVM funtions result code. + * Returns {@link JSVM_OK } if the function executed successfully.\n + * Returns {@link JSVM_INVALID_ARG } if any of the pointer arguments is NULL or cacheType is illegal.\n + * + * @since 12 + */ +JSVM_EXTERN JSVM_Status OH_JSVM_ReleaseCache(JSVM_Env env, + const uint8_t* cacheData, + JSVM_CacheType cacheType); + +EXTERN_C_END + +/** @} */ +#endif /* ARK_RUNTIME_JSVM_JSVM_H */ + diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm_types.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm_types.h new file mode 100644 index 0000000000..7abb16a3f1 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm_types.h @@ -0,0 +1,771 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ARK_RUNTIME_JSVM_JSVM_TYPE_H +#define ARK_RUNTIME_JSVM_JSVM_TYPE_H + +/** + * @addtogroup JSVM + * @{ + * + * @brief Provides the standard JavaScript engine capabilities. + * + * Provides API to Provide independent, standard, and complete JavaScript engine capabilities for developers, + * including managing the engine lifecycle, compiling and running JS code, implementing JS/C++ cross language calls, + * and taking snapshots. + * + * @since 11 + */ + +/** + * @file jsvm_types.h + * + * @brief Provides the JSVM API type define. + * + * Provides API to Provide independent, standard, and complete JavaScript engine capabilities for developers, + * including managing the engine lifecycle, compiling and running JS code, implementing JS/C++ cross language calls, + * and taking snapshots. + * @library libjsvm.so + * @syscap SystemCapability.ArkCompiler.JSVM + * @since 11 + */ + +#include // NOLINT(modernize-deprecated-headers) +#include // NOLINT(modernize-deprecated-headers) +#include // NOLINT(modernize-deprecated-headers) + +#if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900) +typedef uint16_t char16_t; +#endif + +#ifndef JSVM_CDECL +#ifdef _WIN32 +#define JSVM_CDECL __cdecl +#else +#define JSVM_CDECL +#endif +#endif + +/** + * @brief To represent a JavaScript VM instance. + * + * @since 11 + */ +typedef struct JSVM_VM__* JSVM_VM; + +/** + * @brief To represent a JavaScript VM scope. + * + * @since 11 + */ +typedef struct JSVM_VMScope__* JSVM_VMScope; + +/** + * @brief To represent a JavaScript VM environment scope. + * + * @since 11 + */ +typedef struct JSVM_EnvScope__* JSVM_EnvScope; + +/** + * @brief To represent a JavaScript code. + * + * @since 11 + */ +typedef struct JSVM_Script__* JSVM_Script; + +/** + * @brief To represent a JavaScript VM instance. + * + * @since 11 + */ +typedef struct JSVM_Env__* JSVM_Env; + +/** + * @brief To represent a JavaScript profiler. + * + * @since 12 + */ +typedef struct JSVM_CpuProfiler__* JSVM_CpuProfiler; + +/** + * @brief To represent a JavaScript VM environment. + * + * @since 11 + */ +typedef struct JSVM_Value__* JSVM_Value; + +/** + * @brief To represent a JavaScript value references. + * + * @since 11 + */ +typedef struct JSVM_Ref__* JSVM_Ref; + +/** + * @brief To represent a JavaScript VM handle scope. + * + * @since 11 + */ +typedef struct JSVM_HandleScope__* JSVM_HandleScope; + +/** + * @brief To represent a JavaScript VM escapable handle scope. + * + * @since 11 + */ +typedef struct JSVM_EscapableHandleScope__* JSVM_EscapableHandleScope; + +/** + * @brief To represent a JavaScript VM callback additional information. + * + * @since 11 + */ +typedef struct JSVM_CallbackInfo__* JSVM_CallbackInfo; + +/** + * @brief To represent a JavaScript VM value deferred. + * + * @since 11 + */ +typedef struct JSVM_Deferred__* JSVM_Deferred; + + +/** + * @brief Callback function pointer and data for user-provided native function which are to exposed to js via JSVM-API. + * + * @since 11 + */ +typedef struct { + JSVM_Value(JSVM_CDECL* callback)(JSVM_Env env, + JSVM_CallbackInfo info); + void* data; +} JSVM_CallbackStruct; + +/** + * @brief Function pointer type for user-provided native function which are to exposed to js via JSVM-API. + * + * @since 11 + */ +typedef JSVM_CallbackStruct* JSVM_Callback; + +/** + * @brief Function pointer type for add-on provided function that allow the user to be notified. + * + * @since 11 + */ +typedef void(JSVM_CDECL* JSVM_Finalize)(JSVM_Env env, + void* finalizeData, + void* finalizeHint); + +/** + * @brief Function pointer type for callback of ASCII output stream. + * + * @since 12 + */ +typedef bool(JSVM_CDECL* JSVM_OutputStream)(const char* data, + int size, + void* streamData); + +/** + * @brief JSVM_PropertyAttributes are flag used to control the behavior of properties set on a js object. + * + * @since 11 + */ +typedef enum { + /** No explicit attributes are set on the property. */ + JSVM_DEFAULT = 0, + /** The property is writable. */ + JSVM_WRITABLE = 1 << 0, + /** The property is enumeable. */ + JSVM_ENUMERABLE = 1 << 1, + /** The property is configurable. */ + JSVM_CONFIGURABLE = 1 << 2, + /** Used to mark the receiver of a native method need not be checked. + * If JSVM_NO_RECEIVER_CHECK is not set, the method only accept instance of the defined class as receiver, + * Otherwise Exception "Type Error: Illegal Ivocation" will be throw into JSVM. + */ + JSVM_NO_RECEIVER_CHECK = 1 << 3, + /** Used with OH_JSVM_DefineClass to distinguish static properties from instance properties. */ + JSVM_STATIC = 1 << 10, + /** Default for class methods. */ + JSVM_DEFAULT_METHOD = JSVM_WRITABLE | JSVM_CONFIGURABLE, + /** Class method with no receiver check*/ + JSVM_METHOD_NO_RECEIVER_CHECK = JSVM_DEFAULT_METHOD | JSVM_NO_RECEIVER_CHECK, + /** Default for object properties, like in JS obj[prop]. */ + JSVM_DEFAULT_JSPROPERTY = JSVM_WRITABLE | JSVM_ENUMERABLE | JSVM_CONFIGURABLE, + /** Object properties with no receiver check*/ + JSVM_JSPROPERTY_NO_RECEIVER_CHECK = JSVM_DEFAULT_JSPROPERTY | JSVM_NO_RECEIVER_CHECK, +} JSVM_PropertyAttributes; + +/** + * @brief Describes the type of a JSVM_Value. + * + * @since 11 + */ +typedef enum { + /** undefined type. */ + JSVM_UNDEFINED, + /** null type. */ + JSVM_NULL, + /** boolean type. */ + JSVM_BOOLEAN, + /** number type. */ + JSVM_NUMBER, + /** string type. */ + JSVM_STRING, + /** symbol type. */ + JSVM_SYMBOL, + /** object type. */ + JSVM_OBJECT, + /** function type. */ + JSVM_FUNCTION, + /** external type. */ + JSVM_EXTERNAL, + /** bigint type. */ + JSVM_BIGINT, +} JSVM_ValueType; + +/** + * @brief Describes the type of a typedarray. + * + * @since 11 + */ +typedef enum { + /** int8 type. */ + JSVM_INT8_ARRAY, + /** uint8 type. */ + JSVM_UINT8_ARRAY, + /** uint8 clamped type. */ + JSVM_UINT8_CLAMPED_ARRAY, + /** int16 type. */ + JSVM_INT16_ARRAY, + /** uint16 type. */ + JSVM_UINT16_ARRAY, + /** int32 type. */ + JSVM_INT32_ARRAY, + /** uint32 type. */ + JSVM_UINT32_ARRAY, + /** float32 type. */ + JSVM_FLOAT32_ARRAY, + /** float64 type. */ + JSVM_FLOAT64_ARRAY, + /** bigint64 type. */ + JSVM_BIGINT64_ARRAY, + /** biguint64 type. */ + JSVM_BIGUINT64_ARRAY, +} JSVM_TypedarrayType; + +/** + * @brief Integral status code indicating the success or failure of a JSVM-API call. + * + * @since 11 + */ +typedef enum { + /** success status. */ + JSVM_OK, + /** invalidarg status. */ + JSVM_INVALID_ARG, + /** object expected status. */ + JSVM_OBJECT_EXPECTED, + /** string expected status. */ + JSVM_STRING_EXPECTED, + /** name expected status. */ + JSVM_NAME_EXPECTED, + /** function expected status. */ + JSVM_FUNCTION_EXPECTED, + /** number expected status. */ + JSVM_NUMBER_EXPECTED, + /** boolean expected status. */ + JSVM_BOOLEAN_EXPECTED, + /** array expected status. */ + JSVM_ARRAY_EXPECTED, + /** generic failure status. */ + JSVM_GENERIC_FAILURE, + /** pending exception status. */ + JSVM_PENDING_EXCEPTION, + /** cancelled status. */ + JSVM_CANCELLED, + /** escape called twice status. */ + JSVM_ESCAPE_CALLED_TWICE, + /** handle scope mismatch status. */ + JSVM_HANDLE_SCOPE_MISMATCH, + /** callback scope mismatch status. */ + JSVM_CALLBACK_SCOPE_MISMATCH, + /** queue full status. */ + JSVM_QUEUE_FULL, + /** closing status. */ + JSVM_CLOSING, + /** bigint expected status. */ + JSVM_BIGINT_EXPECTED, + /** date expected status. */ + JSVM_DATE_EXPECTED, + /** arraybuffer expected status. */ + JSVM_ARRAYBUFFER_EXPECTED, + /** detachable arraybuffer expected status. */ + JSVM_DETACHABLE_ARRAYBUFFER_EXPECTED, + /** would deadlock status. */ + JSVM_WOULD_DEADLOCK, + /** no external buffers allowed status. */ + JSVM_NO_EXTERNAL_BUFFERS_ALLOWED, + /** cannot run +js status. */ + JSVM_CANNOT_RUN_JS, +} JSVM_Status; + +/** + * @brief limits the range of collected properties.. + * + * @since 11 + */ +typedef enum { + /** will include all keys of the objects's prototype chain as well. */ + JSVM_KEY_INCLUDE_PROTOTYPES, + /** limits the collected properties to the given object only. */ + JSVM_KEY_OWN_ONLY +} JSVM_KeyCollectionMode; + +/** + * @brief Property filter bits. They can be or'ed to build a composite filter.. + * + * @since 11 + */ +typedef enum { + /** key all properties. */ + JSVM_KEY_ALL_PROPERTIES = 0, + /** key writable. */ + JSVM_KEY_WRITABLE = 1, + /** key enumerable. */ + JSVM_KEY_ENUMERABLE = 1 << 1, + /** key configurable. */ + JSVM_KEY_CONFIGURABLE = 1 << 2, + /** key skip strings. */ + JSVM_KEY_SKIP_STRINGS = 1 << 3, + /** key skip symbols. */ + JSVM_KEY_SKIP_SYMBOLS = 1 << 4 +} JSVM_KeyFilter; + +/** + * @brief key conversion select. + * + * @since 11 + */ +typedef enum { + /** will return numbers for integer indices. */ + JSVM_KEY_KEEP_NUMBERS, + /** will convert integer indices to strings. */ + JSVM_KEY_NUMBERS_TO_STRINGS +} JSVM_KeyConversion; + +/** + * @brief Memory pressure level. + * + * @since 11 + */ +typedef enum { + /** none pressure. */ + JSVM_MEMORY_PRESSURE_LEVEL_NONE, + /** moderate pressure. */ + JSVM_MEMORY_PRESSURE_LEVEL_MODERATE, + /** critical pressure. */ + JSVM_MEMORY_PRESSURE_LEVEL_CRITICAL, +} JSVM_MemoryPressureLevel; + +/** + * + * @brief Compile mode + * + * @since 12 + */ +typedef enum { + /** default mode. */ + JSVM_COMPILE_MODE_DEFAULT, + /** consume code cache. */ + JSVM_COMPILE_MODE_CONSUME_CODE_CACHE, + /** apply eager compile. */ + JSVM_COMPILE_MODE_EAGER_COMPILE, + /** preset for compile profile. */ + JSVM_COMPILE_MODE_PRODUCE_COMPILE_PROFILE, + /** consume compile profile. */ + JSVM_COMPILE_MODE_CONSUME_COMPILE_PROFILE, +} JSVM_CompileMode; + +/** + * @brief Compile option id + * + * @since 12 + */ +typedef enum { + /** compile mode. */ + JSVM_COMPILE_MODE, + /** code cache content. */ + JSVM_COMPILE_CODE_CACHE, + /** script origin. */ + JSVM_COMPILE_SCRIPT_ORIGIN, + /** compile profile content. */ + JSVM_COMPILE_COMPILE_PROFILE, + /** switch for source map support. */ + JSVM_COMPILE_ENABLE_SOURCE_MAP, +} JSVM_CompileOptionId; + +/** + * @brief Heap statisics. + * + * @since 12 + */ +typedef struct { + /** the size of the total heap. */ + size_t totalHeapSize; + /** the executable size of the total heap. */ + size_t totalHeapSizeExecutable; + /** the physical size of the total heap. */ + size_t totalPhysicalSize; + /** the available size of the total heap. */ + size_t totalAvailableSize; + /** used size of the heap. */ + size_t usedHeapSize; + /** heap size limit. */ + size_t heapSizeLimit; + /** memory requested by the heap. */ + size_t mallocedMemory; + /** heap-requested external memory. */ + size_t externalMemory; + /** peak memory requested by the heap. */ + size_t peakMallocedMemory; + /** the number of native contexts. */ + size_t numberOfNativeContexts; + /** the number of detached contexts. */ + size_t numberOfDetachedContexts; + /** the size of the total global handles. */ + size_t totalGlobalHandlesSize; + /** the size of the used global handles. */ + size_t usedGlobalHandlesSize; +} JSVM_HeapStatistics; + +/** + * @brief Init the JavaScript VM with init option. + * + * @since 11 + */ +typedef struct { + /** + * Optional nullptr-terminated array of raw adddresses in the embedder that the + * VM can match against during serialization and use for deserialization. This + * array and its content must stay valid for the entire lifetime of the VM + * instance. + */ + const intptr_t* externalReferences; + + /** + * Flags for the VM. IF removeFlags is true, recognized flags will be removed + * from (argc, argv). Note that these flags are specific to VM. + * They are mainly used for development. Do not include them in production as + * they might not take effect if the VM is different from the development + * environment. + */ + int* argc; + /** argv . */ + char** argv; + /** remove flags. */ + bool removeFlags; +} JSVM_InitOptions; + +/** + * @brief Create the JavaScript VM with init option. + * + * @since 11 + */ +typedef struct { + /** optional limits of memory use of the vm. */ + size_t maxOldGenerationSize; + /** optional limits of memory use of the vm. */ + size_t maxYoungGenerationSize; + /** optional limits of memory use of the vm. */ + size_t initialOldGenerationSize; + /** optional limits of memory use of the vm. */ + size_t initialYoungGenerationSize; + /** Optional startup snapshot data. */ + const char* snapshotBlobData; + /** Optional size of the startup snapshot data. */ + size_t snapshotBlobSize; + /** Whether the VM is used for creating snapshot. */ + bool isForSnapshotting; +} JSVM_CreateVMOptions; + +/** + * @brief JavaScript VM info. + * + * @since 11 + */ +typedef struct { + /** The highest API version this VM supports. */ + uint32_t apiVersion; + /** The engine name implementing the VM. */ + const char* engine; + /** The version of the VM. */ + const char* version; + /** The cached data version tag. */ + uint32_t cachedDataVersionTag; +} JSVM_VMInfo; + +/** + * @brief Property descriptor. + * + * @since 11 + */ +typedef struct { + /** Optional string describing the key for the property, encoded as UTF8. + * One of utf8name or name must be provided for the property. + */ + const char* utf8name; + /** Optional value that points to a JavaScript string or symbol to be used as the key for the property. */ + JSVM_Value name; + /** Set this to make the property descriptor object's value property to be + * a JavaScript function represented by method. + */ + JSVM_Callback method; + /** A function to call when a get access of the property is performed. */ + JSVM_Callback getter; + /** A function to call when a set access of the property is performed. */ + JSVM_Callback setter; + /** The value that's retrieved by a get access of the property if the property is a data property. */ + JSVM_Value value; + /** The attributes associated with the particular property. */ + JSVM_PropertyAttributes attributes; +} JSVM_PropertyDescriptor; + +/** + * @brief JSVM-API uses both return values and JavaScript exceptions for error handling + * @since 11 + */ +typedef struct { + /** UTF8-encoded string containing a VM-neutral description of the error. */ + const char* errorMessage; + /** Reserved for VM-specific error details. This is currently not implemented for any VM. */ + void* engineReserved; + /** VM-specific error code. This is currently not implemented for any VM. */ + uint32_t engineErrorCode; + /** The JSVM-API status code that originated with the last error. */ + JSVM_Status errorCode; +} JSVM_ExtendedErrorInfo; + +/** + * @brief A 128-bit value stored as two unsigned 64-bit integers. + * It serves as a UUID with which JavaScript objects or externals can be "tagged" + * in order to ensure that they are of a certain type. + * + * @since 11 + */ +typedef struct { + /** lower type. */ + uint64_t lower; + /** upper type. */ + uint64_t upper; +} JSVM_TypeTag; + +/** + * @brief When the getter, setter, call, etc. behavior occurs on the object, the corresponding + * the corresponding callback will be triggered. + * + * @since 12 + */ +typedef struct { + /** A callback function triggered by getting a named property of an instance object. */ + JSVM_Value(JSVM_CDECL* genericNamedPropertyGetterCallback)(JSVM_Env env, + JSVM_Value name, + JSVM_Value thisArg, + JSVM_Value namedPropertyData); + + /** A callback function triggered by setting a named property of an instance object. */ + JSVM_Value(JSVM_CDECL* genericNamedPropertySetterCallback)(JSVM_Env env, + JSVM_Value name, + JSVM_Value property, + JSVM_Value thisArg, + JSVM_Value namedPropertyData); + + /** A callback function triggered by deleting a named property of an instance object. */ + JSVM_Value(JSVM_CDECL* genericNamedPropertyDeleterCallback)(JSVM_Env env, + JSVM_Value name, + JSVM_Value thisArg, + JSVM_Value namedPropertyData); + + /** A callback function triggered by getting all named properties requests on an object. */ + JSVM_Value(JSVM_CDECL* genericNamedPropertyEnumeratorCallback)(JSVM_Env env, + JSVM_Value thisArg, + JSVM_Value namedPropertyData); + + /** A callback function triggered by getting an indexed property of an instance object. */ + JSVM_Value(JSVM_CDECL* genericIndexedPropertyGetterCallback)(JSVM_Env env, + JSVM_Value index, + JSVM_Value thisArg, + JSVM_Value indexedPropertyData); + + /** A callback function triggered by setting an indexed property of an instance object. */ + JSVM_Value(JSVM_CDECL* genericIndexedPropertySetterCallback)(JSVM_Env env, + JSVM_Value index, + JSVM_Value property, + JSVM_Value thisArg, + JSVM_Value indexedPropertyData); + + /** A callback function triggered by deleting an indexed property of an instance object. */ + JSVM_Value(JSVM_CDECL* genericIndexedPropertyDeleterCallback)(JSVM_Env env, + JSVM_Value index, + JSVM_Value thisArg, + JSVM_Value indexedPropertyData); + + /** A callback function triggered by getting all indexed properties requests on an object. */ + JSVM_Value(JSVM_CDECL* genericIndexedPropertyEnumeratorCallback)(JSVM_Env env, + JSVM_Value thisArg, + JSVM_Value indexedPropertyData); + + /** data will be utilized by the named property callbacks in this struct. */ + JSVM_Value namedPropertyData; + + /** data will be utilized by the indexed property callbacks in this struct. */ + JSVM_Value indexedPropertyData; +} JSVM_PropertyHandlerConfigurationStruct; + +/** + * @brief The function pointer type of the callback provided by the instance object, which triggers the + * corresponding callback when getter, setter, call, and other behaviors occur on the object. + * + * @since 12 + */ +typedef JSVM_PropertyHandlerConfigurationStruct* JSVM_PropertyHandlerCfg; + +/** + * + * @brief Source code information. + * + * @since 12 + */ +typedef struct { + /** Sourcemap url. */ + const char* sourceMapUrl; + /** Resource name. */ + const char* resourceName; + /** Resource line offset. */ + size_t resourceLineOffset; + /** Resource column offset. */ + size_t resourceColumnOffset; +} JSVM_ScriptOrigin; + +/** + * @brief Regular expression flag bits. They can be or'ed to enable a set of flags. + * + * @since 12 + */ +typedef enum { + /** None mode. */ + JSVM_REGEXP_NONE = 0, + /** Global mode. */ + JSVM_REGEXP_GLOBAL = 1 << 0, + /** Ignore Case mode. */ + JSVM_REGEXP_IGNORE_CASE = 1 << 1, + /** Multiline mode. */ + JSVM_REGEXP_MULTILINE = 1 << 2, + /** Sticky mode. */ + JSVM_REGEXP_STICKY = 1 << 3, + /** Unicode mode. */ + JSVM_REGEXP_UNICODE = 1 << 4, + /** dotAll mode. */ + JSVM_REGEXP_DOT_ALL = 1 << 5, + /** Linear mode. */ + JSVM_REGEXP_LINEAR = 1 << 6, + /** Has Indices mode. */ + JSVM_REGEXP_HAS_INDICES = 1 << 7, + /** Unicode Sets mode. */ + JSVM_REGEXP_UNICODE_SETS = 1 << 8, +} JSVM_RegExpFlags; + +/** + * @brief Compile Options + * + * @since 12 + */ +typedef struct { + /** compile option id. */ + JSVM_CompileOptionId id; + /** option content. */ + union { + /** ptr type. */ + void *ptr; + /** int type. */ + int num; + /** bool type. */ + bool boolean; + } content; +} JSVM_CompileOptions; + +/** + * @brief code cache passed with JSVM_COMPILE_CODE_CACHE + * + * @since 12 + */ +typedef struct { + /** cache pointer. */ + uint8_t *cache; + /** length. */ + size_t length; +} JSVM_CodeCache; + +/** + * @brief WebAssembly function optimization level + * + * @since 12 + */ +typedef enum { + /** baseline optimization level. */ + JSVM_WASM_OPT_BASELINE = 10, + /** high optimization level. */ + JSVM_WASM_OPT_HIGH = 20, +} JSVM_WasmOptLevel; + +/** + * @brief Cache data type + * + * @since 12 + */ +typedef enum { + /** js code cache, generated by OH_JSVM_CreateCodeCache */ + JSVM_CACHE_TYPE_JS, + /** WebAssembly cache, generated by OH_JSVM_CreateWasmCache */ + JSVM_CACHE_TYPE_WASM, +} JSVM_CacheType; + +/** + * @brief compile profile passed with JSVM_COMPILE_COMPILE_PROFILE + * + * @since 12 + */ +typedef const struct { + /** profile pointer. */ + int *profile; + /** length. */ + size_t length; +} JSVM_CompileProfile; + +/** + * @brief initialization flag + * + * @since 12 + */ +typedef enum { + /** initialize with zero. */ + JSVM_ZERO_INITIALIZED, + /** leave uninitialized. */ + JSVM_UNINITIALIZED, +} JSVM_InitializedFlag; +/** @} */ +#endif /* ARK_RUNTIME_JSVM_JSVM_TYPE_H */ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/node_version.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/node_version.h new file mode 100644 index 0000000000..6973a3d0fd --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/node_version.h @@ -0,0 +1,102 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +#ifndef SRC_NODE_VERSION_H_ +#define SRC_NODE_VERSION_H_ + +#define NODE_MAJOR_VERSION 18 +#define NODE_MINOR_VERSION 20 +#define NODE_PATCH_VERSION 1 + +#define NODE_VERSION_IS_LTS 1 +#define NODE_VERSION_LTS_CODENAME "Hydrogen" + +#define NODE_VERSION_IS_RELEASE 1 + +#ifndef NODE_STRINGIFY +#define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) +#define NODE_STRINGIFY_HELPER(n) #n +#endif + +#ifndef NODE_RELEASE +#define NODE_RELEASE "node" +#endif + +#ifndef NODE_TAG +# if NODE_VERSION_IS_RELEASE +# define NODE_TAG "" +# else +# define NODE_TAG "-pre" +# endif +#else +// NODE_TAG is passed without quotes when rc.exe is run from msbuild +# define NODE_EXE_VERSION NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \ + NODE_STRINGIFY(NODE_MINOR_VERSION) "." \ + NODE_STRINGIFY(NODE_PATCH_VERSION) \ + NODE_STRINGIFY(NODE_TAG) +#endif + +# define NODE_VERSION_STRING NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \ + NODE_STRINGIFY(NODE_MINOR_VERSION) "." \ + NODE_STRINGIFY(NODE_PATCH_VERSION) \ + NODE_TAG +#ifndef NODE_EXE_VERSION +# define NODE_EXE_VERSION NODE_VERSION_STRING +#endif + +#define NODE_VERSION "v" NODE_VERSION_STRING + + +#define NODE_VERSION_AT_LEAST(major, minor, patch) \ + (( (major) < NODE_MAJOR_VERSION) \ + || ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) \ + || ((major) == NODE_MAJOR_VERSION && \ + (minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION)) + +/** + * Node.js will refuse to load modules that weren't compiled against its own + * module ABI number, exposed as the process.versions.modules property. + * + * Node.js will refuse to load modules with a non-matching ABI version. The + * version number here should be changed whenever an ABI-incompatible API change + * is made in the C++ side, including in V8 or other dependencies. + * + * Node.js will not change the module version during a Major release line + * We will, at times update the version of V8 shipped in the release line + * if it can be made ABI compatible with the previous version. + * + * The registry of used NODE_MODULE_VERSION numbers is located at + * https://github.com/nodejs/node/blob/HEAD/doc/abi_version_registry.json + * Extenders, embedders and other consumers of Node.js that require ABI + * version matching should open a pull request to reserve a number in this + * registry. + */ +#define NODE_MODULE_VERSION 108 + +// The NAPI_VERSION provided by this version of the runtime. This is the version +// which the Node binary being built supports. +#define NAPI_VERSION 9 + +// Node API modules use NAPI_VERSION 8 by default if it is not explicitly +// specified. It must be always 8. +#define NODE_API_DEFAULT_MODULE_API_VERSION 8 + +#endif // SRC_NODE_VERSION_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.cc b/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.cc new file mode 100644 index 0000000000..419f7244b6 --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.cc @@ -0,0 +1,593 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +#include "util.h" // NOLINT(build/include_inline) +#include "util-inl.h" + +#include "debug_utils-inl.h" +#include "env-inl.h" +#include "node_buffer.h" +#include "node_errors.h" +#include "node_internals.h" +#include "node_util.h" +#include "string_bytes.h" +#include "uv.h" +#include "init_param.h" + +#ifdef _WIN32 +#include // _S_IREAD _S_IWRITE +#include +#ifndef S_IRUSR +#define S_IRUSR _S_IREAD +#endif // S_IRUSR +#ifndef S_IWUSR +#define S_IWUSR _S_IWRITE +#endif // S_IWUSR +#else +#include +#include +#endif + +#include +#include +#include +#include +#include + +#define ARGBUFFSIZE 32 + +static std::atomic_int seq = {0}; // Sequence number for diagnostic filenames. + +namespace node { + +using v8::ArrayBufferView; +using v8::Isolate; +using v8::Local; +using v8::String; +using v8::Value; + +bool ReadSystemXpmState() { + char buffer[ARGBUFFSIZE] = { 0 }; + uint32_t buffSize = sizeof(buffer); + + if (SystemGetParameter("ohos.boot.advsecmode.state", buffer, &buffSize) == 0 && strcmp(buffer, "0") != 0) { + return true; + } + return false; +} + +template +static void MakeUtf8String(Isolate* isolate, + Local value, + MaybeStackBuffer* target) { + Local string; + if (!value->ToString(isolate->GetCurrentContext()).ToLocal(&string)) return; + + size_t storage; + if (!StringBytes::StorageSize(isolate, string, UTF8).To(&storage)) return; + storage += 1; + target->AllocateSufficientStorage(storage); + const int flags = + String::NO_NULL_TERMINATION | String::REPLACE_INVALID_UTF8; + const int length = + string->WriteUtf8(isolate, target->out(), storage, nullptr, flags); + target->SetLengthAndZeroTerminate(length); +} + +Utf8Value::Utf8Value(Isolate* isolate, Local value) { + if (value.IsEmpty()) + return; + + MakeUtf8String(isolate, value, this); +} + + +TwoByteValue::TwoByteValue(Isolate* isolate, Local value) { + if (value.IsEmpty()) { + return; + } + + Local string; + if (!value->ToString(isolate->GetCurrentContext()).ToLocal(&string)) return; + + // Allocate enough space to include the null terminator + const size_t storage = string->Length() + 1; + AllocateSufficientStorage(storage); + + const int flags = String::NO_NULL_TERMINATION; + const int length = string->Write(isolate, out(), 0, storage, flags); + SetLengthAndZeroTerminate(length); +} + +BufferValue::BufferValue(Isolate* isolate, Local value) { + // Slightly different take on Utf8Value. If value is a String, + // it will return a Utf8 encoded string. If value is a Buffer, + // it will copy the data out of the Buffer as is. + if (value.IsEmpty()) { + // Dereferencing this object will return nullptr. + Invalidate(); + return; + } + + if (value->IsString()) { + MakeUtf8String(isolate, value, this); + } else if (value->IsArrayBufferView()) { + const size_t len = value.As()->ByteLength(); + // Leave place for the terminating '\0' byte. + AllocateSufficientStorage(len + 1); + value.As()->CopyContents(out(), len); + SetLengthAndZeroTerminate(len); + } else { + Invalidate(); + } +} + +void LowMemoryNotification() { + if (per_process::v8_initialized) { + auto isolate = Isolate::TryGetCurrent(); + if (isolate != nullptr) { + isolate->LowMemoryNotification(); + } + } +} + +std::string GetProcessTitle(const char* default_title) { + std::string buf(16, '\0'); + + for (;;) { + const int rc = uv_get_process_title(buf.data(), buf.size()); + + if (rc == 0) + break; + + // If uv_setup_args() was not called, `uv_get_process_title()` will always + // return `UV_ENOBUFS`, no matter the input size. Guard against a possible + // infinite loop by limiting the buffer size. + if (rc != UV_ENOBUFS || buf.size() >= 1024 * 1024) + return default_title; + + buf.resize(2 * buf.size()); + } + + // Strip excess trailing nul bytes. Using strlen() here is safe, + // uv_get_process_title() always zero-terminates the result. + buf.resize(strlen(buf.data())); + + return buf; +} + +std::string GetHumanReadableProcessName() { + return SPrintF("%s[%d]", GetProcessTitle("Node.js"), uv_os_getpid()); +} + +std::vector SplitString(const std::string_view in, + const std::string_view delim) { + std::vector out; + + for (auto first = in.data(), second = in.data(), last = first + in.size(); + second != last && first != last; + first = second + 1) { + second = + std::find_first_of(first, last, std::cbegin(delim), std::cend(delim)); + + if (first != second) { + out.emplace_back(first, second - first); + } + } + + return out; +} + +void ThrowErrStringTooLong(Isolate* isolate) { + isolate->ThrowException(ERR_STRING_TOO_LONG(isolate)); +} + +double GetCurrentTimeInMicroseconds() { + constexpr double kMicrosecondsPerSecond = 1e6; + uv_timeval64_t tv; + CHECK_EQ(0, uv_gettimeofday(&tv)); + return kMicrosecondsPerSecond * tv.tv_sec + tv.tv_usec; +} + +int WriteFileSync(const char* path, uv_buf_t buf) { + uv_fs_t req; + int fd = uv_fs_open(nullptr, + &req, + path, + O_WRONLY | O_CREAT | O_TRUNC, + S_IWUSR | S_IRUSR, + nullptr); + uv_fs_req_cleanup(&req); + if (fd < 0) { + return fd; + } + + int err = uv_fs_write(nullptr, &req, fd, &buf, 1, 0, nullptr); + uv_fs_req_cleanup(&req); + if (err < 0) { + return err; + } + + err = uv_fs_close(nullptr, &req, fd, nullptr); + uv_fs_req_cleanup(&req); + return err; +} + +int WriteFileSync(v8::Isolate* isolate, + const char* path, + v8::Local string) { + node::Utf8Value utf8(isolate, string); + uv_buf_t buf = uv_buf_init(utf8.out(), utf8.length()); + return WriteFileSync(path, buf); +} + +int ReadFileSync(std::string* result, const char* path) { + uv_fs_t req; + auto defer_req_cleanup = OnScopeLeave([&req]() { + uv_fs_req_cleanup(&req); + }); + + uv_file file = uv_fs_open(nullptr, &req, path, O_RDONLY, 0, nullptr); + if (req.result < 0) { + // req will be cleaned up by scope leave. + return req.result; + } + uv_fs_req_cleanup(&req); + + auto defer_close = OnScopeLeave([file]() { + uv_fs_t close_req; + CHECK_EQ(0, uv_fs_close(nullptr, &close_req, file, nullptr)); + uv_fs_req_cleanup(&close_req); + }); + + *result = std::string(""); + char buffer[4096]; + uv_buf_t buf = uv_buf_init(buffer, sizeof(buffer)); + + while (true) { + const int r = + uv_fs_read(nullptr, &req, file, &buf, 1, result->length(), nullptr); + if (req.result < 0) { + // req will be cleaned up by scope leave. + return req.result; + } + uv_fs_req_cleanup(&req); + if (r <= 0) { + break; + } + result->append(buf.base, r); + } + return 0; +} + +void DiagnosticFilename::LocalTime(TIME_TYPE* tm_struct) { +#ifdef _WIN32 + GetLocalTime(tm_struct); +#else // UNIX, OSX + struct timeval time_val; + gettimeofday(&time_val, nullptr); + localtime_r(&time_val.tv_sec, tm_struct); +#endif +} + +// Defined in node_internals.h +std::string DiagnosticFilename::MakeFilename( + uint64_t thread_id, + const char* prefix, + const char* ext) { + std::ostringstream oss; + TIME_TYPE tm_struct; + LocalTime(&tm_struct); + oss << prefix; +#ifdef _WIN32 + oss << "." << std::setfill('0') << std::setw(4) << tm_struct.wYear; + oss << std::setfill('0') << std::setw(2) << tm_struct.wMonth; + oss << std::setfill('0') << std::setw(2) << tm_struct.wDay; + oss << "." << std::setfill('0') << std::setw(2) << tm_struct.wHour; + oss << std::setfill('0') << std::setw(2) << tm_struct.wMinute; + oss << std::setfill('0') << std::setw(2) << tm_struct.wSecond; +#else // UNIX, OSX + oss << "." + << std::setfill('0') + << std::setw(4) + << tm_struct.tm_year + 1900; + oss << std::setfill('0') + << std::setw(2) + << tm_struct.tm_mon + 1; + oss << std::setfill('0') + << std::setw(2) + << tm_struct.tm_mday; + oss << "." + << std::setfill('0') + << std::setw(2) + << tm_struct.tm_hour; + oss << std::setfill('0') + << std::setw(2) + << tm_struct.tm_min; + oss << std::setfill('0') + << std::setw(2) + << tm_struct.tm_sec; +#endif + oss << "." << uv_os_getpid(); + oss << "." << thread_id; + oss << "." << std::setfill('0') << std::setw(3) << ++seq; + oss << "." << ext; + return oss.str(); +} + +Local NewFunctionTemplate( + v8::Isolate* isolate, + v8::FunctionCallback callback, + Local signature, + v8::ConstructorBehavior behavior, + v8::SideEffectType side_effect_type, + const v8::CFunction* c_function) { + return v8::FunctionTemplate::New(isolate, + callback, + Local(), + signature, + 0, + behavior, + side_effect_type, + c_function); +} + +void SetMethod(Local context, + Local that, + const char* name, + v8::FunctionCallback callback) { + Isolate* isolate = context->GetIsolate(); + Local function = + NewFunctionTemplate(isolate, + callback, + Local(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect) + ->GetFunction(context) + .ToLocalChecked(); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(context, name_string, function).Check(); + function->SetName(name_string); // NODE_SET_METHOD() compatibility. +} + +void SetMethod(v8::Isolate* isolate, + v8::Local that, + const char* name, + v8::FunctionCallback callback) { + Local t = + NewFunctionTemplate(isolate, + callback, + Local(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(name_string, t); +} + +void SetFastMethod(Local context, + Local that, + const char* name, + v8::FunctionCallback slow_callback, + const v8::CFunction* c_function) { + Isolate* isolate = context->GetIsolate(); + Local function = + NewFunctionTemplate(isolate, + slow_callback, + Local(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect, + c_function) + ->GetFunction(context) + .ToLocalChecked(); + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(context, name_string, function).Check(); +} + +void SetFastMethodNoSideEffect(Local context, + Local that, + const char* name, + v8::FunctionCallback slow_callback, + const v8::CFunction* c_function) { + Isolate* isolate = context->GetIsolate(); + Local function = + NewFunctionTemplate(isolate, + slow_callback, + Local(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasNoSideEffect, + c_function) + ->GetFunction(context) + .ToLocalChecked(); + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(context, name_string, function).Check(); +} + +void SetMethodNoSideEffect(Local context, + Local that, + const char* name, + v8::FunctionCallback callback) { + Isolate* isolate = context->GetIsolate(); + Local function = + NewFunctionTemplate(isolate, + callback, + Local(), + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasNoSideEffect) + ->GetFunction(context) + .ToLocalChecked(); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->Set(context, name_string, function).Check(); + function->SetName(name_string); // NODE_SET_METHOD() compatibility. +} + +void SetProtoMethod(v8::Isolate* isolate, + Local that, + const char* name, + v8::FunctionCallback callback) { + Local signature = v8::Signature::New(isolate, that); + Local t = + NewFunctionTemplate(isolate, + callback, + signature, + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->PrototypeTemplate()->Set(name_string, t); + t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. +} + +void SetProtoMethodNoSideEffect(v8::Isolate* isolate, + Local that, + const char* name, + v8::FunctionCallback callback) { + Local signature = v8::Signature::New(isolate, that); + Local t = + NewFunctionTemplate(isolate, + callback, + signature, + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasNoSideEffect); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->PrototypeTemplate()->Set(name_string, t); + t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. +} + +void SetInstanceMethod(v8::Isolate* isolate, + Local that, + const char* name, + v8::FunctionCallback callback) { + Local signature = v8::Signature::New(isolate, that); + Local t = + NewFunctionTemplate(isolate, + callback, + signature, + v8::ConstructorBehavior::kThrow, + v8::SideEffectType::kHasSideEffect); + // kInternalized strings are created in the old space. + const v8::NewStringType type = v8::NewStringType::kInternalized; + Local name_string = + v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked(); + that->InstanceTemplate()->Set(name_string, t); + t->SetClassName(name_string); +} + +void SetConstructorFunction(Local context, + Local that, + const char* name, + Local tmpl, + SetConstructorFunctionFlag flag) { + Isolate* isolate = context->GetIsolate(); + SetConstructorFunction( + context, that, OneByteString(isolate, name), tmpl, flag); +} + +void SetConstructorFunction(Local context, + Local that, + Local name, + Local tmpl, + SetConstructorFunctionFlag flag) { + if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME)) + tmpl->SetClassName(name); + that->Set(context, name, tmpl->GetFunction(context).ToLocalChecked()).Check(); +} + +namespace { + +class NonOwningExternalOneByteResource + : public v8::String::ExternalOneByteStringResource { + public: + explicit NonOwningExternalOneByteResource(const UnionBytes& source) + : source_(source) {} + ~NonOwningExternalOneByteResource() override = default; + + const char* data() const override { + return reinterpret_cast(source_.one_bytes_data()); + } + size_t length() const override { return source_.length(); } + + NonOwningExternalOneByteResource(const NonOwningExternalOneByteResource&) = + delete; + NonOwningExternalOneByteResource& operator=( + const NonOwningExternalOneByteResource&) = delete; + + private: + const UnionBytes source_; +}; + +class NonOwningExternalTwoByteResource + : public v8::String::ExternalStringResource { + public: + explicit NonOwningExternalTwoByteResource(const UnionBytes& source) + : source_(source) {} + ~NonOwningExternalTwoByteResource() override = default; + + const uint16_t* data() const override { return source_.two_bytes_data(); } + size_t length() const override { return source_.length(); } + + NonOwningExternalTwoByteResource(const NonOwningExternalTwoByteResource&) = + delete; + NonOwningExternalTwoByteResource& operator=( + const NonOwningExternalTwoByteResource&) = delete; + + private: + const UnionBytes source_; +}; + +} // anonymous namespace + +Local UnionBytes::ToStringChecked(Isolate* isolate) const { + if (UNLIKELY(length() == 0)) { + // V8 requires non-null data pointers for empty external strings, + // but we don't guarantee that. Solve this by not creating an + // external string at all in that case. + return String::Empty(isolate); + } + if (is_one_byte()) { + NonOwningExternalOneByteResource* source = + new NonOwningExternalOneByteResource(*this); + return String::NewExternalOneByte(isolate, source).ToLocalChecked(); + } else { + NonOwningExternalTwoByteResource* source = + new NonOwningExternalTwoByteResource(*this); + return String::NewExternalTwoByte(isolate, source).ToLocalChecked(); + } +} + +} // namespace node diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.h new file mode 100644 index 0000000000..edf2c7b36d --- /dev/null +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.h @@ -0,0 +1,939 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +#ifndef SRC_UTIL_H_ +#define SRC_UTIL_H_ + +#ifndef NODE_WANT_INTERNALS +#define NODE_WANT_INTERNALS 1 +#endif + +#ifndef NODE_EXTERN_PRIVATE +#define NODE_EXTERN_PRIVATE +#endif + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include "v8.h" + +//#include "node.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __GNUC__ +#define MUST_USE_RESULT __attribute__((warn_unused_result)) +#else +#define MUST_USE_RESULT +#endif + +namespace node { + +bool ReadSystemXpmState(); + +// Maybe remove kPathSeparator when cpp17 is ready +#ifdef _WIN32 + constexpr char kPathSeparator = '\\'; +/* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */ +#define PATH_MAX_BYTES (MAX_PATH * 4) +#else + constexpr char kPathSeparator = '/'; +#define PATH_MAX_BYTES (PATH_MAX) +#endif + +// These should be used in our code as opposed to the native +// versions as they abstract out some platform and or +// compiler version specific functionality +// malloc(0) and realloc(ptr, 0) have implementation-defined behavior in +// that the standard allows them to either return a unique pointer or a +// nullptr for zero-sized allocation requests. Normalize by always using +// a nullptr. +template +inline T* UncheckedRealloc(T* pointer, size_t n); +template +inline T* UncheckedMalloc(size_t n); +template +inline T* UncheckedCalloc(size_t n); + +// Same things, but aborts immediately instead of returning nullptr when +// no memory is available. +template +inline T* Realloc(T* pointer, size_t n); +template +inline T* Malloc(size_t n); +template +inline T* Calloc(size_t n); + +inline char* Malloc(size_t n); +inline char* Calloc(size_t n); +inline char* UncheckedMalloc(size_t n); +inline char* UncheckedCalloc(size_t n); + +template +inline T MultiplyWithOverflowCheck(T a, T b); + +namespace per_process { +// Tells whether the per-process V8::Initialize() is called and +// if it is safe to call v8::Isolate::TryGetCurrent(). +extern bool v8_initialized; +} // namespace per_process + +// Used by the allocation functions when allocation fails. +// Thin wrapper around v8::Isolate::LowMemoryNotification() that checks +// whether V8 is initialized. +void LowMemoryNotification(); + +// The reason that Assert() takes a struct argument instead of individual +// const char*s is to ease instruction cache pressure in calls from CHECK. +struct AssertionInfo { + const char* file_line; // filename:line + const char* message; + const char* function; +}; +void NODE_EXTERN_PRIVATE Assert(const AssertionInfo& info); +void NODE_EXTERN_PRIVATE Abort(); +void DumpBacktrace(FILE* fp); + +// Windows 8+ does not like abort() in Release mode +#ifdef _WIN32 +#define ABORT_NO_BACKTRACE() _exit(134) +#else +#define ABORT_NO_BACKTRACE() abort() +#endif + +#define ABORT() node::Abort() + +#define ERROR_AND_ABORT(expr) \ + do { \ + /* Make sure that this struct does not end up in inline code, but */ \ + /* rather in a read-only data section when modifying this code. */ \ + static const node::AssertionInfo args = { \ + __FILE__ ":" STRINGIFY(__LINE__), #expr, PRETTY_FUNCTION_NAME \ + }; \ + printf("[FATAL] file_line:%s, message:%s, function:%s\n", args.file_line, args.message, args.function); \ + assert(false); \ + } while (0) + +// node::Assert(args); \ + +#ifdef __GNUC__ +#define LIKELY(expr) __builtin_expect(!!(expr), 1) +#define UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#define PRETTY_FUNCTION_NAME __PRETTY_FUNCTION__ +#else +#define LIKELY(expr) expr +#define UNLIKELY(expr) expr +#define PRETTY_FUNCTION_NAME "" +#endif + +#define STRINGIFY_(x) #x +#define STRINGIFY(x) STRINGIFY_(x) + +#define CHECK(expr) \ + do { \ + if (UNLIKELY(!(expr))) { \ + ERROR_AND_ABORT(expr); \ + } \ + } while (0) + +#define CHECK_EQ(a, b) CHECK((a) == (b)) +#define CHECK_GE(a, b) CHECK((a) >= (b)) +#define CHECK_GT(a, b) CHECK((a) > (b)) +#define CHECK_LE(a, b) CHECK((a) <= (b)) +#define CHECK_LT(a, b) CHECK((a) < (b)) +#define CHECK_NE(a, b) CHECK((a) != (b)) +#define CHECK_NULL(val) CHECK((val) == nullptr) +#define CHECK_NOT_NULL(val) CHECK((val) != nullptr) +#define CHECK_IMPLIES(a, b) CHECK(!(a) || (b)) + +#ifdef DEBUG + #define DCHECK(expr) CHECK(expr) + #define DCHECK_EQ(a, b) CHECK((a) == (b)) + #define DCHECK_GE(a, b) CHECK((a) >= (b)) + #define DCHECK_GT(a, b) CHECK((a) > (b)) + #define DCHECK_LE(a, b) CHECK((a) <= (b)) + #define DCHECK_LT(a, b) CHECK((a) < (b)) + #define DCHECK_NE(a, b) CHECK((a) != (b)) + #define DCHECK_NULL(val) CHECK((val) == nullptr) + #define DCHECK_NOT_NULL(val) CHECK((val) != nullptr) + #define DCHECK_IMPLIES(a, b) CHECK(!(a) || (b)) +#else + #define DCHECK(expr) + #define DCHECK_EQ(a, b) + #define DCHECK_GE(a, b) + #define DCHECK_GT(a, b) + #define DCHECK_LE(a, b) + #define DCHECK_LT(a, b) + #define DCHECK_NE(a, b) + #define DCHECK_NULL(val) + #define DCHECK_NOT_NULL(val) + #define DCHECK_IMPLIES(a, b) +#endif + + +#define UNREACHABLE(...) \ + ERROR_AND_ABORT("Unreachable code reached" __VA_OPT__(": ") __VA_ARGS__) + +// ECMA262 20.1.2.6 Number.MAX_SAFE_INTEGER (2^53-1) +constexpr int64_t kMaxSafeJsInteger = 9007199254740991; + +inline bool IsSafeJsInt(v8::Local v); + +// TAILQ-style intrusive list node. +template +class ListNode; + +// TAILQ-style intrusive list head. +template (T::*M)> +class ListHead; + +template +class ListNode { + public: + inline ListNode(); + inline ~ListNode(); + inline void Remove(); + inline bool IsEmpty() const; + + ListNode(const ListNode&) = delete; + ListNode& operator=(const ListNode&) = delete; + + private: + template (U::*M)> friend class ListHead; + friend int GenDebugSymbols(); + ListNode* prev_; + ListNode* next_; +}; + +template (T::*M)> +class ListHead { + public: + class Iterator { + public: + inline T* operator*() const; + inline const Iterator& operator++(); + inline bool operator!=(const Iterator& that) const; + + private: + friend class ListHead; + inline explicit Iterator(ListNode* node); + ListNode* node_; + }; + + inline ListHead() = default; + inline ~ListHead(); + inline void PushBack(T* element); + inline void PushFront(T* element); + inline bool IsEmpty() const; + inline T* PopFront(); + inline Iterator begin() const; + inline Iterator end() const; + + ListHead(const ListHead&) = delete; + ListHead& operator=(const ListHead&) = delete; + + private: + friend int GenDebugSymbols(); + ListNode head_; +}; + +// The helper is for doing safe downcasts from base types to derived types. +template +class ContainerOfHelper { + public: + inline ContainerOfHelper(Inner Outer::*field, Inner* pointer); + template + inline operator TypeName*() const; + private: + Outer* const pointer_; +}; + +// Calculate the address of the outer (i.e. embedding) struct from +// the interior pointer to a data member. +template +constexpr ContainerOfHelper ContainerOf(Inner Outer::*field, + Inner* pointer); + +class KVStore { + public: + KVStore() = default; + virtual ~KVStore() = default; + KVStore(const KVStore&) = delete; + KVStore& operator=(const KVStore&) = delete; + KVStore(KVStore&&) = delete; + KVStore& operator=(KVStore&&) = delete; + + virtual v8::MaybeLocal Get(v8::Isolate* isolate, + v8::Local key) const = 0; + virtual v8::Maybe Get(const char* key) const = 0; + virtual void Set(v8::Isolate* isolate, + v8::Local key, + v8::Local value) = 0; + virtual int32_t Query(v8::Isolate* isolate, + v8::Local key) const = 0; + virtual int32_t Query(const char* key) const = 0; + virtual void Delete(v8::Isolate* isolate, v8::Local key) = 0; + virtual v8::Local Enumerate(v8::Isolate* isolate) const = 0; + + virtual std::shared_ptr Clone(v8::Isolate* isolate) const; + virtual v8::Maybe AssignFromObject(v8::Local context, + v8::Local entries); + v8::Maybe AssignToObject(v8::Isolate* isolate, + v8::Local context, + v8::Local object); + + static std::shared_ptr CreateMapKVStore(); +}; + +// Convenience wrapper around v8::String::NewFromOneByte(). +inline v8::Local OneByteString(v8::Isolate* isolate, + const char* data, + int length = -1); + +// For the people that compile with -funsigned-char. +inline v8::Local OneByteString(v8::Isolate* isolate, + const signed char* data, + int length = -1); + +inline v8::Local OneByteString(v8::Isolate* isolate, + const unsigned char* data, + int length = -1); + +// Used to be a macro, hence the uppercase name. +template +inline v8::Local FIXED_ONE_BYTE_STRING( + v8::Isolate* isolate, + const char(&data)[N]) { + return OneByteString(isolate, data, N - 1); +} + +template +inline v8::Local FIXED_ONE_BYTE_STRING( + v8::Isolate* isolate, + const std::array& arr) { + return OneByteString(isolate, arr.data(), N - 1); +} + + + +// Swaps bytes in place. nbytes is the number of bytes to swap and must be a +// multiple of the word size (checked by function). +inline void SwapBytes16(char* data, size_t nbytes); +inline void SwapBytes32(char* data, size_t nbytes); +inline void SwapBytes64(char* data, size_t nbytes); + +// tolower() is locale-sensitive. Use ToLower() instead. +inline char ToLower(char c); +inline std::string ToLower(const std::string& in); + +// toupper() is locale-sensitive. Use ToUpper() instead. +inline char ToUpper(char c); +inline std::string ToUpper(const std::string& in); + +// strcasecmp() is locale-sensitive. Use StringEqualNoCase() instead. +inline bool StringEqualNoCase(const char* a, const char* b); + +// strncasecmp() is locale-sensitive. Use StringEqualNoCaseN() instead. +inline bool StringEqualNoCaseN(const char* a, const char* b, size_t length); + +template +constexpr size_t arraysize(const T (&)[N]) { + return N; +} + +template +constexpr size_t strsize(const T (&)[N]) { + return N - 1; +} + +// Allocates an array of member type T. For up to kStackStorageSize items, +// the stack is used, otherwise malloc(). +template +class MaybeStackBuffer { + public: + const T* out() const { + return buf_; + } + + T* out() { + return buf_; + } + + // operator* for compatibility with `v8::String::(Utf8)Value` + T* operator*() { + return buf_; + } + + const T* operator*() const { + return buf_; + } + + T& operator[](size_t index) { + CHECK_LT(index, length()); + return buf_[index]; + } + + const T& operator[](size_t index) const { + CHECK_LT(index, length()); + return buf_[index]; + } + + size_t length() const { + return length_; + } + + // Current maximum capacity of the buffer with which SetLength() can be used + // without first calling AllocateSufficientStorage(). + size_t capacity() const { + return capacity_; + } + + // Make sure enough space for `storage` entries is available. + // This method can be called multiple times throughout the lifetime of the + // buffer, but once this has been called Invalidate() cannot be used. + // Content of the buffer in the range [0, length()) is preserved. + void AllocateSufficientStorage(size_t storage); + + void SetLength(size_t length) { + // capacity() returns how much memory is actually available. + CHECK_LE(length, capacity()); + length_ = length; + } + + void SetLengthAndZeroTerminate(size_t length) { + // capacity() returns how much memory is actually available. + CHECK_LE(length + 1, capacity()); + SetLength(length); + + // T() is 0 for integer types, nullptr for pointers, etc. + buf_[length] = T(); + } + + // Make dereferencing this object return nullptr. + // This method can be called multiple times throughout the lifetime of the + // buffer, but once this has been called AllocateSufficientStorage() cannot + // be used. + void Invalidate() { + CHECK(!IsAllocated()); + capacity_ = 0; + length_ = 0; + buf_ = nullptr; + } + + // If the buffer is stored in the heap rather than on the stack. + bool IsAllocated() const { + return !IsInvalidated() && buf_ != buf_st_; + } + + // If Invalidate() has been called. + bool IsInvalidated() const { + return buf_ == nullptr; + } + + // Release ownership of the malloc'd buffer. + // Note: This does not free the buffer. + void Release() { + CHECK(IsAllocated()); + buf_ = buf_st_; + length_ = 0; + capacity_ = arraysize(buf_st_); + } + + MaybeStackBuffer() + : length_(0), capacity_(arraysize(buf_st_)), buf_(buf_st_) { + // Default to a zero-length, null-terminated buffer. + buf_[0] = T(); + } + + explicit MaybeStackBuffer(size_t storage) : MaybeStackBuffer() { + AllocateSufficientStorage(storage); + } + + ~MaybeStackBuffer() { + if (IsAllocated()) + free(buf_); + } + + inline std::basic_string ToString() const { return {out(), length()}; } + inline std::basic_string_view ToStringView() const { + return {out(), length()}; + } + + private: + size_t length_; + // capacity of the malloc'ed buf_ + size_t capacity_; + T* buf_; + T buf_st_[kStackStorageSize]; +}; + +// Provides access to an ArrayBufferView's storage, either the original, +// or for small data, a copy of it. This object's lifetime is bound to the +// original ArrayBufferView's lifetime. +template +class ArrayBufferViewContents { + public: + ArrayBufferViewContents() = default; + + ArrayBufferViewContents(const ArrayBufferViewContents&) = delete; + void operator=(const ArrayBufferViewContents&) = delete; + + explicit inline ArrayBufferViewContents(v8::Local value); + explicit inline ArrayBufferViewContents(v8::Local value); + explicit inline ArrayBufferViewContents(v8::Local abv); + inline void Read(v8::Local abv); + inline void ReadValue(v8::Local buf); + + inline bool WasDetached() const { return was_detached_; } + inline const T* data() const { return data_; } + inline size_t length() const { return length_; } + + private: + // Declaring operator new and delete as deleted is not spec compliant. + // Therefore, declare them private instead to disable dynamic alloc. + void* operator new(size_t size); + void* operator new[](size_t size); + void operator delete(void*, size_t); + void operator delete[](void*, size_t); + + T stack_storage_[kStackStorageSize]; + T* data_ = nullptr; + size_t length_ = 0; + bool was_detached_ = false; +}; + +class Utf8Value : public MaybeStackBuffer { + public: + explicit Utf8Value(v8::Isolate* isolate, v8::Local value); + + inline bool operator==(const char* a) const { return strcmp(out(), a) == 0; } + inline bool operator!=(const char* a) const { return !(*this == a); } +}; + +class TwoByteValue : public MaybeStackBuffer { + public: + explicit TwoByteValue(v8::Isolate* isolate, v8::Local value); +}; + +class BufferValue : public MaybeStackBuffer { + public: + explicit BufferValue(v8::Isolate* isolate, v8::Local value); + + inline std::string ToString() const { return std::string(out(), length()); } +}; + +#define SPREAD_BUFFER_ARG(val, name) \ + CHECK((val)->IsArrayBufferView()); \ + v8::Local name = (val).As(); \ + const size_t name##_offset = name->ByteOffset(); \ + const size_t name##_length = name->ByteLength(); \ + char* const name##_data = \ + static_cast(name->Buffer()->Data()) + name##_offset; \ + if (name##_length > 0) CHECK_NE(name##_data, nullptr); + +// Use this when a variable or parameter is unused in order to explicitly +// silence a compiler warning about that. +template inline void USE(T&&) {} + +template +struct OnScopeLeaveImpl { + Fn fn_; + bool active_; + + explicit OnScopeLeaveImpl(Fn&& fn) : fn_(std::move(fn)), active_(true) {} + ~OnScopeLeaveImpl() { if (active_) fn_(); } + + OnScopeLeaveImpl(const OnScopeLeaveImpl& other) = delete; + OnScopeLeaveImpl& operator=(const OnScopeLeaveImpl& other) = delete; + OnScopeLeaveImpl(OnScopeLeaveImpl&& other) + : fn_(std::move(other.fn_)), active_(other.active_) { + other.active_ = false; + } +}; + +// Run a function when exiting the current scope. Used like this: +// auto on_scope_leave = OnScopeLeave([&] { +// // ... run some code ... +// }); +template +inline MUST_USE_RESULT OnScopeLeaveImpl OnScopeLeave(Fn&& fn) { + return OnScopeLeaveImpl{std::move(fn)}; +} + +// Simple RAII wrapper for contiguous data that uses malloc()/free(). +template +struct MallocedBuffer { + T* data; + size_t size; + + T* release() { + T* ret = data; + data = nullptr; + return ret; + } + + void Truncate(size_t new_size) { + CHECK_LE(new_size, size); + size = new_size; + } + + void Realloc(size_t new_size) { + Truncate(new_size); + data = UncheckedRealloc(data, new_size); + } + + bool is_empty() const { return data == nullptr; } + + MallocedBuffer() : data(nullptr), size(0) {} + explicit MallocedBuffer(size_t size) : data(Malloc(size)), size(size) {} + MallocedBuffer(T* data, size_t size) : data(data), size(size) {} + MallocedBuffer(MallocedBuffer&& other) : data(other.data), size(other.size) { + other.data = nullptr; + } + MallocedBuffer& operator=(MallocedBuffer&& other) { + this->~MallocedBuffer(); + return *new(this) MallocedBuffer(std::move(other)); + } + ~MallocedBuffer() { + free(data); + } + MallocedBuffer(const MallocedBuffer&) = delete; + MallocedBuffer& operator=(const MallocedBuffer&) = delete; +}; + +template +class NonCopyableMaybe { + public: + NonCopyableMaybe() : empty_(true) {} + explicit NonCopyableMaybe(T&& value) + : empty_(false), + value_(std::move(value)) {} + + bool IsEmpty() const { + return empty_; + } + + const T* get() const { + return empty_ ? nullptr : &value_; + } + + const T* operator->() const { + CHECK(!empty_); + return &value_; + } + + T&& Release() { + CHECK_EQ(empty_, false); + empty_ = true; + return std::move(value_); + } + + private: + bool empty_; + T value_; +}; + +// Test whether some value can be called with (). +template +struct is_callable : std::is_function { }; + +template +struct is_callable::value + >::type> : std::true_type { }; + +template +struct FunctionDeleter { + void operator()(T* pointer) const { function(pointer); } + typedef std::unique_ptr Pointer; +}; + +template +using DeleteFnPtr = typename FunctionDeleter::Pointer; + +std::vector SplitString(const std::string_view in, + const std::string_view delim); + +inline v8::MaybeLocal ToV8Value(v8::Local context, + std::string_view str, + v8::Isolate* isolate = nullptr); +template ::is_specialized, bool>::type> +inline v8::MaybeLocal ToV8Value(v8::Local context, + const T& number, + v8::Isolate* isolate = nullptr); +template +inline v8::MaybeLocal ToV8Value(v8::Local context, + const std::vector& vec, + v8::Isolate* isolate = nullptr); +template +inline v8::MaybeLocal ToV8Value(v8::Local context, + const std::set& set, + v8::Isolate* isolate = nullptr); +template +inline v8::MaybeLocal ToV8Value(v8::Local context, + const std::unordered_map& map, + v8::Isolate* isolate = nullptr); + +// These macros expects a `Isolate* isolate` and a `Local context` +// to be in the scope. +#define READONLY_PROPERTY(obj, name, value) \ + do { \ + obj->DefineOwnProperty( \ + context, FIXED_ONE_BYTE_STRING(isolate, name), value, v8::ReadOnly) \ + .Check(); \ + } while (0) + +#define READONLY_DONT_ENUM_PROPERTY(obj, name, var) \ + do { \ + obj->DefineOwnProperty( \ + context, \ + OneByteString(isolate, name), \ + var, \ + static_cast(v8::ReadOnly | v8::DontEnum)) \ + .Check(); \ + } while (0) + +#define READONLY_FALSE_PROPERTY(obj, name) \ + READONLY_PROPERTY(obj, name, v8::False(isolate)) + +#define READONLY_TRUE_PROPERTY(obj, name) \ + READONLY_PROPERTY(obj, name, v8::True(isolate)) + +#define READONLY_STRING_PROPERTY(obj, name, str) \ + READONLY_PROPERTY(obj, name, ToV8Value(context, str).ToLocalChecked()) + +// Variation on NODE_DEFINE_CONSTANT that sets a String value. +#define NODE_DEFINE_STRING_CONSTANT(target, name, constant) \ + do { \ + v8::Isolate* isolate = target->GetIsolate(); \ + v8::Local constant_name = \ + v8::String::NewFromUtf8(isolate, name).ToLocalChecked(); \ + v8::Local constant_value = \ + v8::String::NewFromUtf8(isolate, constant).ToLocalChecked(); \ + v8::PropertyAttribute constant_attributes = \ + static_cast(v8::ReadOnly | v8::DontDelete); \ + target \ + ->DefineOwnProperty(isolate->GetCurrentContext(), \ + constant_name, \ + constant_value, \ + constant_attributes) \ + .Check(); \ + } while (0) + +enum class Endianness { LITTLE, BIG }; + +inline Endianness GetEndianness() { + // Constant-folded by the compiler. + const union { + uint8_t u8[2]; + uint16_t u16; + } u = {{1, 0}}; + return u.u16 == 1 ? Endianness::LITTLE : Endianness::BIG; +} + +inline bool IsLittleEndian() { + return GetEndianness() == Endianness::LITTLE; +} + +inline bool IsBigEndian() { + return GetEndianness() == Endianness::BIG; +} + +// Round up a to the next highest multiple of b. +template +constexpr T RoundUp(T a, T b) { + return a % b != 0 ? a + b - (a % b) : a; +} + +// Align ptr to an `alignment`-bytes boundary. +template +constexpr T* AlignUp(T* ptr, U alignment) { + return reinterpret_cast( + RoundUp(reinterpret_cast(ptr), alignment)); +} + +class SlicedArguments : public MaybeStackBuffer> { + public: + inline explicit SlicedArguments( + const v8::FunctionCallbackInfo& args, size_t start = 0); +}; + +// Convert a v8::PersistentBase, e.g. v8::Global, to a Local, with an extra +// optimization for strong persistent handles. +class PersistentToLocal { + public: + // If persistent.IsWeak() == false, then do not call persistent.Reset() + // while the returned Local is still in scope, it will destroy the + // reference to the object. + template + static inline v8::Local Default( + v8::Isolate* isolate, + const v8::PersistentBase& persistent) { + if (persistent.IsWeak()) { + return PersistentToLocal::Weak(isolate, persistent); + } else { + return PersistentToLocal::Strong(persistent); + } + } + + // Unchecked conversion from a non-weak Persistent to Local, + // use with care! + // + // Do not call persistent.Reset() while the returned Local is still in + // scope, it will destroy the reference to the object. + template + static inline v8::Local Strong( + const v8::PersistentBase& persistent) { + DCHECK(!persistent.IsWeak()); + return *reinterpret_cast*>( + const_cast*>(&persistent)); + } + + template + static inline v8::Local Weak( + v8::Isolate* isolate, + const v8::PersistentBase& persistent) { + return v8::Local::New(isolate, persistent); + } +}; + +// Can be used as a key for std::unordered_map when lookup performance is more +// important than size and the keys are statically used to avoid redundant hash +// computations. +class FastStringKey { + public: + constexpr explicit FastStringKey(std::string_view name); + + struct Hash { + constexpr size_t operator()(const FastStringKey& key) const; + }; + constexpr bool operator==(const FastStringKey& other) const; + + constexpr std::string_view as_string_view() const; + + private: + static constexpr size_t HashImpl(std::string_view str); + + const std::string_view name_; + const size_t cached_hash_; +}; + +// Like std::static_pointer_cast but for unique_ptr with the default deleter. +template +std::unique_ptr static_unique_pointer_cast(std::unique_ptr&& ptr) { + return std::unique_ptr(static_cast(ptr.release())); +} + +#define MAYBE_FIELD_PTR(ptr, field) ptr == nullptr ? nullptr : &(ptr->field) + +// Returns a non-zero code if it fails to open or read the file, +// aborts if it fails to close the file. +int ReadFileSync(std::string* result, const char* path); + +v8::Local NewFunctionTemplate( + v8::Isolate* isolate, + v8::FunctionCallback callback, + v8::Local signature = v8::Local(), + v8::ConstructorBehavior behavior = v8::ConstructorBehavior::kAllow, + v8::SideEffectType side_effect = v8::SideEffectType::kHasSideEffect, + const v8::CFunction* c_function = nullptr); + +// Convenience methods for NewFunctionTemplate(). +void SetMethod(v8::Local context, + v8::Local that, + const char* name, + v8::FunctionCallback callback); +// Similar to SetProtoMethod but without receiver signature checks. +void SetMethod(v8::Isolate* isolate, + v8::Local that, + const char* name, + v8::FunctionCallback callback); + +void SetFastMethod(v8::Local context, + v8::Local that, + const char* name, + v8::FunctionCallback slow_callback, + const v8::CFunction* c_function); +void SetFastMethodNoSideEffect(v8::Local context, + v8::Local that, + const char* name, + v8::FunctionCallback slow_callback, + const v8::CFunction* c_function); + +void SetProtoMethod(v8::Isolate* isolate, + v8::Local that, + const char* name, + v8::FunctionCallback callback); + +void SetInstanceMethod(v8::Isolate* isolate, + v8::Local that, + const char* name, + v8::FunctionCallback callback); + +// Safe variants denote the function has no side effects. +void SetMethodNoSideEffect(v8::Local context, + v8::Local that, + const char* name, + v8::FunctionCallback callback); +void SetProtoMethodNoSideEffect(v8::Isolate* isolate, + v8::Local that, + const char* name, + v8::FunctionCallback callback); + +enum class SetConstructorFunctionFlag { + NONE, + SET_CLASS_NAME, +}; + +void SetConstructorFunction(v8::Local context, + v8::Local that, + const char* name, + v8::Local tmpl, + SetConstructorFunctionFlag flag = + SetConstructorFunctionFlag::SET_CLASS_NAME); + +void SetConstructorFunction(v8::Local context, + v8::Local that, + v8::Local name, + v8::Local tmpl, + SetConstructorFunctionFlag flag = + SetConstructorFunctionFlag::SET_CLASS_NAME); + +} // namespace node + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_UTIL_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h index bc4d9f303d..ac0182c1dc 100644 --- a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h +++ b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h @@ -24,7 +24,12 @@ ****************************************************************************/ #pragma once + +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY #include "ark_runtime/jsvm.h" +#else +#include "jsvm.h" +#endif #include "platform/openharmony/napi/native_common.h" // Empty value so that macros here are able to return NULL or void diff --git a/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h index 4202d8838d..027ef87ab8 100644 --- a/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h @@ -26,7 +26,7 @@ #pragma once #include "CommonHeader.h" -#if !defined(_WIN) +#if !defined(_WIN) && CC_PLATFORM == CC_PLATFORM_OPENHARMONY #include #ifndef LOGI @@ -36,9 +36,9 @@ #define LOGD(...) ((void) OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) #endif #else - #define LOGI - #define LOGW - #define LOGE + #define LOGI CC_LOG_INFO + #define LOGW CC_LOG_WARNING + #define LOGE CC_LOG_ERROR #endif namespace se { class Class; @@ -143,4 +143,4 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier- jsbFinalizeWrapper(nativeObject, funcName, #funcName); \ } -#define _SE(name) &(name##RegistryStruct) \ No newline at end of file +#define _SE(name) &(name##RegistryStruct) diff --git a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp index 309cf49a51..69e76c5888 100644 --- a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp @@ -30,7 +30,12 @@ #include "State.h" #include "Utils.h" #include "CommonHeader.h" + +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY #include "ark_runtime/jsvm.h" +#else +#include "jsvm.h" +#endif #define _EXPOSE_GC "__jsb_gc__" @@ -191,7 +196,7 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, JSVM_Value jsvmStr; NODE_API_CALL(status, _env, OH_JSVM_CreateStringUtf8(_env, scriptStr, length, &jsvmStr)); if(status != JSVM_OK) { - SE_LOGE("ScriptEngine::evalString, create string failed, fileName = %{public}s", fileName); + CC_LOG_ERROR("ScriptEngine::evalString, create string failed, fileName = %s", fileName); return false; } @@ -211,14 +216,14 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, OH_JSVM_CompileScriptWithOrigin(_env, jsvmStr, cachedData, cacheLength, false, &cacheRejected,&scriptOrigin, &compiledScript)); if(status != JSVM_OK) { - SE_LOGE("ScriptEngine::evalSting, compile failed, fileName = %{public}s", fileName); + CC_LOG_ERROR("ScriptEngine::evalSting, compile failed, fileName = %s", fileName); return false; } JSVM_Value result; NODE_API_CALL(status, _env, OH_JSVM_RunScript(_env, compiledScript, &result)); if(status != JSVM_OK) { - SE_LOGE("ScriptEngine::evelSting, run failed, fileName = %{public}s", fileName); + CC_LOG_ERROR("ScriptEngine::evelSting, run failed, fileName = %s", fileName); return false; } @@ -248,6 +253,10 @@ bool ScriptEngine::init() { NODE_API_CALL(status, _env, OH_JSVM_OpenEnvScope(_env, &_envScope)); se::AutoHandleScope hs; + + uint32_t jsvmVersion = 0; + NODE_API_CALL(status, _env, OH_JSVM_GetVersion(_env, &jsvmVersion)); + SE_LOGD("Initializing JSVM, version: %u\n", jsvmVersion); Object::setup(); NativePtrToObjectMap::init(); @@ -439,13 +448,18 @@ bool ScriptEngine::saveByteCodeToFile(const std::string &path, const std::string return true; } +bool ScriptEngine::runByteCodeFile(const std::string &pathBc, Value *ret /* = nullptr */) { + // TO BE IMPLEMENTED + return false; +} + void ScriptEngine::clearException() { //not impl return; } void ScriptEngine::garbageCollect() { - SE_LOGD("GC begin ..., (js->native map) size: %{public}d",(int)NativePtrToObjectMap::size()); + CC_LOG_DEBUG("GC begin ..., (js->native map) size: %d",(int)NativePtrToObjectMap::size()); if(_gcFunc == nullptr) { JSVM_Status status; @@ -454,7 +468,7 @@ void ScriptEngine::garbageCollect() { _gcFunc->call({}, nullptr); } - SE_LOGD("GC end ..., (js->native map) size: %{public}d",(int)NativePtrToObjectMap::size()); + CC_LOG_DEBUG("GC end ..., (js->native map) size: %d",(int)NativePtrToObjectMap::size()); } bool ScriptEngine::isGarbageCollecting() const { diff --git a/native/cocos/bindings/jswrapper/jsvm/Utils.cpp b/native/cocos/bindings/jswrapper/jsvm/Utils.cpp index f903b2864f..34b26152b0 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Utils.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/Utils.cpp @@ -227,10 +227,10 @@ void logJsException(JSVM_Env env, const char *file, int line) { std::string stackStr = jsToString(stack); std::string messageStr = jsToString(message); - SE_LOGE("JS exception occurred at %{public}s:%{public}d\n\ - [name]: %{public}s\n\ - [message]: %{public}s\n\ - [stack]: %{public}s", + CC_LOG_ERROR("JS exception occurred at %s:%d\n\ + [name]: %s\n\ + [message]: %s\n\ + [stack]: %s", file, line, nameStr.c_str(), messageStr.c_str(), stackStr.c_str()); auto exceptionCallback = ScriptEngine::getInstance()->getExceptionCallback(); exceptionCallback("", messageStr.c_str(), stackStr.c_str()); diff --git a/native/external-config.json b/native/external-config.json index c2f846c095..aa47840a8c 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -3,6 +3,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3.8.6-5" + "checkout": "v3.8.6-6" } } \ No newline at end of file diff --git a/templates/common/CMakeLists.txt b/templates/common/CMakeLists.txt index c96ac82483..f39f6e31ee 100755 --- a/templates/common/CMakeLists.txt +++ b/templates/common/CMakeLists.txt @@ -9,12 +9,13 @@ set(TARGET_IOS_VERSION "11.0" CACHE STRING "Target iOS version" FORCE) set(CMAKE_CXX_STANDARD 17) option(CC_DEBUG_FORCE "Force enable CC_DEBUG in release mode" OFF) option(USE_SE_V8 "Use V8 JavaScript Engine" ON) +option(USE_SE_JSVM "Use JSVM JavaScript Engine" OFF) +option(USE_SE_JSC "Use JavaScriptCore on MacOSX/iOS" OFF) option(USE_V8_DEBUGGER "Compile v8 inspector ws server" ON) option(USE_V8_DEBUGGER_FORCE "Force enable debugger in release mode" OFF) option(USE_SOCKET "Enable WebSocket & SocketIO" ON) option(USE_AUDIO "Enable Audio" ON) #Enable AudioEngine option(USE_EDIT_BOX "Enable EditBox" ON) -option(USE_SE_JSC "Use JavaScriptCore on MacOSX/iOS" OFF) option(USE_VIDEO "Enable VideoPlayer Component" ON) option(USE_WEBVIEW "Enable WebView Component" ON) option(USE_MIDDLEWARE "Enable Middleware" ON)