mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-21 16:12:40 +08:00
Support JSVM API on non-openharmony platforms which will make debugging JSVM API easier. (#18398)
* Support JSVM API on non-openharmony platforms which will make debugging JSVM API easier. JSVM v8 backend source code is copied from https://gitee.com/openharmony/third_party_node/tree/OpenHarmony-v5.0.2-Release * CI test JSVM v8 backend.
This commit is contained in:
@@ -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
|
||||
|
||||
+25
-11
@@ -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
|
||||
|
||||
@@ -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 <typename R, typename... Args>
|
||||
template <typename Fn>
|
||||
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
|
||||
CallbackQueue<R, Args...>::CreateCallback(Fn&& fn, CallbackFlags::Flags flags) {
|
||||
return std::make_unique<CallbackImpl<Fn>>(std::move(fn), flags);
|
||||
}
|
||||
|
||||
template <typename R, typename... Args>
|
||||
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
|
||||
CallbackQueue<R, Args...>::Shift() {
|
||||
std::unique_ptr<Callback> ret = std::move(head_);
|
||||
if (ret) {
|
||||
head_ = ret->get_next();
|
||||
if (!head_)
|
||||
tail_ = nullptr; // The queue is now empty.
|
||||
size_--;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
template <typename R, typename... Args>
|
||||
void CallbackQueue<R, Args...>::Push(std::unique_ptr<Callback> 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 <typename R, typename... Args>
|
||||
void CallbackQueue<R, Args...>::ConcatMove(CallbackQueue<R, Args...>&& 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 <typename R, typename... Args>
|
||||
size_t CallbackQueue<R, Args...>::size() const {
|
||||
return size_.load();
|
||||
}
|
||||
|
||||
template <typename R, typename... Args>
|
||||
CallbackQueue<R, Args...>::Callback::Callback(CallbackFlags::Flags flags)
|
||||
: flags_(flags) {}
|
||||
|
||||
template <typename R, typename... Args>
|
||||
CallbackFlags::Flags CallbackQueue<R, Args...>::Callback::flags() const {
|
||||
return flags_;
|
||||
}
|
||||
|
||||
template <typename R, typename... Args>
|
||||
std::unique_ptr<typename CallbackQueue<R, Args...>::Callback>
|
||||
CallbackQueue<R, Args...>::Callback::get_next() {
|
||||
return std::move(next_);
|
||||
}
|
||||
|
||||
template <typename R, typename... Args>
|
||||
void CallbackQueue<R, Args...>::Callback::set_next(
|
||||
std::unique_ptr<Callback> next) {
|
||||
next_ = std::move(next);
|
||||
}
|
||||
|
||||
template <typename R, typename... Args>
|
||||
template <typename Fn>
|
||||
CallbackQueue<R, Args...>::CallbackImpl<Fn>::CallbackImpl(
|
||||
Fn&& callback, CallbackFlags::Flags flags)
|
||||
: Callback(flags),
|
||||
callback_(std::move(callback)) {}
|
||||
|
||||
template <typename R, typename... Args>
|
||||
template <typename Fn>
|
||||
R CallbackQueue<R, Args...>::CallbackImpl<Fn>::Call(Args... args) {
|
||||
return callback_(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
} // namespace node
|
||||
|
||||
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_CALLBACK_QUEUE_INL_H_
|
||||
@@ -0,0 +1,78 @@
|
||||
#ifndef SRC_CALLBACK_QUEUE_H_
|
||||
#define SRC_CALLBACK_QUEUE_H_
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include <atomic>
|
||||
|
||||
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 <typename R, typename... Args>
|
||||
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<Callback> get_next();
|
||||
inline void set_next(std::unique_ptr<Callback> next);
|
||||
|
||||
CallbackFlags::Flags flags_;
|
||||
std::unique_ptr<Callback> next_;
|
||||
|
||||
friend class CallbackQueue;
|
||||
};
|
||||
|
||||
template <typename Fn>
|
||||
inline std::unique_ptr<Callback> CreateCallback(
|
||||
Fn&& fn, CallbackFlags::Flags);
|
||||
|
||||
inline std::unique_ptr<Callback> Shift();
|
||||
inline void Push(std::unique_ptr<Callback> 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 <typename Fn>
|
||||
class CallbackImpl final : public Callback {
|
||||
public:
|
||||
CallbackImpl(Fn&& callback, CallbackFlags::Flags flags);
|
||||
R Call(Args... args) override;
|
||||
|
||||
private:
|
||||
Fn callback_;
|
||||
};
|
||||
|
||||
std::atomic<size_t> size_ {0};
|
||||
std::unique_ptr<Callback> head_;
|
||||
Callback* tail_ = nullptr;
|
||||
};
|
||||
|
||||
} // namespace node
|
||||
|
||||
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_CALLBACK_QUEUE_H_
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,658 @@
|
||||
#ifndef SRC_JS_NATIVE_API_V8_H_
|
||||
#define SRC_JS_NATIVE_API_V8_H_
|
||||
|
||||
#include <variant>
|
||||
#include <unordered_set>
|
||||
#include <stack>
|
||||
#include <mutex>
|
||||
#include "jsvm_types.h"
|
||||
#include "js_native_api_v8_internals.h"
|
||||
#include "callback_queue.h"
|
||||
|
||||
#ifdef TARGET_OHOS
|
||||
#include <unistd.h>
|
||||
extern "C" void ReportData(uint32_t resType, int64_t value,
|
||||
const std::unordered_map<std::string, std::string>& 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::Local<v8::Script>, v8::Global<v8::Script>>;
|
||||
using DataType = enum { kJsvmScript };
|
||||
|
||||
template<typename T>
|
||||
JSVM_Data__(T ptr, bool retained, DataType type = kJsvmScript)
|
||||
: taggedPointer(ptr),
|
||||
isGlobal(retained),
|
||||
type(type) {}
|
||||
|
||||
template<class T>
|
||||
v8::Local<T> ToV8Local(v8::Isolate *isolate) {
|
||||
if (isGlobal) {
|
||||
return v8::Local<T>::New(isolate, std::get<v8::Global<T>>(taggedPointer));
|
||||
} else {
|
||||
return std::get<v8::Local<T>>(taggedPointer);
|
||||
}
|
||||
}
|
||||
|
||||
SourcePtr taggedPointer;
|
||||
bool isGlobal = false;
|
||||
DataType type;
|
||||
};
|
||||
|
||||
struct JSVM_Env__ {
|
||||
explicit JSVM_Env__(v8::Local<v8::Context> 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 <typename Fn>
|
||||
// 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<JSVM_Env__*>(data)->RunAndClearInterrupts();
|
||||
// }, this);
|
||||
// }
|
||||
//
|
||||
// void RunAndClearInterrupts();
|
||||
//
|
||||
// v8impl::Agent* inspector_agent() { return inspector_agent_; }
|
||||
|
||||
v8::Platform* platform();
|
||||
|
||||
inline v8::Local<v8::Context> 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<v8::Value> 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 <typename T, typename U = decltype(HandleThrow)>
|
||||
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<typename T>
|
||||
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<JSVM_Data__*>());
|
||||
}
|
||||
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<v8::Context> context_persistent;
|
||||
|
||||
v8impl::Persistent<v8::Value> 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<v8impl::RefTracker*> 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<std::pair<int, std::vector<JSVM_Data__*>>> dataStack;
|
||||
|
||||
private:
|
||||
v8impl::Agent* inspector_agent_;
|
||||
typedef node::CallbackQueue<void, JSVM_Env__*> 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<v8::Value> v8value = v8impl::V8LocalValueFromJsValue((src)); \
|
||||
RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), JSVM_INVALID_ARG); \
|
||||
(result) = v8value.As<v8::Function>(); \
|
||||
} 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<v8::Value>) == sizeof(JSVM_Value),
|
||||
"Cannot convert between v8::Local<v8::Value> and JSVM_Value");
|
||||
|
||||
inline JSVM_Value JsValueFromV8LocalValue(v8::Local<v8::Value> local) {
|
||||
return reinterpret_cast<JSVM_Value>(*local);
|
||||
}
|
||||
|
||||
inline v8::Local<v8::Value> V8LocalValueFromJsValue(JSVM_Value v) {
|
||||
v8::Local<v8::Value> local;
|
||||
memcpy(static_cast<void*>(&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 <typename... Args>
|
||||
Reference(JSVM_Env env, v8::Local<v8::Value> value, Args&&... args);
|
||||
|
||||
public:
|
||||
static Reference* New(JSVM_Env env,
|
||||
v8::Local<v8::Value> 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<v8::Value> Get();
|
||||
void Delete();
|
||||
|
||||
protected:
|
||||
void Finalize() override;
|
||||
|
||||
private:
|
||||
static void WeakCallback(const v8::WeakCallbackInfo<Reference>& data);
|
||||
|
||||
void SetWeak();
|
||||
|
||||
v8impl::Persistent<v8::Value> 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> v8_value = v8impl::V8LocalValueFromJsValue(propertyCfg->namedPropertyData);
|
||||
v8impl::Reference* reference = v8impl::Reference::New(env, v8_value, 1, v8impl::Ownership::kUserland);
|
||||
newPropertyCfg->namedPropertyData_ = reinterpret_cast<JSVM_Ref>(reference);
|
||||
}
|
||||
|
||||
if (propertyCfg->indexedPropertyData != nullptr) {
|
||||
v8::Local<v8::Value> v8_value = v8impl::V8LocalValueFromJsValue(propertyCfg->indexedPropertyData);
|
||||
v8impl::Reference* reference = v8impl::Reference::New(env, v8_value, 1, v8impl::Ownership::kUserland);
|
||||
newPropertyCfg->indexedPropertyData_ = reinterpret_cast<JSVM_Ref>(reference);
|
||||
}
|
||||
}
|
||||
|
||||
return newPropertyCfg;
|
||||
}
|
||||
|
||||
inline void CfgFinalizedCallback(JSVM_Env env, void* finalizeData, void* finalizeHint)
|
||||
{
|
||||
auto cfg = reinterpret_cast<JSVM_PropertyHandlerCfgStruct *>(finalizeData);
|
||||
if (cfg->namedPropertyData_ != nullptr) {
|
||||
delete reinterpret_cast<v8impl::Reference*>(cfg->namedPropertyData_);
|
||||
}
|
||||
if (cfg->indexedPropertyData_ != nullptr) {
|
||||
delete reinterpret_cast<v8impl::Reference*>(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<std::string, std::string> 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_
|
||||
@@ -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 <typename T>
|
||||
using Persistent = v8::Global<T>;
|
||||
|
||||
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_
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 <stddef.h> // NOLINT(modernize-deprecated-headers)
|
||||
#include <stdint.h> // NOLINT(modernize-deprecated-headers)
|
||||
#include <stdbool.h> // 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 */
|
||||
@@ -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_
|
||||
@@ -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 <io.h> // _S_IREAD _S_IWRITE
|
||||
#include <time.h>
|
||||
#ifndef S_IRUSR
|
||||
#define S_IRUSR _S_IREAD
|
||||
#endif // S_IRUSR
|
||||
#ifndef S_IWUSR
|
||||
#define S_IWUSR _S_IWRITE
|
||||
#endif // S_IWUSR
|
||||
#else
|
||||
#include <sys/time.h>
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
|
||||
#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 <typename T>
|
||||
static void MakeUtf8String(Isolate* isolate,
|
||||
Local<Value> value,
|
||||
MaybeStackBuffer<T>* target) {
|
||||
Local<String> 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> value) {
|
||||
if (value.IsEmpty())
|
||||
return;
|
||||
|
||||
MakeUtf8String(isolate, value, this);
|
||||
}
|
||||
|
||||
|
||||
TwoByteValue::TwoByteValue(Isolate* isolate, Local<Value> value) {
|
||||
if (value.IsEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Local<String> 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> 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<ArrayBufferView>()->ByteLength();
|
||||
// Leave place for the terminating '\0' byte.
|
||||
AllocateSufficientStorage(len + 1);
|
||||
value.As<ArrayBufferView>()->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<std::string_view> SplitString(const std::string_view in,
|
||||
const std::string_view delim) {
|
||||
std::vector<std::string_view> 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<v8::String> 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<v8::FunctionTemplate> NewFunctionTemplate(
|
||||
v8::Isolate* isolate,
|
||||
v8::FunctionCallback callback,
|
||||
Local<v8::Signature> signature,
|
||||
v8::ConstructorBehavior behavior,
|
||||
v8::SideEffectType side_effect_type,
|
||||
const v8::CFunction* c_function) {
|
||||
return v8::FunctionTemplate::New(isolate,
|
||||
callback,
|
||||
Local<v8::Value>(),
|
||||
signature,
|
||||
0,
|
||||
behavior,
|
||||
side_effect_type,
|
||||
c_function);
|
||||
}
|
||||
|
||||
void SetMethod(Local<v8::Context> context,
|
||||
Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback) {
|
||||
Isolate* isolate = context->GetIsolate();
|
||||
Local<v8::Function> function =
|
||||
NewFunctionTemplate(isolate,
|
||||
callback,
|
||||
Local<v8::Signature>(),
|
||||
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<v8::String> 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<v8::Template> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback) {
|
||||
Local<v8::FunctionTemplate> t =
|
||||
NewFunctionTemplate(isolate,
|
||||
callback,
|
||||
Local<v8::Signature>(),
|
||||
v8::ConstructorBehavior::kThrow,
|
||||
v8::SideEffectType::kHasSideEffect);
|
||||
// kInternalized strings are created in the old space.
|
||||
const v8::NewStringType type = v8::NewStringType::kInternalized;
|
||||
Local<v8::String> name_string =
|
||||
v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
|
||||
that->Set(name_string, t);
|
||||
}
|
||||
|
||||
void SetFastMethod(Local<v8::Context> context,
|
||||
Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback slow_callback,
|
||||
const v8::CFunction* c_function) {
|
||||
Isolate* isolate = context->GetIsolate();
|
||||
Local<v8::Function> function =
|
||||
NewFunctionTemplate(isolate,
|
||||
slow_callback,
|
||||
Local<v8::Signature>(),
|
||||
v8::ConstructorBehavior::kThrow,
|
||||
v8::SideEffectType::kHasSideEffect,
|
||||
c_function)
|
||||
->GetFunction(context)
|
||||
.ToLocalChecked();
|
||||
const v8::NewStringType type = v8::NewStringType::kInternalized;
|
||||
Local<v8::String> name_string =
|
||||
v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
|
||||
that->Set(context, name_string, function).Check();
|
||||
}
|
||||
|
||||
void SetFastMethodNoSideEffect(Local<v8::Context> context,
|
||||
Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback slow_callback,
|
||||
const v8::CFunction* c_function) {
|
||||
Isolate* isolate = context->GetIsolate();
|
||||
Local<v8::Function> function =
|
||||
NewFunctionTemplate(isolate,
|
||||
slow_callback,
|
||||
Local<v8::Signature>(),
|
||||
v8::ConstructorBehavior::kThrow,
|
||||
v8::SideEffectType::kHasNoSideEffect,
|
||||
c_function)
|
||||
->GetFunction(context)
|
||||
.ToLocalChecked();
|
||||
const v8::NewStringType type = v8::NewStringType::kInternalized;
|
||||
Local<v8::String> name_string =
|
||||
v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
|
||||
that->Set(context, name_string, function).Check();
|
||||
}
|
||||
|
||||
void SetMethodNoSideEffect(Local<v8::Context> context,
|
||||
Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback) {
|
||||
Isolate* isolate = context->GetIsolate();
|
||||
Local<v8::Function> function =
|
||||
NewFunctionTemplate(isolate,
|
||||
callback,
|
||||
Local<v8::Signature>(),
|
||||
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<v8::String> 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<v8::FunctionTemplate> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback) {
|
||||
Local<v8::Signature> signature = v8::Signature::New(isolate, that);
|
||||
Local<v8::FunctionTemplate> 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<v8::String> 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<v8::FunctionTemplate> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback) {
|
||||
Local<v8::Signature> signature = v8::Signature::New(isolate, that);
|
||||
Local<v8::FunctionTemplate> 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<v8::String> 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<v8::FunctionTemplate> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback) {
|
||||
Local<v8::Signature> signature = v8::Signature::New(isolate, that);
|
||||
Local<v8::FunctionTemplate> 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<v8::String> name_string =
|
||||
v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
|
||||
that->InstanceTemplate()->Set(name_string, t);
|
||||
t->SetClassName(name_string);
|
||||
}
|
||||
|
||||
void SetConstructorFunction(Local<v8::Context> context,
|
||||
Local<v8::Object> that,
|
||||
const char* name,
|
||||
Local<v8::FunctionTemplate> tmpl,
|
||||
SetConstructorFunctionFlag flag) {
|
||||
Isolate* isolate = context->GetIsolate();
|
||||
SetConstructorFunction(
|
||||
context, that, OneByteString(isolate, name), tmpl, flag);
|
||||
}
|
||||
|
||||
void SetConstructorFunction(Local<v8::Context> context,
|
||||
Local<v8::Object> that,
|
||||
Local<v8::String> name,
|
||||
Local<v8::FunctionTemplate> 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<const char*>(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<String> 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
|
||||
@@ -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 <climits>
|
||||
#include <cstddef>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#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 <typename T>
|
||||
inline T* UncheckedRealloc(T* pointer, size_t n);
|
||||
template <typename T>
|
||||
inline T* UncheckedMalloc(size_t n);
|
||||
template <typename T>
|
||||
inline T* UncheckedCalloc(size_t n);
|
||||
|
||||
// Same things, but aborts immediately instead of returning nullptr when
|
||||
// no memory is available.
|
||||
template <typename T>
|
||||
inline T* Realloc(T* pointer, size_t n);
|
||||
template <typename T>
|
||||
inline T* Malloc(size_t n);
|
||||
template <typename T>
|
||||
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 <typename T>
|
||||
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<v8::Value> v);
|
||||
|
||||
// TAILQ-style intrusive list node.
|
||||
template <typename T>
|
||||
class ListNode;
|
||||
|
||||
// TAILQ-style intrusive list head.
|
||||
template <typename T, ListNode<T> (T::*M)>
|
||||
class ListHead;
|
||||
|
||||
template <typename T>
|
||||
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 <typename U, ListNode<U> (U::*M)> friend class ListHead;
|
||||
friend int GenDebugSymbols();
|
||||
ListNode* prev_;
|
||||
ListNode* next_;
|
||||
};
|
||||
|
||||
template <typename T, ListNode<T> (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<T>* node);
|
||||
ListNode<T>* 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<T> head_;
|
||||
};
|
||||
|
||||
// The helper is for doing safe downcasts from base types to derived types.
|
||||
template <typename Inner, typename Outer>
|
||||
class ContainerOfHelper {
|
||||
public:
|
||||
inline ContainerOfHelper(Inner Outer::*field, Inner* pointer);
|
||||
template <typename TypeName>
|
||||
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 <typename Inner, typename Outer>
|
||||
constexpr ContainerOfHelper<Inner, Outer> 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<v8::String> Get(v8::Isolate* isolate,
|
||||
v8::Local<v8::String> key) const = 0;
|
||||
virtual v8::Maybe<std::string> Get(const char* key) const = 0;
|
||||
virtual void Set(v8::Isolate* isolate,
|
||||
v8::Local<v8::String> key,
|
||||
v8::Local<v8::String> value) = 0;
|
||||
virtual int32_t Query(v8::Isolate* isolate,
|
||||
v8::Local<v8::String> key) const = 0;
|
||||
virtual int32_t Query(const char* key) const = 0;
|
||||
virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0;
|
||||
virtual v8::Local<v8::Array> Enumerate(v8::Isolate* isolate) const = 0;
|
||||
|
||||
virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const;
|
||||
virtual v8::Maybe<bool> AssignFromObject(v8::Local<v8::Context> context,
|
||||
v8::Local<v8::Object> entries);
|
||||
v8::Maybe<bool> AssignToObject(v8::Isolate* isolate,
|
||||
v8::Local<v8::Context> context,
|
||||
v8::Local<v8::Object> object);
|
||||
|
||||
static std::shared_ptr<KVStore> CreateMapKVStore();
|
||||
};
|
||||
|
||||
// Convenience wrapper around v8::String::NewFromOneByte().
|
||||
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
|
||||
const char* data,
|
||||
int length = -1);
|
||||
|
||||
// For the people that compile with -funsigned-char.
|
||||
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
|
||||
const signed char* data,
|
||||
int length = -1);
|
||||
|
||||
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate,
|
||||
const unsigned char* data,
|
||||
int length = -1);
|
||||
|
||||
// Used to be a macro, hence the uppercase name.
|
||||
template <int N>
|
||||
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(
|
||||
v8::Isolate* isolate,
|
||||
const char(&data)[N]) {
|
||||
return OneByteString(isolate, data, N - 1);
|
||||
}
|
||||
|
||||
template <std::size_t N>
|
||||
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(
|
||||
v8::Isolate* isolate,
|
||||
const std::array<char, N>& 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 <typename T, size_t N>
|
||||
constexpr size_t arraysize(const T (&)[N]) {
|
||||
return N;
|
||||
}
|
||||
|
||||
template <typename T, size_t N>
|
||||
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 <typename T, size_t kStackStorageSize = 1024>
|
||||
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<T> ToString() const { return {out(), length()}; }
|
||||
inline std::basic_string_view<T> 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 <typename T, size_t kStackStorageSize = 64>
|
||||
class ArrayBufferViewContents {
|
||||
public:
|
||||
ArrayBufferViewContents() = default;
|
||||
|
||||
ArrayBufferViewContents(const ArrayBufferViewContents&) = delete;
|
||||
void operator=(const ArrayBufferViewContents&) = delete;
|
||||
|
||||
explicit inline ArrayBufferViewContents(v8::Local<v8::Value> value);
|
||||
explicit inline ArrayBufferViewContents(v8::Local<v8::Object> value);
|
||||
explicit inline ArrayBufferViewContents(v8::Local<v8::ArrayBufferView> abv);
|
||||
inline void Read(v8::Local<v8::ArrayBufferView> abv);
|
||||
inline void ReadValue(v8::Local<v8::Value> 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<char> {
|
||||
public:
|
||||
explicit Utf8Value(v8::Isolate* isolate, v8::Local<v8::Value> 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<uint16_t> {
|
||||
public:
|
||||
explicit TwoByteValue(v8::Isolate* isolate, v8::Local<v8::Value> value);
|
||||
};
|
||||
|
||||
class BufferValue : public MaybeStackBuffer<char> {
|
||||
public:
|
||||
explicit BufferValue(v8::Isolate* isolate, v8::Local<v8::Value> value);
|
||||
|
||||
inline std::string ToString() const { return std::string(out(), length()); }
|
||||
};
|
||||
|
||||
#define SPREAD_BUFFER_ARG(val, name) \
|
||||
CHECK((val)->IsArrayBufferView()); \
|
||||
v8::Local<v8::ArrayBufferView> name = (val).As<v8::ArrayBufferView>(); \
|
||||
const size_t name##_offset = name->ByteOffset(); \
|
||||
const size_t name##_length = name->ByteLength(); \
|
||||
char* const name##_data = \
|
||||
static_cast<char*>(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 <typename T> inline void USE(T&&) {}
|
||||
|
||||
template <typename Fn>
|
||||
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 <typename Fn>
|
||||
inline MUST_USE_RESULT OnScopeLeaveImpl<Fn> OnScopeLeave(Fn&& fn) {
|
||||
return OnScopeLeaveImpl<Fn>{std::move(fn)};
|
||||
}
|
||||
|
||||
// Simple RAII wrapper for contiguous data that uses malloc()/free().
|
||||
template <typename T>
|
||||
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<T>(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 <typename T>
|
||||
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 <typename T, typename = void>
|
||||
struct is_callable : std::is_function<T> { };
|
||||
|
||||
template <typename T>
|
||||
struct is_callable<T, typename std::enable_if<
|
||||
std::is_same<decltype(void(&T::operator())), void>::value
|
||||
>::type> : std::true_type { };
|
||||
|
||||
template <typename T, void (*function)(T*)>
|
||||
struct FunctionDeleter {
|
||||
void operator()(T* pointer) const { function(pointer); }
|
||||
typedef std::unique_ptr<T, FunctionDeleter> Pointer;
|
||||
};
|
||||
|
||||
template <typename T, void (*function)(T*)>
|
||||
using DeleteFnPtr = typename FunctionDeleter<T, function>::Pointer;
|
||||
|
||||
std::vector<std::string_view> SplitString(const std::string_view in,
|
||||
const std::string_view delim);
|
||||
|
||||
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
|
||||
std::string_view str,
|
||||
v8::Isolate* isolate = nullptr);
|
||||
template <typename T, typename test_for_number =
|
||||
typename std::enable_if<std::numeric_limits<T>::is_specialized, bool>::type>
|
||||
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
|
||||
const T& number,
|
||||
v8::Isolate* isolate = nullptr);
|
||||
template <typename T>
|
||||
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
|
||||
const std::vector<T>& vec,
|
||||
v8::Isolate* isolate = nullptr);
|
||||
template <typename T>
|
||||
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
|
||||
const std::set<T>& set,
|
||||
v8::Isolate* isolate = nullptr);
|
||||
template <typename T, typename U>
|
||||
inline v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
|
||||
const std::unordered_map<T, U>& map,
|
||||
v8::Isolate* isolate = nullptr);
|
||||
|
||||
// These macros expects a `Isolate* isolate` and a `Local<Context> 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::PropertyAttribute>(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<v8::String> constant_name = \
|
||||
v8::String::NewFromUtf8(isolate, name).ToLocalChecked(); \
|
||||
v8::Local<v8::String> constant_value = \
|
||||
v8::String::NewFromUtf8(isolate, constant).ToLocalChecked(); \
|
||||
v8::PropertyAttribute constant_attributes = \
|
||||
static_cast<v8::PropertyAttribute>(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 <typename T>
|
||||
constexpr T RoundUp(T a, T b) {
|
||||
return a % b != 0 ? a + b - (a % b) : a;
|
||||
}
|
||||
|
||||
// Align ptr to an `alignment`-bytes boundary.
|
||||
template <typename T, typename U>
|
||||
constexpr T* AlignUp(T* ptr, U alignment) {
|
||||
return reinterpret_cast<T*>(
|
||||
RoundUp(reinterpret_cast<uintptr_t>(ptr), alignment));
|
||||
}
|
||||
|
||||
class SlicedArguments : public MaybeStackBuffer<v8::Local<v8::Value>> {
|
||||
public:
|
||||
inline explicit SlicedArguments(
|
||||
const v8::FunctionCallbackInfo<v8::Value>& 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<T> is still in scope, it will destroy the
|
||||
// reference to the object.
|
||||
template <class TypeName>
|
||||
static inline v8::Local<TypeName> Default(
|
||||
v8::Isolate* isolate,
|
||||
const v8::PersistentBase<TypeName>& persistent) {
|
||||
if (persistent.IsWeak()) {
|
||||
return PersistentToLocal::Weak(isolate, persistent);
|
||||
} else {
|
||||
return PersistentToLocal::Strong(persistent);
|
||||
}
|
||||
}
|
||||
|
||||
// Unchecked conversion from a non-weak Persistent<T> to Local<T>,
|
||||
// use with care!
|
||||
//
|
||||
// Do not call persistent.Reset() while the returned Local<T> is still in
|
||||
// scope, it will destroy the reference to the object.
|
||||
template <class TypeName>
|
||||
static inline v8::Local<TypeName> Strong(
|
||||
const v8::PersistentBase<TypeName>& persistent) {
|
||||
DCHECK(!persistent.IsWeak());
|
||||
return *reinterpret_cast<v8::Local<TypeName>*>(
|
||||
const_cast<v8::PersistentBase<TypeName>*>(&persistent));
|
||||
}
|
||||
|
||||
template <class TypeName>
|
||||
static inline v8::Local<TypeName> Weak(
|
||||
v8::Isolate* isolate,
|
||||
const v8::PersistentBase<TypeName>& persistent) {
|
||||
return v8::Local<TypeName>::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 <typename T, typename U>
|
||||
std::unique_ptr<T> static_unique_pointer_cast(std::unique_ptr<U>&& ptr) {
|
||||
return std::unique_ptr<T>(static_cast<T*>(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<v8::FunctionTemplate> NewFunctionTemplate(
|
||||
v8::Isolate* isolate,
|
||||
v8::FunctionCallback callback,
|
||||
v8::Local<v8::Signature> signature = v8::Local<v8::Signature>(),
|
||||
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<v8::Context> context,
|
||||
v8::Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback);
|
||||
// Similar to SetProtoMethod but without receiver signature checks.
|
||||
void SetMethod(v8::Isolate* isolate,
|
||||
v8::Local<v8::Template> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback);
|
||||
|
||||
void SetFastMethod(v8::Local<v8::Context> context,
|
||||
v8::Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback slow_callback,
|
||||
const v8::CFunction* c_function);
|
||||
void SetFastMethodNoSideEffect(v8::Local<v8::Context> context,
|
||||
v8::Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback slow_callback,
|
||||
const v8::CFunction* c_function);
|
||||
|
||||
void SetProtoMethod(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback);
|
||||
|
||||
void SetInstanceMethod(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback);
|
||||
|
||||
// Safe variants denote the function has no side effects.
|
||||
void SetMethodNoSideEffect(v8::Local<v8::Context> context,
|
||||
v8::Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback);
|
||||
void SetProtoMethodNoSideEffect(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> that,
|
||||
const char* name,
|
||||
v8::FunctionCallback callback);
|
||||
|
||||
enum class SetConstructorFunctionFlag {
|
||||
NONE,
|
||||
SET_CLASS_NAME,
|
||||
};
|
||||
|
||||
void SetConstructorFunction(v8::Local<v8::Context> context,
|
||||
v8::Local<v8::Object> that,
|
||||
const char* name,
|
||||
v8::Local<v8::FunctionTemplate> tmpl,
|
||||
SetConstructorFunctionFlag flag =
|
||||
SetConstructorFunctionFlag::SET_CLASS_NAME);
|
||||
|
||||
void SetConstructorFunction(v8::Local<v8::Context> context,
|
||||
v8::Local<v8::Object> that,
|
||||
v8::Local<v8::String> name,
|
||||
v8::Local<v8::FunctionTemplate> tmpl,
|
||||
SetConstructorFunctionFlag flag =
|
||||
SetConstructorFunctionFlag::SET_CLASS_NAME);
|
||||
|
||||
} // namespace node
|
||||
|
||||
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#endif // SRC_UTIL_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
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "CommonHeader.h"
|
||||
#if !defined(_WIN)
|
||||
#if !defined(_WIN) && CC_PLATFORM == CC_PLATFORM_OPENHARMONY
|
||||
#include <hilog/log.h>
|
||||
|
||||
#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)
|
||||
#define _SE(name) &(name##RegistryStruct)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
"type": "github",
|
||||
"owner": "cocos-creator",
|
||||
"name": "engine-native-external",
|
||||
"checkout": "v3.8.6-5"
|
||||
"checkout": "v3.8.6-6"
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user