mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-21 08:02:39 +08:00
Update Spidermonkey (97.0.1) backend for se (jswrapper) (#10170)
* Update spidermonkey backend for se. * Update cmakelist * Bug fix for se spidermonkey backend. * Fix constructor binding for spidermonkey backend. * Fix wrong syntax of calling native function in simple-texture.jsb.ts & builtin-res-mgr.jsb.ts * Use jsb.createExternalArrayBuffer for caching since it will not be moved during GGC. * Cleanup se spidermonkey backend * Add Object::createExternalArrayBuffer for se v8 backend. * Remove unused code in jsb_assets_manual.cpp * Add jsb.createExternalArrayBuffer binding. * Remove unused WebGLRenderingContext registeration. * Remove unused code in jsb_global_init.cpp * Add Root::setDevice. * Invoke ScriptEngine::mainLoopUpdate in Engine.cpp. * Update CMakeLists.txt * Make missing return type as an error. * Cleanup for sm/ScriptEngine.cpp * prefine.cmake fix for vs.
This commit is contained in:
@@ -66,7 +66,7 @@ simpleTextureProto._ctor = function () {
|
||||
const oldGetGFXTexture = simpleTextureProto.getGFXTexture;
|
||||
simpleTextureProto.getGFXTexture = function () {
|
||||
if (!this._gfxTexture) {
|
||||
this._gfxTexture = oldGetGFXTexture();
|
||||
this._gfxTexture = oldGetGFXTexture.call(this);
|
||||
}
|
||||
return this._gfxTexture;
|
||||
};
|
||||
|
||||
@@ -81,7 +81,7 @@ builtinResMgrProto.initBuiltinRes = function (device: Device): Promise<void> {
|
||||
}
|
||||
|
||||
return Promise.resolve().then(() => {
|
||||
oldInitBuiltinRes.call(device);
|
||||
oldInitBuiltinRes.call(this, device);
|
||||
}).then(() => this._preloadAssets());
|
||||
};
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ export class NodeUIProperties {
|
||||
this._node = node;
|
||||
|
||||
if (JSB) {
|
||||
this._uiTransformDirty = new Uint32Array(1);
|
||||
this._uiTransformDirty = new Uint32Array((jsb as any).createExternalArrayBuffer(4));
|
||||
Object.defineProperty(this, 'uiTransformDirty',
|
||||
{
|
||||
get (): boolean {
|
||||
|
||||
@@ -89,13 +89,7 @@ export const TRANSFORM_ON = 1 << 0;
|
||||
const Destroying = CCObject.Flags.Destroying;
|
||||
|
||||
// For optimize getPosition, getRotation, getScale
|
||||
export const _tempFloatArray = new Float32Array([
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
0, 0, 0, 0
|
||||
]);
|
||||
export const _tempFloatArray = new Float32Array(jsb.createExternalArrayBuffer(20 * 4));
|
||||
//
|
||||
|
||||
Node._setTempFloatArray(_tempFloatArray.buffer);
|
||||
@@ -1302,8 +1296,9 @@ nodeProto._ctor = function (name?: string) {
|
||||
this._components = [];
|
||||
this._eventProcessor = new legacyCC.NodeEventProcessor(this);
|
||||
this._uiProps = new NodeUIProperties(this);
|
||||
this._activeInHierarchyArr = new Uint8Array([0]);
|
||||
this._layerArr = new Uint32Array([Layers.Enum.DEFAULT]);
|
||||
this._activeInHierarchyArr = new Uint8Array(jsb.createExternalArrayBuffer(1));
|
||||
this._layerArr = new Uint32Array(jsb.createExternalArrayBuffer(4));
|
||||
this._layerArr[0] = Layers.Enum.DEFAULT;
|
||||
this._scene = null;
|
||||
this._prefab = null;
|
||||
// record scene's id when set this node as persist node
|
||||
|
||||
+20
-2
@@ -11,6 +11,7 @@ set(ENGINE_NAME cocos_engine)
|
||||
################################# options ############################################
|
||||
# default fallback options
|
||||
cc_set_if_undefined(USE_SE_V8 ON)
|
||||
cc_set_if_undefined(USE_SE_SM OFF)
|
||||
cc_set_if_undefined(USE_V8_DEBUGGER ON)
|
||||
cc_set_if_undefined(USE_SOCKET ON)
|
||||
cc_set_if_undefined(USE_AUDIO ON)
|
||||
@@ -101,6 +102,7 @@ cc_inspect_values(
|
||||
CC_USE_VULKAN
|
||||
USE_SE_V8
|
||||
USE_V8_DEBUGGER
|
||||
USE_SE_SM
|
||||
USE_SOCKET
|
||||
USE_AUDIO
|
||||
USE_EDIT_BOX
|
||||
@@ -111,8 +113,6 @@ cc_inspect_values(
|
||||
USE_DRAGONBONES
|
||||
USE_SPINE
|
||||
USE_WEBSOCKET_SERVER
|
||||
USE_SE_V8
|
||||
USE_V8_DEBUGGER
|
||||
USE_PHYSICS_PHYSX
|
||||
USE_JOB_SYSTEM_TBB
|
||||
USE_JOB_SYSTEM_TASKFLOW
|
||||
@@ -2418,6 +2418,23 @@ if(USE_SE_JSC)
|
||||
)
|
||||
endif()
|
||||
|
||||
if(USE_SE_SM)
|
||||
cocos_source_files(MODULE ccbindings
|
||||
cocos/bindings/jswrapper/sm/Base.h
|
||||
NO_WERROR cocos/bindings/jswrapper/sm/Class.cpp
|
||||
cocos/bindings/jswrapper/sm/Class.h
|
||||
cocos/bindings/jswrapper/sm/HelperMacros.h
|
||||
NO_WERROR cocos/bindings/jswrapper/sm/HelperMacros.cpp
|
||||
NO_WERROR cocos/bindings/jswrapper/sm/Object.cpp
|
||||
cocos/bindings/jswrapper/sm/Object.h
|
||||
NO_WERROR cocos/bindings/jswrapper/sm/ScriptEngine.cpp
|
||||
cocos/bindings/jswrapper/sm/ScriptEngine.h
|
||||
cocos/bindings/jswrapper/sm/SeApi.h
|
||||
NO_WERROR cocos/bindings/jswrapper/sm/Utils.cpp
|
||||
cocos/bindings/jswrapper/sm/Utils.h
|
||||
)
|
||||
endif()
|
||||
|
||||
cocos_source_files(MODULE ccbindings
|
||||
cocos/bindings/jswrapper/config.cpp
|
||||
cocos/bindings/jswrapper/config.h
|
||||
@@ -2793,6 +2810,7 @@ function(cc_apply_definations target)
|
||||
$<IF:$<BOOL:${USE_PHYSICS_PHYSX}>,USE_PHYSICS_PHYSX=1,USE_PHYSICS_PHYSX=0>
|
||||
$<IF:$<BOOL:${CC_EDITOR}>,CC_EDITOR=1,CC_EDITOR=0>
|
||||
$<$<BOOL:${USE_SE_JSC}>:SCRIPT_ENGINE_TYPE=3>
|
||||
$<$<BOOL:${USE_SE_SM}>:SCRIPT_ENGINE_TYPE=1>
|
||||
$<$<CONFIG:Debug>:CC_DEBUG=1>
|
||||
)
|
||||
endfunction()
|
||||
|
||||
@@ -100,13 +100,17 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
if("$ENV{COCOS_ENGINE_DEV}" EQUAL "1")
|
||||
set(WERROR_FLAGS "-Werror") # -Wshorten-64-to-32 -Werror=return-type
|
||||
set(WERROR_FLAGS "-Werror -Werror=return-type") # -Wshorten-64-to-32 -Werror=return-type
|
||||
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
|
||||
set(WERROR_FLAGS "/WX")
|
||||
endif()
|
||||
message(STATUS "Enable NO_WERROR")
|
||||
else()
|
||||
set(WERROR_FLAGS "")
|
||||
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
|
||||
set(WERROR_FLAGS "")
|
||||
else()
|
||||
set(WERROR_FLAGS "-Werror=return-type")
|
||||
endif()
|
||||
message(STATUS "Ignore NO_WERROR")
|
||||
endif()
|
||||
|
||||
|
||||
@@ -27,10 +27,10 @@
|
||||
#pragma once
|
||||
|
||||
#define SCRIPT_ENGINE_NONE 0
|
||||
//#define SCRIPT_ENGINE_SM 1
|
||||
#define SCRIPT_ENGINE_SM 1
|
||||
#define SCRIPT_ENGINE_V8 2
|
||||
#define SCRIPT_ENGINE_JSC 3
|
||||
//#define SCRIPT_ENGINE_CHAKRACORE 4
|
||||
#define SCRIPT_ENGINE_CHAKRACORE 4
|
||||
|
||||
#ifndef SCRIPT_ENGINE_TYPE
|
||||
#define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_V8
|
||||
|
||||
@@ -30,16 +30,35 @@
|
||||
#define UINT64_C(value) __CONCAT(value, ULL)
|
||||
#endif
|
||||
|
||||
#include "js/Conversions.h"
|
||||
#include "js/Initialization.h"
|
||||
#include "jsapi.h"
|
||||
#include "jsfriendapi.h"
|
||||
|
||||
#include "js/Initialization.h"
|
||||
#include "js/Conversions.h"
|
||||
#include "js/ArrayBuffer.h"
|
||||
#include "js/JSON.h"
|
||||
#include "js/Equality.h"
|
||||
#include "js/Warnings.h"
|
||||
#include "js/LocaleSensitive.h"
|
||||
#include "js/ContextOptions.h"
|
||||
#include "js/CompilationAndEvaluation.h"
|
||||
#include "js/SourceText.h"
|
||||
#include "js/GCAPI.h"
|
||||
#include "js/BuildId.h"
|
||||
#include "js/MemoryMetrics.h"
|
||||
#include "js/Array.h"
|
||||
#include "js/experimental/TypedData.h"
|
||||
#include "js/BigInt.h"
|
||||
|
||||
#include "mozilla/Unused.h"
|
||||
|
||||
#include "../PrivateObject.h"
|
||||
#include "HelperMacros.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "HelperMacros.h"
|
||||
#include <initializer_list>
|
||||
|
||||
@@ -45,6 +45,7 @@ bool empty_constructor(JSContext *cx, uint32_t argc, JS::Value *vp) {
|
||||
}
|
||||
|
||||
std::vector<Class *> __allClasses;
|
||||
|
||||
} // namespace
|
||||
|
||||
Class::Class()
|
||||
@@ -71,6 +72,18 @@ Class *Class::create(const char *className, Object *obj, Object *parentProto, JS
|
||||
return cls;
|
||||
}
|
||||
|
||||
Class *Class::create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, JSNative ctor) {
|
||||
se::AutoHandleScope scope;
|
||||
se::Object * currentParent = parent;
|
||||
se::Value tmp;
|
||||
for (auto i = 0; i < classPath.size() - 1; i++) {
|
||||
bool ok = currentParent->getProperty(*(classPath.begin() + i), &tmp);
|
||||
CCASSERT(ok, "class or namespace in path is not defined");
|
||||
currentParent = tmp.toObject();
|
||||
}
|
||||
return create(*(classPath.end() - 1), currentParent, parentProto, ctor);
|
||||
}
|
||||
|
||||
bool Class::init(const char *clsName, Object *parent, Object *parentProto, JSNative ctor) {
|
||||
_name = clsName;
|
||||
|
||||
@@ -97,31 +110,41 @@ void Class::destroy() {
|
||||
SAFE_DEC_REF(_parentProto);
|
||||
}
|
||||
|
||||
/* static */
|
||||
void Class::onTraceCallback(JSTracer* trc, JSObject* obj) {
|
||||
auto* seObj = reinterpret_cast<Object*>(internal::SE_JS_GetPrivate(obj, 1));
|
||||
if (seObj != nullptr) {
|
||||
JS::TraceEdge(trc, &seObj->_heap, "seObj");
|
||||
}
|
||||
}
|
||||
|
||||
bool Class::install() {
|
||||
// assert(__clsMap.find(_name) == __clsMap.end());
|
||||
//
|
||||
// __clsMap.emplace(_name, this);
|
||||
|
||||
_jsCls.name = _name;
|
||||
_jsCls.flags = JSCLASS_USERBIT1 | JSCLASS_HAS_RESERVED_SLOTS(2) | JSCLASS_FOREGROUND_FINALIZE; //IDEA: Use JSCLASS_BACKGROUND_FINALIZE to improve GC performance
|
||||
if (_finalizeOp != nullptr) {
|
||||
_jsCls.flags = JSCLASS_HAS_PRIVATE | JSCLASS_FOREGROUND_FINALIZE; //IDEA: Use JSCLASS_BACKGROUND_FINALIZE to improve GC performance
|
||||
_classOps.finalize = _finalizeOp;
|
||||
} else {
|
||||
_jsCls.flags = JSCLASS_HAS_PRIVATE;
|
||||
_classOps.finalize = [](JSFreeOp *fop, JSObject *obj) {};
|
||||
}
|
||||
|
||||
_classOps.trace = Class::onTraceCallback;
|
||||
|
||||
_jsCls.cOps = &_classOps;
|
||||
|
||||
JSObject * parentObj = _parentProto != nullptr ? _parentProto->_getJSObject() : nullptr;
|
||||
JS::RootedObject parent(__cx, _parent->_getJSObject());
|
||||
JS::RootedObject parentProto(__cx, parentObj);
|
||||
JS::RootedObject parent(__cx, _parent->_getJSObject());
|
||||
|
||||
_funcs.push_back(JS_FS_END);
|
||||
_properties.push_back(JS_PS_END);
|
||||
_staticFuncs.push_back(JS_FS_END);
|
||||
_staticProperties.push_back(JS_PS_END);
|
||||
|
||||
JSObject *jsobj = JS_InitClass(__cx, parent, parentProto, &_jsCls, _ctor, 0, _properties.data(), _funcs.data(), _staticProperties.data(), _staticFuncs.data());
|
||||
JS::RootedObject jsobj(__cx, JS_InitClass(__cx, parent, parentProto, &_jsCls, _ctor, 0, _properties.data(), _funcs.data(), _staticProperties.data(), _staticFuncs.data()));
|
||||
if (jsobj != nullptr) {
|
||||
_proto = Object::_createJSObject(nullptr, jsobj);
|
||||
// SE_LOGD("_proto: %p, name: %s\n", _proto, _name);
|
||||
@@ -133,25 +156,33 @@ bool Class::install() {
|
||||
}
|
||||
|
||||
bool Class::defineFunction(const char *name, JSNative func) {
|
||||
JSFunctionSpec cb = JS_FN(name, func, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE);
|
||||
JSFunctionSpec cb = JS_FN(name, func, 0, JSPROP_ENUMERATE);
|
||||
_funcs.push_back(cb);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Class::defineProperty(const char *name, JSNative getter, JSNative setter) {
|
||||
JSPropertySpec property = JS_PSGS(name, getter, setter, JSPROP_ENUMERATE | JSPROP_PERMANENT);
|
||||
JSPropertySpec property = JS_PSGS(name, getter, setter, JSPROP_ENUMERATE);
|
||||
_properties.push_back(property);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Class::defineProperty(const std::initializer_list<const char *> &names, JSNative getter, JSNative setter) {
|
||||
bool ret = true;
|
||||
for (const auto *name : names) {
|
||||
ret &= defineProperty(name, getter, setter);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool Class::defineStaticFunction(const char *name, JSNative func) {
|
||||
JSFunctionSpec cb = JS_FN(name, func, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE);
|
||||
JSFunctionSpec cb = JS_FN(name, func, 0, JSPROP_ENUMERATE);
|
||||
_staticFuncs.push_back(cb);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Class::defineStaticProperty(const char *name, JSNative getter, JSNative setter) {
|
||||
JSPropertySpec property = JS_PSGS(name, getter, setter, JSPROP_ENUMERATE | JSPROP_PERMANENT);
|
||||
JSPropertySpec property = JS_PSGS(name, getter, setter, JSPROP_ENUMERATE);
|
||||
_staticProperties.push_back(property);
|
||||
return true;
|
||||
}
|
||||
@@ -176,11 +207,10 @@ bool Class::defineFinalizeFunction(JSFinalizeOp func) {
|
||||
// return obj;
|
||||
// }
|
||||
|
||||
JSObject *Class::_createJSObjectWithClass(Class *cls) {
|
||||
JSObject * proto = cls->_proto != nullptr ? cls->_proto->_getJSObject() : nullptr;
|
||||
void Class::_createJSObjectWithClass(Class *cls, JS::MutableHandleObject outObj) {
|
||||
JSObject *proto = cls->_proto != nullptr ? cls->_proto->_getJSObject() : nullptr;
|
||||
JS::RootedObject jsProto(__cx, proto);
|
||||
JS::RootedObject obj(__cx, JS_NewObjectWithGivenProto(__cx, &cls->_jsCls, jsProto));
|
||||
return obj;
|
||||
outObj.set(JS_NewObjectWithGivenProto(__cx, &cls->_jsCls, jsProto));
|
||||
}
|
||||
|
||||
void Class::setContext(JSContext *cx) {
|
||||
|
||||
@@ -51,6 +51,7 @@ public:
|
||||
* @note Don't need to delete the pointer return by this method, it's managed internally.
|
||||
*/
|
||||
static Class *create(const char *className, Object *obj, Object *parentProto, JSNative ctor);
|
||||
static Class *create(const std::initializer_list<const char *> &classPath, se::Object *parent, Object *parentProto, JSNative ctor);
|
||||
|
||||
/**
|
||||
* @brief Defines a member function with a callback. Each objects created by class will have this function property.
|
||||
@@ -68,6 +69,7 @@ public:
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineProperty(const char *name, JSNative getter, JSNative setter);
|
||||
bool defineProperty(const std::initializer_list<const char *> &names, JSNative getter, JSNative setter);
|
||||
|
||||
/**
|
||||
* @brief Defines a static function with a callback. Only JavaScript constructor object will have this function.
|
||||
@@ -124,11 +126,13 @@ private:
|
||||
void destroy();
|
||||
|
||||
// static JSObject* _createJSObject(const std::string &clsName, Class** outCls);
|
||||
static JSObject *_createJSObjectWithClass(Class *cls);
|
||||
static void _createJSObjectWithClass(Class *cls, JS::MutableHandleObject outObj);
|
||||
|
||||
static void setContext(JSContext *cx);
|
||||
static void cleanup();
|
||||
|
||||
static void onTraceCallback(JSTracer* trc, JSObject* obj);
|
||||
|
||||
const char *_name;
|
||||
Object * _parent;
|
||||
Object * _proto;
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
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 "HelperMacros.h"
|
||||
|
||||
#if defined(RECORD_JSB_INVOKING)
|
||||
|
||||
namespace {
|
||||
bool cmp(const std::pair<const char *, std::tuple<int, uint64_t>> &a, const std::pair<const char *, std::tuple<int, uint64_t>> &b) {
|
||||
return std::get<1>(a.second) > std::get<1>(b.second);
|
||||
}
|
||||
unsigned int __jsbInvocationCount; // NOLINT(readability-identifier-naming)
|
||||
std::map<char const *, std::tuple<int, uint64_t>> __jsbFunctionInvokedRecords; // NOLINT(readability-identifier-naming)
|
||||
} // namespace
|
||||
|
||||
JsbInvokeScopeT::JsbInvokeScopeT(const char *functionName) : _functionName(functionName) {
|
||||
_start = std::chrono::high_resolution_clock::now();
|
||||
__jsbInvocationCount++;
|
||||
}
|
||||
JsbInvokeScopeT::~JsbInvokeScopeT() {
|
||||
auto &ref = __jsbFunctionInvokedRecords[_functionName];
|
||||
std::get<0>(ref) += 1;
|
||||
std::get<1>(ref) += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - _start).count();
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
void printJSBInvokeAtFrame(int n) {
|
||||
#if defined(RECORD_JSB_INVOKING)
|
||||
static int cnt = 0;
|
||||
cnt += 1;
|
||||
if (cnt % n == 0) {
|
||||
printJSBInvoke();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void clearRecordJSBInvoke() {
|
||||
#if defined(RECORD_JSB_INVOKING)
|
||||
__jsbInvocationCount = 0;
|
||||
__jsbFunctionInvokedRecords.clear();
|
||||
#endif
|
||||
}
|
||||
|
||||
void printJSBInvoke() {
|
||||
#if defined(RECORD_JSB_INVOKING)
|
||||
static std::vector<std::pair<const char *, std::tuple<int, uint64_t>>> pairs;
|
||||
for (const auto &it : __jsbFunctionInvokedRecords) {
|
||||
pairs.emplace_back(it); //NOLINT
|
||||
}
|
||||
|
||||
std::sort(pairs.begin(), pairs.end(), cmp);
|
||||
cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::LEVEL_DEBUG, "Start print JSB function record info....... %d times", __jsbInvocationCount);
|
||||
for (const auto &pair : pairs) {
|
||||
cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::LEVEL_DEBUG, "\t%s takes %.3lf ms, invoked %u times,", pair.first, std::get<1>(pair.second) / 1000000.0, std::get<0>(pair.second));
|
||||
}
|
||||
pairs.clear();
|
||||
cc::Log::logMessage(cc::LogType::KERNEL, cc::LogLevel::LEVEL_DEBUG, "End print JSB function record info.......\n");
|
||||
#endif
|
||||
}
|
||||
@@ -27,10 +27,59 @@
|
||||
#pragma once
|
||||
|
||||
#include "../config.h"
|
||||
#include "../ValueArrayPool.h"
|
||||
|
||||
//#define RECORD_JSB_INVOKING
|
||||
|
||||
#ifndef CC_DEBUG
|
||||
#undef RECORD_JSB_INVOKING
|
||||
#endif
|
||||
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
|
||||
|
||||
extern uint32_t __jsbInvocationCount;
|
||||
#if defined(RECORD_JSB_INVOKING)
|
||||
|
||||
class JsbInvokeScopeT {
|
||||
public:
|
||||
JsbInvokeScopeT(const char *functionName);
|
||||
~JsbInvokeScopeT();
|
||||
|
||||
private:
|
||||
const char * _functionName;
|
||||
std::chrono::time_point<std::chrono::high_resolution_clock> _start;
|
||||
};
|
||||
#define JsbInvokeScope(arg) JsbInvokeScopeT invokeScope(arg); // NOLINT(readability-identifier-naming)
|
||||
|
||||
#else
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
#define JsbInvokeScope(arg) \
|
||||
do { \
|
||||
} while (0)
|
||||
|
||||
#endif
|
||||
|
||||
template <typename T, typename STATE>
|
||||
constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier-naming)
|
||||
return reinterpret_cast<T *>(s.nativeThisObject());
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
constexpr typename std::enable_if<std::is_enum<T>::value, char *>::type SE_UNDERLYING_TYPE_NAME() { // NOLINT(readability-identifier-naming)
|
||||
return typeid(std::underlying_type_t<T>).name();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
constexpr typename std::enable_if<!std::is_enum<T>::value, char *>::type SE_UNDERLYING_TYPE_NAME() { // NOLINT(readability-identifier-naming)
|
||||
return typeid(T).name();
|
||||
}
|
||||
|
||||
void clearRecordJSBInvoke();
|
||||
|
||||
void printJSBInvoke();
|
||||
|
||||
void printJSBInvokeAtFrame(int n);
|
||||
|
||||
|
||||
#define SAFE_INC_REF(obj) \
|
||||
if (obj != nullptr) obj->incRef()
|
||||
@@ -47,15 +96,17 @@ extern uint32_t __jsbInvocationCount;
|
||||
|
||||
#define SE_BIND_FUNC(funcName) \
|
||||
bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \
|
||||
++__jsbInvocationCount; \
|
||||
JsbInvokeScope(#funcName); \
|
||||
bool ret = false; \
|
||||
JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \
|
||||
JS::Value _thiz = _argv.computeThis(_cx); \
|
||||
se::ValueArray args; \
|
||||
se::internal::jsToSeArgs(_cx, argc, _argv, &args); \
|
||||
JS::RootedObject _thizObj(_cx, _thiz.toObjectOrNull()); \
|
||||
void * nativeThisObject = se::internal::getPrivate(_cx, _thizObj); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
JS::RootedObject _thizObj(_cx); \
|
||||
_argv.computeThis(_cx, &_thizObj); \
|
||||
se::ValueArray & args = se::gValueArrayPool.get(argc); \
|
||||
se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \
|
||||
se::internal::jsToSeArgs(_cx, argc, _argv, args); \
|
||||
se::PrivateObjectBase *privateObject = static_cast<se::PrivateObjectBase *>(se::internal::getPrivate(_cx, _thizObj, 0)); \
|
||||
se::Object * thisObject = reinterpret_cast<se::Object *>(se::internal::getPrivate(_cx, _thizObj, 1)); \
|
||||
se::State state(thisObject, privateObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
@@ -64,30 +115,55 @@ extern uint32_t __jsbInvocationCount;
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define SE_BIND_FUNC_FAST(funcName) \
|
||||
bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \
|
||||
JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \
|
||||
JS::RootedObject _thizObj(_cx); \
|
||||
_argv.computeThis(_cx, &_thizObj); \
|
||||
auto *privateObject = static_cast<se::PrivateObjectBase *>(se::internal::SE_JS_GetPrivate(_thizObj, 0)); \
|
||||
funcName(privateObject->getRaw()); \
|
||||
_argv.rval().setUndefined(); \
|
||||
return true; \
|
||||
}
|
||||
|
||||
#define SE_DECLARE_FINALIZE_FUNC(funcName) \
|
||||
void funcName##Registry(JSFreeOp *_fop, JSObject *_obj);
|
||||
|
||||
#define SE_BIND_FINALIZE_FUNC(funcName) \
|
||||
void funcName##Registry(JSFreeOp *_fop, JSObject *_obj) { \
|
||||
void *nativeThisObject = JS_GetPrivate(_obj); \
|
||||
SE_LOGD("cjh finalize: %s, %p\n", #funcName, _obj); \
|
||||
JsbInvokeScope(#funcName); \
|
||||
se::PrivateObjectBase* privateObject = static_cast<se::PrivateObjectBase*>(se::internal::SE_JS_GetPrivate(_obj, 0)); \
|
||||
se::Object* seObj = static_cast<se::Object*>(se::internal::SE_JS_GetPrivate(_obj, 1)); \
|
||||
bool ret = false; \
|
||||
if (nativeThisObject == nullptr) \
|
||||
if (privateObject == nullptr) \
|
||||
return; \
|
||||
se::State state(nativeThisObject); \
|
||||
se::State state(privateObject); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
if (seObj->isClearMappingInFinalizer() && privateObject!= nullptr) { \
|
||||
void *nativeObj = privateObject->getRaw(); \
|
||||
auto iter = se::NativePtrToObjectMap::find(nativeObj); \
|
||||
if (iter != se::NativePtrToObjectMap::end()) { \
|
||||
se::NativePtrToObjectMap::erase(iter); \
|
||||
} \
|
||||
} \
|
||||
seObj->decRef(); \
|
||||
}
|
||||
|
||||
|
||||
#define SE_BIND_CTOR(funcName, cls, finalizeCb) \
|
||||
bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \
|
||||
++__jsbInvocationCount; \
|
||||
JsbInvokeScope(#funcName); \
|
||||
bool ret = false; \
|
||||
JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \
|
||||
se::ValueArray args; \
|
||||
se::internal::jsToSeArgs(_cx, argc, _argv, &args); \
|
||||
se::Object *thisObject = se::Object::createObjectWithClass(cls); \
|
||||
se::ValueArray & args = se::gValueArrayPool.get(argc); \
|
||||
se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \
|
||||
se::internal::jsToSeArgs(_cx, argc, _argv, args); \
|
||||
se::Object *thisObject = se::Object::_createJSObjectForConstructor(cls, _argv); \
|
||||
thisObject->_setFinalizeCallback(finalizeCb##Registry); \
|
||||
_argv.rval().setObject(*thisObject->_getJSObject()); \
|
||||
se::State state(thisObject, args); \
|
||||
ret = funcName(state); \
|
||||
@@ -104,13 +180,15 @@ extern uint32_t __jsbInvocationCount;
|
||||
|
||||
#define SE_BIND_SUB_CLS_CTOR(funcName, cls, finalizeCb) \
|
||||
bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \
|
||||
++__jsbInvocationCount; \
|
||||
JsbInvokeScope(#funcName); \
|
||||
bool ret = false; \
|
||||
JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \
|
||||
JS::Value _thiz = _argv.computeThis(_cx); \
|
||||
se::ValueArray args; \
|
||||
se::internal::jsToSeArgs(_cx, argc, _argv, &args); \
|
||||
se::Object *thisObject = se::Object::_createJSObject(cls, _thiz.toObjectOrNull()); \
|
||||
JS::RootedObject _thizObj(_cx); \
|
||||
_argv.computeThis(_cx, &_thizObj); \
|
||||
se::ValueArray & args = se::gValueArrayPool.get(argc); \
|
||||
se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \
|
||||
se::internal::jsToSeArgs(_cx, argc, _argv, args); \
|
||||
se::Object *thisObject = se::Object::_createJSObject(cls, _thizObj); \
|
||||
thisObject->_setFinalizeCallback(finalizeCb##Registry); \
|
||||
se::State state(thisObject, args); \
|
||||
ret = funcName(state); \
|
||||
@@ -125,15 +203,16 @@ extern uint32_t __jsbInvocationCount;
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define SE_BIND_PROP_GET(funcName) \
|
||||
bool funcName##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \
|
||||
++__jsbInvocationCount; \
|
||||
#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \
|
||||
bool funcName##postFix##Registry(JSContext *_cx, unsigned argc, JS::Value *_vp) { \
|
||||
JsbInvokeScope(#funcName); \
|
||||
bool ret = false; \
|
||||
JS::CallArgs _argv = JS::CallArgsFromVp(argc, _vp); \
|
||||
JS::Value _thiz = _argv.computeThis(_cx); \
|
||||
JS::RootedObject _thizObj(_cx, _thiz.toObjectOrNull()); \
|
||||
void * nativeThisObject = se::internal::getPrivate(_cx, _thizObj); \
|
||||
se::State state(nativeThisObject); \
|
||||
JS::RootedObject _thizObj(_cx); \
|
||||
_argv.computeThis(_cx, &_thizObj); \
|
||||
se::PrivateObjectBase * privateObject = static_cast<se::PrivateObjectBase *>(se::internal::getPrivate(_cx, _thizObj, 0)); \
|
||||
se::Object *thisObject = reinterpret_cast<se::Object *>(se::internal::getPrivate(_cx, _thizObj, 1)); \
|
||||
se::State state(thisObject, privateObject); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
@@ -142,19 +221,23 @@ extern uint32_t __jsbInvocationCount;
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define SE_BIND_PROP_SET(funcName) \
|
||||
bool funcName##Registry(JSContext *_cx, unsigned _argc, JS::Value *_vp) { \
|
||||
++__jsbInvocationCount; \
|
||||
#define SE_BIND_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, )
|
||||
#define SE_BIND_FUNC_AS_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, _asGetter)
|
||||
|
||||
#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \
|
||||
bool funcName##postFix##Registry(JSContext *_cx, unsigned _argc, JS::Value *_vp) { \
|
||||
JsbInvokeScope(#funcName); \
|
||||
bool ret = false; \
|
||||
JS::CallArgs _argv = JS::CallArgsFromVp(_argc, _vp); \
|
||||
JS::Value _thiz = _argv.computeThis(_cx); \
|
||||
JS::RootedObject _thizObj(_cx, _thiz.toObjectOrNull()); \
|
||||
void * nativeThisObject = se::internal::getPrivate(_cx, _thizObj); \
|
||||
se::Value data; \
|
||||
JS::RootedObject _thizObj(_cx); \
|
||||
_argv.computeThis(_cx, &_thizObj); \
|
||||
se::PrivateObjectBase * privateObject = static_cast<se::PrivateObjectBase *>(se::internal::getPrivate(_cx, _thizObj, 0)); \
|
||||
se::Object *thisObject = reinterpret_cast<se::Object *>(se::internal::getPrivate(_cx, _thizObj, 1)); \
|
||||
se::ValueArray & args = se::gValueArrayPool.get(1); \
|
||||
se::CallbackDepthGuard depthGuard{args, se::gValueArrayPool._depth}; \
|
||||
se::Value& data{args[0]}; \
|
||||
se::internal::jsToSeValue(_cx, _argv[0], &data); \
|
||||
se::ValueArray args; \
|
||||
args.push_back(std::move(data)); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
se::State state(thisObject, privateObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
@@ -162,6 +245,9 @@ extern uint32_t __jsbInvocationCount;
|
||||
return ret; \
|
||||
}
|
||||
|
||||
#define SE_BIND_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, )
|
||||
#define SE_BIND_FUNC_AS_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, _asSetter)
|
||||
|
||||
#define SE_TYPE_NAME(t) typeid(t).name()
|
||||
|
||||
#define SE_QUOTEME_(x) #x
|
||||
|
||||
@@ -39,30 +39,21 @@ std::unordered_map<Object *, void *> __objectMap; // Currently, the value `void*
|
||||
|
||||
namespace {
|
||||
JSContext *__cx = nullptr;
|
||||
|
||||
void get_or_create_js_obj(JSContext *cx, JS::HandleObject obj, const std::string &name, JS::MutableHandleObject jsObj) {
|
||||
JS::RootedValue nsval(cx);
|
||||
JS_GetProperty(cx, obj, name.c_str(), &nsval);
|
||||
if (nsval.isNullOrUndefined()) {
|
||||
jsObj.set(JS_NewPlainObject(cx));
|
||||
nsval = JS::ObjectValue(*jsObj);
|
||||
JS_SetProperty(cx, obj, name.c_str(), nsval);
|
||||
} else {
|
||||
jsObj.set(nsval.toObjectOrNull());
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Object::Object()
|
||||
: _root(nullptr),
|
||||
_privateData(nullptr),
|
||||
: _privateObject(nullptr),
|
||||
_cls(nullptr),
|
||||
_finalizeCb(nullptr),
|
||||
_rootCount(0) {
|
||||
_currentVMId = ScriptEngine::getInstance()->getVMId();
|
||||
_currentVMId = ScriptEngine::getInstance()->getVMId();
|
||||
}
|
||||
|
||||
Object::~Object() {
|
||||
if (_cls == nullptr) {
|
||||
unroot();
|
||||
}
|
||||
|
||||
if (_rootCount > 0) {
|
||||
unprotect();
|
||||
}
|
||||
@@ -80,6 +71,10 @@ bool Object::init(Class *cls, JSObject *obj) {
|
||||
assert(__objectMap.find(this) == __objectMap.end());
|
||||
__objectMap.emplace(this, nullptr);
|
||||
|
||||
if (_cls == nullptr) {
|
||||
root();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -93,13 +88,24 @@ Object *Object::_createJSObject(Class *cls, JSObject *obj) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
Object *Object::_createJSObjectForConstructor(Class *cls, const JS::CallArgs& args) {
|
||||
Object *ret = new Object();
|
||||
JS::RootedObject obj(__cx, JS_NewObjectForConstructor(__cx, &cls->_jsCls, args));
|
||||
if (!ret->init(cls, obj)) {
|
||||
delete ret;
|
||||
ret = nullptr;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
Object *Object::createPlainObject() {
|
||||
Object *obj = Object::_createJSObject(nullptr, JS_NewPlainObject(__cx));
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object *Object::createObjectWithClass(Class *cls) {
|
||||
JSObject *jsobj = Class::_createJSObjectWithClass(cls);
|
||||
JS::RootedObject jsobj(__cx);
|
||||
Class::_createJSObjectWithClass(cls, &jsobj);
|
||||
Object * obj = Object::_createJSObject(cls, jsobj);
|
||||
return obj;
|
||||
}
|
||||
@@ -115,22 +121,72 @@ Object *Object::getObjectWithPtr(void *ptr) {
|
||||
}
|
||||
|
||||
Object *Object::createArrayObject(size_t length) {
|
||||
JS::RootedObject jsobj(__cx, JS_NewArrayObject(__cx, length));
|
||||
JS::RootedObject jsobj(__cx, JS::NewArrayObject(__cx, length));
|
||||
Object * obj = Object::_createJSObject(nullptr, jsobj);
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object *Object::createArrayBufferObject(void *data, size_t byteLength) {
|
||||
JS::RootedObject jsobj(__cx, JS_NewArrayBuffer(__cx, (uint32_t)byteLength));
|
||||
bool isShared = false;
|
||||
JS::AutoCheckCannotGC nogc;
|
||||
uint8_t * tmpData = JS_GetArrayBufferData(jsobj, &isShared, nogc);
|
||||
if (data) {
|
||||
memcpy((void *)tmpData, (const void *)data, byteLength);
|
||||
} else {
|
||||
memset((void *)tmpData, 0, byteLength);
|
||||
Object *Object::createArrayBufferObject(const void *data, size_t byteLength) {
|
||||
Object* obj = nullptr;
|
||||
|
||||
if (byteLength > 0 && data != nullptr)
|
||||
{
|
||||
mozilla::UniquePtr<uint8_t[], JS::FreePolicy> jsBuf(
|
||||
js_pod_arena_malloc<uint8_t>(js::ArrayBufferContentsArena, byteLength)
|
||||
);
|
||||
if (!jsBuf)
|
||||
return nullptr;
|
||||
|
||||
memcpy(jsBuf.get(), data, byteLength);
|
||||
JS::RootedObject jsobj(__cx, JS::NewArrayBufferWithContents(__cx, byteLength, jsBuf.get()));
|
||||
if (jsobj)
|
||||
{
|
||||
// If JS::NewArrayBufferWithContents returns non-null, the ownership of
|
||||
// the data is transfered to obj, so we release the ownership here.
|
||||
mozilla::Unused << jsBuf.release();
|
||||
|
||||
obj = Object::_createJSObject(nullptr, jsobj);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
JS::RootedObject jsobj(__cx, JS::NewArrayBuffer(__cx, byteLength));
|
||||
if (jsobj)
|
||||
{
|
||||
obj = Object::_createJSObject(nullptr, jsobj);
|
||||
}
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
/* static */
|
||||
Object *Object::createExternalArrayBufferObject(void* contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void* freeUserData/* = nullptr*/) {
|
||||
struct BackingStoreUserData {
|
||||
BufferContentsFreeFunc freeFunc;
|
||||
void* freeUserData;
|
||||
size_t byteLength;
|
||||
};
|
||||
|
||||
auto* userData = new BackingStoreUserData();
|
||||
userData->freeFunc = freeFunc;
|
||||
userData->freeUserData = freeUserData;
|
||||
userData->byteLength = byteLength;
|
||||
|
||||
Object* obj = nullptr;
|
||||
JS::RootedObject jsobj(__cx, JS::NewExternalArrayBuffer(
|
||||
__cx, byteLength, contents,
|
||||
[](void* data, void* deleterData) {
|
||||
auto* userData = reinterpret_cast<BackingStoreUserData*>(deleterData);
|
||||
userData->freeFunc(data, userData->byteLength, userData->freeUserData);
|
||||
delete userData;
|
||||
},
|
||||
userData)
|
||||
);
|
||||
if (jsobj)
|
||||
{
|
||||
obj = Object::_createJSObject(nullptr, jsobj);
|
||||
}
|
||||
Object *obj = Object::_createJSObject(nullptr, jsobj);
|
||||
return obj;
|
||||
}
|
||||
|
||||
@@ -145,58 +201,112 @@ Object *Object::createTypedArray(TypedArrayType type, const void *data, size_t b
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
JSObject * arr = nullptr;
|
||||
void * tmpData = nullptr;
|
||||
bool isShared = false;
|
||||
JS::AutoCheckCannotGC nogc;
|
||||
|
||||
#define CREATE_TYPEDARRAY(_type_, _data, _byteLength, count) { \
|
||||
void* tmpData = nullptr; \
|
||||
JS::RootedObject arr(__cx, JS_New##_type_##Array(__cx, (uint32_t)(count))); \
|
||||
bool isShared = false; \
|
||||
if (_data != nullptr) { \
|
||||
JS::AutoCheckCannotGC nogc; \
|
||||
tmpData = JS_Get##_type_##ArrayData(arr, &isShared, nogc); \
|
||||
memcpy(tmpData, (const void*)_data, (_byteLength)); \
|
||||
} \
|
||||
Object* obj = Object::_createJSObject(nullptr, arr); \
|
||||
return obj; }
|
||||
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
CREATE_TYPEDARRAY(Int8, data, byteLength, byteLength);
|
||||
case TypedArrayType::INT16:
|
||||
CREATE_TYPEDARRAY(Int16, data, byteLength, byteLength/2);
|
||||
case TypedArrayType::INT32:
|
||||
CREATE_TYPEDARRAY(Int32, data, byteLength, byteLength/4);
|
||||
case TypedArrayType::UINT8:
|
||||
CREATE_TYPEDARRAY(Uint8, data, byteLength, byteLength);
|
||||
case TypedArrayType::UINT16:
|
||||
CREATE_TYPEDARRAY(Uint16, data, byteLength, byteLength/2);
|
||||
case TypedArrayType::UINT32:
|
||||
CREATE_TYPEDARRAY(Uint32, data, byteLength, byteLength/4);
|
||||
case TypedArrayType::FLOAT32:
|
||||
CREATE_TYPEDARRAY(Float32, data, byteLength, byteLength/4);
|
||||
case TypedArrayType::FLOAT64:
|
||||
CREATE_TYPEDARRAY(Float64, data, byteLength, byteLength/8);
|
||||
default:
|
||||
assert(false); // Should never go here.
|
||||
break;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
#undef CREATE_TYPEDARRAY
|
||||
}
|
||||
|
||||
/* static */
|
||||
Object *Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj) {
|
||||
return Object::createTypedArrayWithBuffer(type, obj, 0);
|
||||
}
|
||||
|
||||
/* static */
|
||||
Object *Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset) {
|
||||
size_t byteLength{0};
|
||||
uint8_t *skip{nullptr};
|
||||
obj->getTypedArrayData(&skip, &byteLength);
|
||||
return Object::createTypedArrayWithBuffer(type, obj, offset, byteLength - offset);
|
||||
}
|
||||
|
||||
/* static */
|
||||
Object *Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset, size_t byteLength) {
|
||||
if (type == TypedArrayType::NONE) {
|
||||
SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (type == TypedArrayType::UINT8_CLAMPED) {
|
||||
SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
assert(obj->isArrayBuffer());
|
||||
JS::RootedObject jsobj(__cx, obj->_getJSObject());
|
||||
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
arr = JS_NewInt8Array(__cx, (uint32_t)byteLength);
|
||||
tmpData = JS_GetInt8ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
arr = JS_NewInt16Array(__cx, (uint32_t)byteLength / 2);
|
||||
tmpData = JS_GetInt16ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
arr = JS_NewInt32Array(__cx, (uint32_t)byteLength / 4);
|
||||
tmpData = JS_GetInt32ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
arr = JS_NewUint8Array(__cx, (uint32_t)byteLength);
|
||||
tmpData = JS_GetUint8ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
arr = JS_NewUint16Array(__cx, (uint32_t)byteLength / 2);
|
||||
tmpData = JS_GetUint16ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
arr = JS_NewUint32Array(__cx, (uint32_t)byteLength / 4);
|
||||
tmpData = JS_GetUint32ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
arr = JS_NewFloat32Array(__cx, (uint32_t)byteLength / 4);
|
||||
tmpData = JS_GetFloat32ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
arr = JS_NewFloat64Array(__cx, (uint32_t)byteLength / 8);
|
||||
tmpData = JS_GetFloat64ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::INT8: {
|
||||
JS::RootedObject typeArray(__cx, JS_NewInt8ArrayWithBuffer(__cx, jsobj, offset, byteLength));
|
||||
return Object::_createJSObject(nullptr, typeArray);
|
||||
}
|
||||
case TypedArrayType::INT16: {
|
||||
JS::RootedObject typeArray(__cx, JS_NewInt16ArrayWithBuffer(__cx, jsobj, offset, byteLength / 2));
|
||||
return Object::_createJSObject(nullptr, typeArray);
|
||||
}
|
||||
case TypedArrayType::INT32: {
|
||||
JS::RootedObject typeArray(__cx, JS_NewInt32ArrayWithBuffer(__cx, jsobj, offset, byteLength / 4));
|
||||
return Object::_createJSObject(nullptr, typeArray);
|
||||
}
|
||||
case TypedArrayType::UINT8: {
|
||||
JS::RootedObject typeArray(__cx, JS_NewUint8ArrayWithBuffer(__cx, jsobj, offset, byteLength));
|
||||
return Object::_createJSObject(nullptr, typeArray);
|
||||
}
|
||||
case TypedArrayType::UINT16: {
|
||||
JS::RootedObject typeArray(__cx, JS_NewUint16ArrayWithBuffer(__cx, jsobj, offset, byteLength / 2));
|
||||
return Object::_createJSObject(nullptr, typeArray);
|
||||
}
|
||||
case TypedArrayType::UINT32: {
|
||||
JS::RootedObject typeArray(__cx, JS_NewUint32ArrayWithBuffer(__cx, jsobj, offset, byteLength / 4));
|
||||
return Object::_createJSObject(nullptr, typeArray);
|
||||
}
|
||||
case TypedArrayType::FLOAT32: {
|
||||
JS::RootedObject typeArray(__cx, JS_NewFloat32ArrayWithBuffer(__cx, jsobj, offset, byteLength / 4));
|
||||
return Object::_createJSObject(nullptr, typeArray);
|
||||
}
|
||||
case TypedArrayType::FLOAT64: {
|
||||
JS::RootedObject typeArray(__cx, JS_NewFloat64ArrayWithBuffer(__cx, jsobj, offset, byteLength / 8));
|
||||
return Object::_createJSObject(nullptr, typeArray);
|
||||
}
|
||||
default:
|
||||
assert(false); // Should never go here.
|
||||
break;
|
||||
}
|
||||
|
||||
//If data has content,then will copy data into buffer,or will only clear buffer.
|
||||
if (data) {
|
||||
memcpy(tmpData, (const void *)data, byteLength);
|
||||
} else {
|
||||
memset(tmpData, 0, byteLength);
|
||||
}
|
||||
|
||||
Object *obj = Object::_createJSObject(nullptr, arr);
|
||||
return obj;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Object *Object::createUint8TypedArray(uint8_t *data, size_t dataCount) {
|
||||
@@ -220,7 +330,7 @@ void Object::_setFinalizeCallback(JSFinalizeOp finalizeCb) {
|
||||
_finalizeCb = finalizeCb;
|
||||
}
|
||||
|
||||
bool Object::getProperty(const char *name, Value *data) {
|
||||
bool Object::getProperty(const char *name, Value *data, bool cachePropertyName) {
|
||||
assert(data != nullptr);
|
||||
data->setUndefined();
|
||||
|
||||
@@ -257,13 +367,32 @@ bool Object::setProperty(const char *name, const Value &v) {
|
||||
|
||||
bool Object::defineProperty(const char *name, JSNative getter, JSNative setter) {
|
||||
JS::RootedObject jsObj(__cx, _getJSObject());
|
||||
return JS_DefineProperty(__cx, jsObj, name, JS::UndefinedHandleValue, JSPROP_PERMANENT | JSPROP_ENUMERATE | JSPROP_SHARED, getter, setter);
|
||||
return JS_DefineProperty(__cx, jsObj, name, getter, setter, JSPROP_ENUMERATE);
|
||||
}
|
||||
|
||||
bool Object::defineOwnProperty(const char *name, const se::Value &value, bool writable, bool enumerable, bool configurable) {
|
||||
JS::RootedObject jsObj(__cx, _getJSObject());
|
||||
JS::RootedValue jsVal(__cx);
|
||||
internal::seToJsValue(__cx, value, &jsVal);
|
||||
|
||||
unsigned attrs = 0;
|
||||
if (!writable) {
|
||||
attrs |= JSPROP_READONLY;
|
||||
}
|
||||
if (enumerable) {
|
||||
attrs |= JSPROP_ENUMERATE;
|
||||
}
|
||||
if (!configurable) {
|
||||
attrs |= JSPROP_PERMANENT;
|
||||
}
|
||||
|
||||
return JS_DefineProperty(__cx, jsObj, name, jsVal, attrs);
|
||||
}
|
||||
|
||||
bool Object::call(const ValueArray &args, Object *thisObject, Value *rval /* = nullptr*/) {
|
||||
assert(isFunction());
|
||||
|
||||
JS::AutoValueVector jsarr(__cx);
|
||||
JS::RootedValueVector jsarr(__cx);
|
||||
jsarr.reserve(args.size());
|
||||
internal::seToJsArgs(__cx, args, &jsarr);
|
||||
|
||||
@@ -276,6 +405,7 @@ bool Object::call(const ValueArray &args, Object *thisObject, Value *rval /* = n
|
||||
JS::RootedValue func(__cx, JS::ObjectValue(*funcObj));
|
||||
JS::RootedValue rcValue(__cx);
|
||||
|
||||
JSAutoRealm autoRealm(__cx, func.toObjectOrNull());
|
||||
bool ok = JS_CallFunctionValue(__cx, contextObject, func, jsarr, &rcValue);
|
||||
|
||||
if (ok) {
|
||||
@@ -290,8 +420,8 @@ bool Object::call(const ValueArray &args, Object *thisObject, Value *rval /* = n
|
||||
|
||||
bool Object::defineFunction(const char *funcName, JSNative func) {
|
||||
JS::RootedObject object(__cx, _getJSObject());
|
||||
bool ok = JS_DefineFunction(__cx, object, funcName, func, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT);
|
||||
return ok;
|
||||
JSFunction* jsFunc = JS_DefineFunction(__cx, object, funcName, func, 0, JSPROP_ENUMERATE);
|
||||
return jsFunc != nullptr;
|
||||
}
|
||||
|
||||
bool Object::getArrayLength(uint32_t *length) const {
|
||||
@@ -300,7 +430,7 @@ bool Object::getArrayLength(uint32_t *length) const {
|
||||
return false;
|
||||
|
||||
JS::RootedObject object(__cx, _getJSObject());
|
||||
if (JS_GetArrayLength(__cx, object, length))
|
||||
if (JS::GetArrayLength(__cx, object, length))
|
||||
return true;
|
||||
|
||||
*length = 0;
|
||||
@@ -334,12 +464,12 @@ bool Object::setArrayElement(uint32_t index, const Value &data) {
|
||||
}
|
||||
|
||||
bool Object::isFunction() const {
|
||||
return JS_ObjectIsFunction(__cx, _getJSObject());
|
||||
return JS_ObjectIsFunction(_getJSObject());
|
||||
}
|
||||
|
||||
bool Object::_isNativeFunction(JSNative func) const {
|
||||
JSObject *obj = _getJSObject();
|
||||
return JS_ObjectIsFunction(__cx, obj) && JS_IsNativeFunction(obj, func);
|
||||
return JS_ObjectIsFunction(obj) && JS_IsNativeFunction(obj, func);
|
||||
}
|
||||
|
||||
bool Object::isTypedArray() const {
|
||||
@@ -374,20 +504,26 @@ Object::TypedArrayType Object::getTypedArrayType() const {
|
||||
bool Object::getTypedArrayData(uint8_t **ptr, size_t *length) const {
|
||||
assert(JS_IsArrayBufferViewObject(_getJSObject()));
|
||||
bool isShared = false;
|
||||
|
||||
JS::AutoCheckCannotGC nogc;
|
||||
*ptr = (uint8_t *)JS_GetArrayBufferViewData(_getJSObject(), &isShared, nogc);
|
||||
*length = JS_GetArrayBufferViewByteLength(_getJSObject());
|
||||
if (ptr != nullptr) {
|
||||
*ptr = (uint8_t *)JS_GetArrayBufferViewData(_getJSObject(), &isShared, nogc);
|
||||
}
|
||||
|
||||
if (length != nullptr) {
|
||||
*length = JS_GetArrayBufferViewByteLength(_getJSObject());
|
||||
}
|
||||
return (*ptr != nullptr);
|
||||
}
|
||||
|
||||
bool Object::isArray() const {
|
||||
JS::RootedValue value(__cx, JS::ObjectValue(*_getJSObject()));
|
||||
bool isArray = false;
|
||||
return JS_IsArrayObject(__cx, value, &isArray) && isArray;
|
||||
return JS::IsArrayObject(__cx, value, &isArray) && isArray;
|
||||
}
|
||||
|
||||
bool Object::isArrayBuffer() const {
|
||||
return JS_IsArrayBufferObject(_getJSObject());
|
||||
return JS::IsArrayBufferObject(_getJSObject());
|
||||
}
|
||||
|
||||
bool Object::getArrayBufferData(uint8_t **ptr, size_t *length) const {
|
||||
@@ -395,8 +531,13 @@ bool Object::getArrayBufferData(uint8_t **ptr, size_t *length) const {
|
||||
|
||||
bool isShared = false;
|
||||
JS::AutoCheckCannotGC nogc;
|
||||
*ptr = (uint8_t *)JS_GetArrayBufferData(_getJSObject(), &isShared, nogc);
|
||||
*length = JS_GetArrayBufferByteLength(_getJSObject());
|
||||
if (ptr != nullptr) {
|
||||
*ptr = (uint8_t *)JS::GetArrayBufferData(_getJSObject(), &isShared, nogc);
|
||||
}
|
||||
|
||||
if (length != nullptr) {
|
||||
*length = JS::GetArrayBufferByteLength(_getJSObject());
|
||||
}
|
||||
return (*ptr != nullptr);
|
||||
}
|
||||
|
||||
@@ -428,32 +569,45 @@ bool Object::getAllKeys(std::vector<std::string> *allKeys) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
void *Object::getPrivateData() const {
|
||||
if (_privateData == nullptr) {
|
||||
JS::RootedObject obj(__cx, _getJSObject());
|
||||
const_cast<Object *>(this)->_privateData = internal::getPrivate(__cx, obj);
|
||||
void Object::setPrivateObject(PrivateObjectBase *data) {
|
||||
assert(_privateObject == nullptr);
|
||||
#if CC_DEBUG
|
||||
//assert(NativePtrToObjectMap::find(data->getRaw()) == NativePtrToObjectMap::end());
|
||||
auto it = NativePtrToObjectMap::find(data->getRaw());
|
||||
if (it != NativePtrToObjectMap::end()) {
|
||||
auto *pri = it->second->getPrivateObject();
|
||||
SE_LOGE("Already exists object %s/[%s], trying to add %s/[%s]\n", pri->getName(), typeid(*pri).name(), data->getName(), typeid(*data).name());
|
||||
#if JSB_TRACK_OBJECT_CREATION
|
||||
SE_LOGE(" previous object created at %s\n", it->second->_objectCreationStackFrame.c_str());
|
||||
#endif
|
||||
assert(false);
|
||||
}
|
||||
return _privateData;
|
||||
#endif
|
||||
JS::RootedObject obj(__cx, _getJSObject());
|
||||
internal::setPrivate(__cx, obj, data, this, &_internalData, _finalizeCb); //TODO(cjh): how to use _internalData?
|
||||
NativePtrToObjectMap::emplace(data->getRaw(), this);
|
||||
_privateObject = data;
|
||||
defineOwnProperty("__native_ptr__", se::Value(static_cast<uint64_t>(reinterpret_cast<uintptr_t>(data->getRaw()))), false, false, false);
|
||||
}
|
||||
|
||||
void Object::setPrivateData(void *data) {
|
||||
assert(_privateData == nullptr);
|
||||
assert(NativePtrToObjectMap::find(data) == NativePtrToObjectMap::end());
|
||||
assert(_cls != nullptr);
|
||||
JS::RootedObject obj(__cx, _getJSObject());
|
||||
internal::setPrivate(__cx, obj, data, _finalizeCb);
|
||||
|
||||
NativePtrToObjectMap::emplace(data, this);
|
||||
_privateData = data;
|
||||
PrivateObjectBase *Object::getPrivateObject() const {
|
||||
if (_privateObject == nullptr) {
|
||||
JS::RootedObject obj(__cx, _getJSObject());
|
||||
const_cast<Object *>(this)->_privateObject = static_cast<PrivateObjectBase *>(internal::getPrivate(__cx, obj, 0));
|
||||
}
|
||||
return _privateObject;
|
||||
}
|
||||
|
||||
void Object::clearPrivateData(bool clearMapping) {
|
||||
if (_privateData != nullptr) {
|
||||
if (clearMapping)
|
||||
NativePtrToObjectMap::erase(_privateData);
|
||||
if (_privateObject != nullptr) {
|
||||
if (clearMapping) {
|
||||
NativePtrToObjectMap::erase(_privateObject->getRaw());
|
||||
}
|
||||
JS::RootedObject obj(__cx, _getJSObject());
|
||||
internal::clearPrivate(__cx, obj);
|
||||
_privateData = nullptr;
|
||||
defineOwnProperty("__native_ptr__", se::Value(static_cast<uint64_t>(reinterpret_cast<uintptr_t>(nullptr))), false, false, false);
|
||||
delete _privateObject;
|
||||
_privateObject = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -474,13 +628,12 @@ void Object::cleanup() {
|
||||
e.second->decRef();
|
||||
}
|
||||
NativePtrToObjectMap::clear();
|
||||
NonRefNativePtrCreatedByCtorMap::clear();
|
||||
__cx = nullptr;
|
||||
});
|
||||
}
|
||||
|
||||
JSObject *Object::_getJSObject() const {
|
||||
return isRooted() ? _root->get() : _heap.get();
|
||||
return isRooted() ? _root.get() : _heap.get();
|
||||
}
|
||||
|
||||
void Object::root() {
|
||||
@@ -501,50 +654,50 @@ void Object::unroot() {
|
||||
|
||||
void Object::protect() {
|
||||
assert(_root == nullptr);
|
||||
assert(_heap != JS::GCPolicy<JSObject *>::initial());
|
||||
assert(_heap != JS::SafelyInitialized<JSObject *>::create());
|
||||
|
||||
_root = new JS::PersistentRootedObject(__cx, _heap);
|
||||
_heap = JS::GCPolicy<JSObject *>::initial();
|
||||
_root.init(__cx, _heap);
|
||||
_heap.set(JS::SafelyInitialized<JSObject *>::create());
|
||||
}
|
||||
|
||||
void Object::unprotect() {
|
||||
if (_root == nullptr)
|
||||
if (!_root.initialized())
|
||||
return;
|
||||
|
||||
assert(_currentVMId == ScriptEngine::getInstance()->getVMId());
|
||||
assert(_heap == JS::GCPolicy<JSObject *>::initial());
|
||||
_heap = *_root;
|
||||
delete _root;
|
||||
_root = nullptr;
|
||||
assert(_heap == JS::SafelyInitialized<JSObject *>::create());
|
||||
_heap = _root.get();
|
||||
_root.reset();
|
||||
}
|
||||
|
||||
void Object::reset() {
|
||||
if (_root != nullptr) {
|
||||
delete _root;
|
||||
_root = nullptr;
|
||||
}
|
||||
_root.reset();
|
||||
_heap = JS::SafelyInitialized<JSObject *>::create();
|
||||
}
|
||||
|
||||
_heap = JS::GCPolicy<JSObject *>::initial();
|
||||
void Object::onTraceCallback(JSTracer* trc, void* data) {
|
||||
auto* thiz = reinterpret_cast<Object*>(data);
|
||||
thiz->trace(trc);
|
||||
}
|
||||
|
||||
/* Tracing makes no sense in the rooted case, because JS::PersistentRooted
|
||||
* already takes care of that. */
|
||||
void Object::trace(JSTracer *tracer, void *data) {
|
||||
void Object::trace(JSTracer *tracer) {
|
||||
assert(!isRooted());
|
||||
JS::TraceEdge(tracer, &_heap, "ccobj tracing");
|
||||
JS::TraceEdge(tracer, &_heap, "seobj tracing");
|
||||
}
|
||||
|
||||
/* If not tracing, then you must call this method during GC in order to
|
||||
* update the object's location if it was moved, or null it out if it was
|
||||
* finalized. If the object was finalized, returns true. */
|
||||
bool Object::updateAfterGC(void *data) {
|
||||
bool Object::updateAfterGC(JSTracer* trc, void *data) {
|
||||
assert(!isRooted());
|
||||
bool isGarbageCollected = false;
|
||||
internal::PrivateData *internalData = nullptr;
|
||||
|
||||
JSObject *oldPtr = _heap.unbarrieredGet();
|
||||
if (_heap.unbarrieredGet() != nullptr)
|
||||
JS_UpdateWeakPointerAfterGC(&_heap);
|
||||
JS_UpdateWeakPointerAfterGC(trc, &_heap);
|
||||
|
||||
JSObject *newPtr = _heap.unbarrieredGet();
|
||||
|
||||
@@ -574,7 +727,7 @@ bool Object::strictEquals(Object *o) const {
|
||||
JS::RootedValue v1(__cx, JS::ObjectValue(*_getJSObject()));
|
||||
JS::RootedValue v2(__cx, JS::ObjectValue(*o->_getJSObject()));
|
||||
bool same = false;
|
||||
bool ok = JS_SameValue(__cx, v1, v2, &same);
|
||||
bool ok = JS::SameValue(__cx, v1, v2, &same);
|
||||
return ok && same;
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,10 @@ namespace se {
|
||||
|
||||
class Class;
|
||||
|
||||
namespace internal {
|
||||
struct PrivateData;
|
||||
}
|
||||
|
||||
/**
|
||||
* se::Object represents JavaScript Object.
|
||||
*/
|
||||
@@ -92,6 +96,20 @@ public:
|
||||
*/
|
||||
static Object *createTypedArray(TypedArrayType type, const void *data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Typed Array Object with a se::Object, which is a ArrayBuffer,
|
||||
if provide a null pointer,then will create a empty JavaScript Typed Array Object.
|
||||
* @param[in] type The format of typed array.
|
||||
* @param[in] obj A ArrayBuffer to TypedArray.
|
||||
* @param[in] offset Offset of ArrayBuffer to create with.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object which refers to the ArrayBuffer Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj);
|
||||
static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset);
|
||||
static Object *createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Array Buffer object from an existing pointer.
|
||||
* @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
@@ -99,7 +117,10 @@ public:
|
||||
* @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object *createArrayBufferObject(void *data, size_t byteLength);
|
||||
static Object *createArrayBufferObject(const void *data, size_t byteLength);
|
||||
|
||||
using BufferContentsFreeFunc = void (*)(void* contents, size_t byteLength, void* userData);
|
||||
static Object *createExternalArrayBufferObject(void* contents, size_t nbytes, BufferContentsFreeFunc freeFunc, void* freeUserData = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Object from a JSON formatted string.
|
||||
@@ -131,7 +152,15 @@ public:
|
||||
* @param[out] value The property's value if object has the property, otherwise the undefined value.
|
||||
* @return true if object has the property, otherwise false.
|
||||
*/
|
||||
bool getProperty(const char *name, Value *value);
|
||||
inline bool getProperty(const char *name, Value *data) {
|
||||
return getProperty(name, data, false);
|
||||
}
|
||||
|
||||
bool getProperty(const char *name, Value *data, bool cachePropertyName);
|
||||
|
||||
inline bool getProperty(const std::string &name, Value *value) {
|
||||
return getProperty(name.c_str(), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets a property to an object.
|
||||
@@ -141,6 +170,10 @@ public:
|
||||
*/
|
||||
bool setProperty(const char *name, const Value &value);
|
||||
|
||||
inline bool setProperty(const std::string &name, const Value &value) {
|
||||
return setProperty(name.c_str(), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Defines a property with native accessor callbacks for an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
@@ -150,6 +183,8 @@ public:
|
||||
*/
|
||||
bool defineProperty(const char *name, JSNative getter, JSNative setter);
|
||||
|
||||
bool defineOwnProperty(const char *name, const se::Value &value, bool writable = true, bool enumerable = true, bool configurable = true);
|
||||
|
||||
/**
|
||||
* @brief Defines a function with a native callback for an object.
|
||||
* @param[in] funcName A utf-8 string containing the function name.
|
||||
@@ -242,19 +277,33 @@ public:
|
||||
*/
|
||||
bool getAllKeys(std::vector<std::string> *allKeys) const;
|
||||
|
||||
/**
|
||||
* @brief Sets a pointer to private data on an object.
|
||||
* @param[in] data A void* to set as the object's private data.
|
||||
* @note This method will associate private data with se::Object by std::unordered_map::emplace.
|
||||
* It's used for search a se::Object via a void* private data.
|
||||
*/
|
||||
void setPrivateData(void *data);
|
||||
void setPrivateObject(PrivateObjectBase *data);
|
||||
PrivateObjectBase *getPrivateObject() const;
|
||||
|
||||
/**
|
||||
* @brief Gets an object's private data.
|
||||
* @return A void* that is the object's private data, if the object has private data, otherwise nullptr.
|
||||
*/
|
||||
void *getPrivateData() const;
|
||||
* @brief Gets an object's private data.
|
||||
* @return A void* that is the object's private data, if the object has private data, otherwise nullptr.
|
||||
*/
|
||||
inline void *getPrivateData() const {
|
||||
return _privateObject ? _privateObject->getRaw() : nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sets a pointer to private data on an object.
|
||||
* @param[in] data A void* to set as the object's private data.
|
||||
* @note This method will associate private data with se::Object by std::unordered_map::emplace.
|
||||
* It's used for search a se::Object via a void* private data.
|
||||
*/
|
||||
template <typename T>
|
||||
inline void setPrivateData(T *data) {
|
||||
static_assert(!std::is_void<T>::value, "void * is not allowed for private data");
|
||||
setPrivateObject(se::make_shared_private_object(data));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline T *getTypedPrivateData() const {
|
||||
return reinterpret_cast<T *>(getPrivateData());
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Clears private data of an object.
|
||||
@@ -262,6 +311,12 @@ public:
|
||||
*/
|
||||
void clearPrivateData(bool clearMapping = true);
|
||||
|
||||
/**
|
||||
* @brief Sets whether to clear the mapping of native object & se::Object in finalizer
|
||||
*/
|
||||
inline void setClearMappingInFinalizer(bool v) { _clearMappingInFinalizer = v; }
|
||||
inline bool isClearMappingInFinalizer() const { return _clearMappingInFinalizer; }
|
||||
|
||||
/**
|
||||
* @brief Roots an object from garbage collection.
|
||||
* @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
|
||||
@@ -356,6 +411,7 @@ public:
|
||||
|
||||
// Private API used in wrapper
|
||||
static Object *_createJSObject(Class *cls, JSObject *obj);
|
||||
static Object *_createJSObjectForConstructor(Class *cls, const JS::CallArgs& args);
|
||||
void _setFinalizeCallback(JSFinalizeOp finalizeCb);
|
||||
bool _isNativeFunction(JSNative func) const;
|
||||
JSObject * _getJSObject() const;
|
||||
@@ -369,26 +425,31 @@ private:
|
||||
|
||||
static void setContext(JSContext *cx);
|
||||
static void cleanup();
|
||||
static void onTraceCallback(JSTracer* trc, void* data);
|
||||
|
||||
void trace(JSTracer *tracer, void *data);
|
||||
bool updateAfterGC(void *data);
|
||||
void trace(JSTracer *tracer);
|
||||
bool updateAfterGC(JSTracer* trc, void *data);
|
||||
|
||||
void protect();
|
||||
void unprotect();
|
||||
void reset();
|
||||
|
||||
JS::Heap<JSObject *> _heap; /* should be untouched if in rooted mode */
|
||||
JS::PersistentRootedObject *_root; /* should be null if not in rooted mode */
|
||||
JS::PersistentRootedObject _root; /* should be null if not in rooted mode */
|
||||
|
||||
void *_privateData;
|
||||
PrivateObjectBase * _privateObject{nullptr};
|
||||
internal::PrivateData *_internalData{nullptr};
|
||||
|
||||
Class * _cls;
|
||||
JSFinalizeOp _finalizeCb;
|
||||
Class * _cls{nullptr};
|
||||
JSFinalizeOp _finalizeCb{nullptr};
|
||||
|
||||
uint32_t _rootCount;
|
||||
uint32_t _currentVMId;
|
||||
uint32_t _rootCount{0};
|
||||
uint32_t _currentVMId{0};
|
||||
|
||||
bool _clearMappingInFinalizer{true};
|
||||
|
||||
friend class ScriptEngine;
|
||||
friend class Class;
|
||||
};
|
||||
|
||||
extern std::unordered_map<Object *, void *> __objectMap; // Currently, the value `void*` is always nullptr
|
||||
|
||||
@@ -66,30 +66,36 @@ const char *BYTE_CODE_FILE_EXT = ".jsc";
|
||||
|
||||
ScriptEngine *__instance = nullptr;
|
||||
|
||||
const JSClassOps __sandboxClassOps = {
|
||||
nullptr, nullptr, nullptr, nullptr,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, nullptr,
|
||||
JS_GlobalObjectTraceHook};
|
||||
const JSClassOps global_classOps = {
|
||||
nullptr, // addProperty
|
||||
nullptr, // delProperty
|
||||
nullptr, // enumerate
|
||||
nullptr, // newEnumerate
|
||||
nullptr, // resolve
|
||||
nullptr, // mayResolve
|
||||
nullptr, // finalize
|
||||
nullptr, // call
|
||||
nullptr, // hasInstance
|
||||
nullptr, // construct
|
||||
JS_GlobalObjectTraceHook, // trace
|
||||
};
|
||||
|
||||
JSClass __globalClass = {
|
||||
"global",
|
||||
JSCLASS_GLOBAL_FLAGS,
|
||||
&__sandboxClassOps};
|
||||
&global_classOps};
|
||||
|
||||
void reportWarning(JSContext *cx, JSErrorReport *report) {
|
||||
MOZ_RELEASE_ASSERT(report);
|
||||
MOZ_RELEASE_ASSERT(JSREPORT_IS_WARNING(report->flags));
|
||||
// MOZ_RELEASE_ASSERT(report->isWarning());
|
||||
|
||||
SE_LOGE("%s:%u:%s\n", report->filename ? report->filename : "<no filename>",
|
||||
(unsigned int)report->lineno,
|
||||
report->message().c_str());
|
||||
}
|
||||
|
||||
void SetStandardCompartmentOptions(JS::CompartmentOptions &options) {
|
||||
void SetStandardCompartmentOptions(JS::RealmOptions &options) {
|
||||
bool enableSharedMemory = true;
|
||||
options.behaviors().setVersion(JSVERSION_LATEST);
|
||||
options.creationOptions().setSharedMemoryAndAtomicsEnabled(enableSharedMemory);
|
||||
}
|
||||
|
||||
@@ -104,11 +110,9 @@ bool __log(JSContext *cx, uint32_t argc, JS::Value *vp) {
|
||||
JSString *string = JS::ToString(cx, args[0]);
|
||||
if (string) {
|
||||
JS::RootedString jsstr(cx, string);
|
||||
char * buffer = JS_EncodeStringToUTF8(cx, jsstr);
|
||||
JS::UniqueChars buffer = JS_EncodeStringToUTF8(cx, jsstr);
|
||||
|
||||
SE_LOGD("JS: %s\n", buffer);
|
||||
|
||||
JS_free(cx, buffer);
|
||||
SE_LOGD("JS: %s\n", buffer.get());
|
||||
}
|
||||
}
|
||||
args.rval().setUndefined();
|
||||
@@ -121,11 +125,11 @@ bool privateDataContructor(JSContext *cx, uint32_t argc, JS::Value *vp) {
|
||||
}
|
||||
|
||||
void privateDataFinalize(JSFreeOp *fop, JSObject *obj) {
|
||||
internal::PrivateData *p = (internal::PrivateData *)JS_GetPrivate(obj);
|
||||
internal::PrivateData *p = (internal::PrivateData *)internal::SE_JS_GetPrivate(obj, 0);
|
||||
if (p == nullptr)
|
||||
return;
|
||||
|
||||
JS_SetPrivate(obj, p->data);
|
||||
internal::SE_JS_SetPrivate(obj, 0, p->data);
|
||||
if (p->finalizeCb != nullptr)
|
||||
p->finalizeCb(fop, obj);
|
||||
free(p);
|
||||
@@ -133,7 +137,7 @@ void privateDataFinalize(JSFreeOp *fop, JSObject *obj) {
|
||||
|
||||
// ------------------------------------------------------- ScriptEngine
|
||||
|
||||
void on_garbage_collect(JSContext *cx, JSGCStatus status, void *data) {
|
||||
void on_garbage_collect(JSContext* cx, JSGCStatus status, JS::GCReason reason, void* data) {
|
||||
/* We finalize any pending toggle refs before doing any garbage collection,
|
||||
* so that we can collect the JS wrapper objects, and in order to minimize
|
||||
* the chances of objects having a pending toggle up queued when they are
|
||||
@@ -147,66 +151,6 @@ void on_garbage_collect(JSContext *cx, JSGCStatus status, void *data) {
|
||||
}
|
||||
}
|
||||
|
||||
// For promise
|
||||
using JobQueue = JS::GCVector<JSObject *, 0, js::SystemAllocPolicy>;
|
||||
|
||||
// Per-context promise state.
|
||||
struct PromiseState {
|
||||
explicit PromiseState(JSContext *cx);
|
||||
|
||||
JS::PersistentRooted<JobQueue> jobQueue;
|
||||
bool drainingJobQueue;
|
||||
bool quitting;
|
||||
};
|
||||
|
||||
PromiseState::PromiseState(JSContext *cx)
|
||||
: drainingJobQueue(false),
|
||||
quitting(false) {}
|
||||
|
||||
PromiseState *getPromiseState(JSContext *cx) {
|
||||
PromiseState *sc = static_cast<PromiseState *>(JS_GetContextPrivate(cx));
|
||||
assert(sc);
|
||||
return sc;
|
||||
}
|
||||
|
||||
JSObject *onGetIncumbentGlobalCallback(JSContext *cx) {
|
||||
return JS::CurrentGlobalOrNull(cx);
|
||||
}
|
||||
|
||||
bool onEnqueuePromiseJobCallback(JSContext *cx, JS::HandleObject job, JS::HandleObject allocationSite,
|
||||
JS::HandleObject incumbentGlobal, void *data) {
|
||||
PromiseState *sc = getPromiseState(cx);
|
||||
assert(job);
|
||||
return sc->jobQueue.append(job);
|
||||
}
|
||||
|
||||
bool drainJobQueue() {
|
||||
JSContext * cx = ScriptEngine::getInstance()->_getContext();
|
||||
PromiseState *sc = getPromiseState(cx);
|
||||
if (sc->quitting || sc->drainingJobQueue)
|
||||
return true;
|
||||
|
||||
sc->drainingJobQueue = true;
|
||||
|
||||
JS::RootedObject job(cx);
|
||||
JS::HandleValueArray args(JS::HandleValueArray::empty());
|
||||
JS::RootedValue rval(cx);
|
||||
// Execute jobs in a loop until we've reached the end of the queue.
|
||||
// Since executing a job can trigger enqueuing of additional jobs,
|
||||
// it's crucial to re-check the queue length during each iteration.
|
||||
for (size_t i = 0; i < sc->jobQueue.length(); i++) {
|
||||
job = sc->jobQueue[i];
|
||||
JSAutoCompartment ac(cx, job);
|
||||
JS::Call(cx, JS::UndefinedHandleValue, job, args, &rval);
|
||||
ScriptEngine::getInstance()->clearException();
|
||||
sc->jobQueue[i].set(nullptr);
|
||||
}
|
||||
sc->jobQueue.clear();
|
||||
sc->drainingJobQueue = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string removeFileExt(const std::string &filePath) {
|
||||
size_t pos = filePath.rfind('.');
|
||||
if (0 < pos) {
|
||||
@@ -215,10 +159,16 @@ std::string removeFileExt(const std::string &filePath) {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
bool getBytecodeBuildId(JS::BuildIdCharVector *buildId) {
|
||||
static const char *buildid = "cocos_xdr";
|
||||
bool ok = buildId->append(buildid, strlen(buildid));
|
||||
return ok;
|
||||
bool getBytecodeBuildId(JS::BuildIdCharVector* buildId) {
|
||||
// The browser embeds the date into the buildid and the buildid is embedded
|
||||
// in the binary, so every 'make' necessarily builds a new firefox binary.
|
||||
// Fortunately, the actual firefox executable is tiny -- all the code is in
|
||||
// libxul.so and other shared modules -- so this isn't a big deal. Not so
|
||||
// for the statically-linked JS shell. To avoid recompiling js.cpp and
|
||||
// re-linking 'js' on every 'make', we use a constant buildid and rely on
|
||||
// the shell user to manually clear any caches between cache-breaking updates.
|
||||
const char buildid[] = "cocos_xdr";
|
||||
return buildId->append(buildid, sizeof(buildid));
|
||||
}
|
||||
|
||||
// For console stuff
|
||||
@@ -289,13 +239,25 @@ bool JSB_console_assert(State &s) {
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(JSB_console_assert)
|
||||
|
||||
bool JSB_console_time(State &s) {
|
||||
return true; //TODO(cjh)
|
||||
}
|
||||
SE_BIND_FUNC(JSB_console_time)
|
||||
|
||||
bool JSB_console_timeEnd(State &s) {
|
||||
return true;//TODO(cjh)
|
||||
}
|
||||
SE_BIND_FUNC(JSB_console_timeEnd)
|
||||
|
||||
|
||||
} // namespace
|
||||
|
||||
AutoHandleScope::AutoHandleScope() {
|
||||
}
|
||||
|
||||
AutoHandleScope::~AutoHandleScope() {
|
||||
drainJobQueue();
|
||||
js::RunJobs(se::ScriptEngine::getInstance()->_getContext());
|
||||
}
|
||||
|
||||
ScriptEngine *ScriptEngine::getInstance() {
|
||||
@@ -328,12 +290,12 @@ ScriptEngine::ScriptEngine()
|
||||
}
|
||||
|
||||
/* static */
|
||||
void ScriptEngine::onWeakPointerCompartmentCallback(JSContext *cx, JSCompartment *comp, void *data) {
|
||||
onWeakPointerZoneGroupCallback(cx, data);
|
||||
void ScriptEngine::onWeakPointerCompartmentCallback(JSTracer* trc, JS::Compartment *comp, void *data) {
|
||||
onWeakPointerZoneGroupCallback(trc, data);
|
||||
}
|
||||
|
||||
/* static */
|
||||
void ScriptEngine::onWeakPointerZoneGroupCallback(JSContext *cx, void *data) {
|
||||
void ScriptEngine::onWeakPointerZoneGroupCallback(JSTracer* trc, void *data) {
|
||||
bool isInCleanup = getInstance()->isInCleanup();
|
||||
bool isIterUpdated = false;
|
||||
Object *obj = nullptr;
|
||||
@@ -342,7 +304,7 @@ void ScriptEngine::onWeakPointerZoneGroupCallback(JSContext *cx, void *data) {
|
||||
obj = iter->second;
|
||||
isIterUpdated = false;
|
||||
if (!obj->isRooted()) {
|
||||
if (obj->updateAfterGC(data)) {
|
||||
if (obj->updateAfterGC(trc, data)) {
|
||||
obj->decRef();
|
||||
iter = NativePtrToObjectMap::erase(iter);
|
||||
isIterUpdated = true;
|
||||
@@ -376,58 +338,56 @@ bool ScriptEngine::init() {
|
||||
return false;
|
||||
|
||||
NativePtrToObjectMap::init();
|
||||
NonRefNativePtrCreatedByCtorMap::init();
|
||||
|
||||
Class::setContext(_cx);
|
||||
Object::setContext(_cx);
|
||||
|
||||
js::UseInternalJobQueues(_cx);
|
||||
|
||||
JS_SetGCParameter(_cx, JSGC_MAX_BYTES, 0xffffffff);
|
||||
JS_SetGCParameter(_cx, JSGC_MODE, JSGC_MODE_INCREMENTAL);
|
||||
JS_SetGCParameter(_cx, JSGC_INCREMENTAL_GC_ENABLED, 1);
|
||||
JS_SetGCParameter(_cx, JSGC_PER_ZONE_GC_ENABLED, 1);
|
||||
JS_SetGCParameter(_cx, JSGC_COMPACTING_ENABLED, 1);
|
||||
|
||||
JS_SetNativeStackQuota(_cx, 5000000);
|
||||
|
||||
JS_SetOffthreadIonCompilationEnabled(_cx, true);
|
||||
JS_SetGlobalJitCompilerOption(_cx, JSJITCOMPILER_ION_ENABLE, 1);
|
||||
JS_SetGlobalJitCompilerOption(_cx, JSJITCOMPILER_BASELINE_ENABLE, 1);
|
||||
|
||||
JS_SetGCCallback(_cx, on_garbage_collect, nullptr);
|
||||
|
||||
if (!JS::InitSelfHostedCode(_cx))
|
||||
return false;
|
||||
|
||||
PromiseState *sc = new (std::nothrow) PromiseState(_cx);
|
||||
if (!sc)
|
||||
return false;
|
||||
|
||||
JS_SetContextPrivate(_cx, sc);
|
||||
|
||||
// Waiting is allowed on the shell's main thread, for now.
|
||||
JS_SetFutexCanWait(_cx);
|
||||
|
||||
JS::SetWarningReporter(_cx, reportWarning);
|
||||
|
||||
#if defined(JS_GC_ZEAL) && defined(DEBUG)
|
||||
// JS_SetGCZeal(_cx, 2, JS_DEFAULT_ZEAL_FREQ);
|
||||
#endif
|
||||
#if defined(JS_GC_ZEAL) && defined(DEBUG)
|
||||
// JS_SetGCZeal(_cx, 2, JS_DEFAULT_ZEAL_FREQ);
|
||||
#endif
|
||||
|
||||
JS_SetDefaultLocale(_cx, "UTF-8");
|
||||
|
||||
JS_BeginRequest(_cx);
|
||||
|
||||
JS::CompartmentOptions options;
|
||||
JS::RealmOptions options;
|
||||
SetStandardCompartmentOptions(options);
|
||||
|
||||
#ifdef DEBUG
|
||||
#ifdef DEBUG
|
||||
JS::ContextOptionsRef(_cx)
|
||||
.setExtraWarnings(true)
|
||||
.setIon(false)
|
||||
.setBaseline(false)
|
||||
.setAsmJS(false);
|
||||
#else
|
||||
.setDisableIon()
|
||||
.setWasmBaseline(false)
|
||||
.setAsmJS(false)
|
||||
.setWasm(false)
|
||||
.setWasmIon(false);
|
||||
#else
|
||||
JS::ContextOptionsRef(_cx)
|
||||
// .setExtraWarnings(true)
|
||||
.setIon(true)
|
||||
.setBaseline(true)
|
||||
.setAsmJS(true)
|
||||
.setNativeRegExp(true);
|
||||
#endif
|
||||
.setAsmJS(true)
|
||||
.setWasm(true)
|
||||
.setWasmBaseline(true)
|
||||
.setWasmIon(true);
|
||||
#endif
|
||||
|
||||
JSObject *globalObj = JS_NewGlobalObject(_cx, &__globalClass, nullptr, JS::DontFireOnNewGlobalHook, options);
|
||||
JS::RootedObject globalObj(_cx, JS_NewGlobalObject(_cx, &__globalClass, nullptr, JS::DontFireOnNewGlobalHook, options));
|
||||
|
||||
if (nullptr == globalObj)
|
||||
return false;
|
||||
@@ -437,8 +397,8 @@ bool ScriptEngine::init() {
|
||||
|
||||
JS::RootedObject rootedGlobalObj(_cx, _globalObj->_getJSObject());
|
||||
|
||||
_oldCompartment = JS_EnterCompartment(_cx, rootedGlobalObj);
|
||||
JS_InitStandardClasses(_cx, rootedGlobalObj);
|
||||
_oldCompartment = JS::EnterRealm(_cx, rootedGlobalObj);
|
||||
JS::InitRealmStandardClasses(_cx);
|
||||
|
||||
_globalObj->setProperty("window", Value(_globalObj));
|
||||
|
||||
@@ -454,6 +414,8 @@ bool ScriptEngine::init() {
|
||||
consoleObj->defineFunction("warn", _SE(JSB_console_warn));
|
||||
consoleObj->defineFunction("error", _SE(JSB_console_error));
|
||||
consoleObj->defineFunction("assert", _SE(JSB_console_assert));
|
||||
consoleObj->defineFunction("time", _SE(JSB_console_info)); //TODO(cjh)
|
||||
consoleObj->defineFunction("timeEnd", _SE(JSB_console_info)); //TODO(cjh)
|
||||
|
||||
_globalObj->setProperty("console", Value(consoleObj));
|
||||
|
||||
@@ -462,15 +424,8 @@ bool ScriptEngine::init() {
|
||||
JS_DefineFunction(_cx, rootedGlobalObj, "log", __log, 0, JSPROP_PERMANENT);
|
||||
JS_DefineFunction(_cx, rootedGlobalObj, "forceGC", __forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT);
|
||||
|
||||
// JS_AddWeakPointerZoneGroupCallback(_cx, ScriptEngine::onWeakPointerZoneGroupCallback, nullptr);
|
||||
JS_AddWeakPointerCompartmentCallback(_cx, ScriptEngine::onWeakPointerCompartmentCallback, nullptr);
|
||||
|
||||
JS_FireOnNewGlobalObject(_cx, rootedGlobalObj);
|
||||
JS::SetBuildIdOp(_cx, getBytecodeBuildId);
|
||||
|
||||
sc->jobQueue.init(_cx, JobQueue(js::SystemAllocPolicy()));
|
||||
JS::SetEnqueuePromiseJobCallback(_cx, onEnqueuePromiseJobCallback);
|
||||
JS::SetGetIncumbentGlobalCallback(_cx, onGetIncumbentGlobalCallback);
|
||||
JS::SetProcessBuildIdOp(getBytecodeBuildId);
|
||||
|
||||
__jsb_CCPrivateData_class = Class::create("__PrivateData", _globalObj, nullptr, privateDataContructor);
|
||||
__jsb_CCPrivateData_class->defineFinalizeFunction(privateDataFinalize);
|
||||
@@ -501,26 +456,14 @@ void ScriptEngine::cleanup() {
|
||||
}
|
||||
_beforeCleanupHookArray.clear();
|
||||
|
||||
auto sc = getPromiseState(_cx);
|
||||
sc->quitting = true;
|
||||
|
||||
SAFE_DEC_REF(_globalObj);
|
||||
Class::cleanup();
|
||||
Object::cleanup();
|
||||
|
||||
// JS_RemoveWeakPointerZoneGroupCallback(_cx, ScriptEngine::onWeakPointerZoneGroupCallback);
|
||||
// JS_RemoveWeakPointerCompartmentCallback(_cx, ScriptEngine::onWeakPointerCompartmentCallback);
|
||||
JS_LeaveCompartment(_cx, _oldCompartment);
|
||||
JS::LeaveRealm(_cx, _oldCompartment);
|
||||
|
||||
JS::SetGetIncumbentGlobalCallback(_cx, nullptr);
|
||||
JS::SetEnqueuePromiseJobCallback(_cx, nullptr);
|
||||
|
||||
sc->jobQueue.reset();
|
||||
|
||||
JS_EndRequest(_cx);
|
||||
JS_DestroyContext(_cx);
|
||||
|
||||
delete sc;
|
||||
_cx = nullptr;
|
||||
_globalObj = nullptr;
|
||||
_oldCompartment = nullptr;
|
||||
@@ -537,7 +480,6 @@ void ScriptEngine::cleanup() {
|
||||
_isInCleanup = false;
|
||||
|
||||
NativePtrToObjectMap::destroy();
|
||||
NonRefNativePtrCreatedByCtorMap::destroy();
|
||||
}
|
||||
|
||||
void ScriptEngine::addBeforeCleanupHook(const std::function<void()> &hook) {
|
||||
@@ -573,6 +515,12 @@ void ScriptEngine::addRegisterCallback(RegisterCallback cb) {
|
||||
_registerCallbackArray.push_back(cb);
|
||||
}
|
||||
|
||||
void ScriptEngine::addPermanentRegisterCallback(RegisterCallback cb) {
|
||||
if (std::find(_permRegisterCallbackArray.begin(), _permRegisterCallbackArray.end(), cb) == _permRegisterCallbackArray.end()) {
|
||||
_permRegisterCallbackArray.push_back(cb);
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - Debug
|
||||
|
||||
static std::string inData;
|
||||
@@ -593,7 +541,7 @@ static void cc_closesocket(int fd) {
|
||||
|
||||
void ScriptEngine::_debugProcessInput(const std::string &str) {
|
||||
JS::RootedObject debugGlobal(_cx, _debugGlobalObj->_getJSObject());
|
||||
JSCompartment * globalCpt = JS_EnterCompartment(_cx, debugGlobal);
|
||||
JS::Realm * globalCpt = JS::EnterRealm(_cx, debugGlobal);
|
||||
|
||||
Value func;
|
||||
if (_debugGlobalObj->getProperty("processInput", &func) && func.isObject() && func.toObject()->isFunction()) {
|
||||
@@ -602,7 +550,7 @@ void ScriptEngine::_debugProcessInput(const std::string &str) {
|
||||
func.toObject()->call(args, _debugGlobalObj);
|
||||
}
|
||||
|
||||
JS_LeaveCompartment(_cx, globalCpt);
|
||||
JS::LeaveRealm(_cx, globalCpt);
|
||||
}
|
||||
|
||||
static bool NS_ProcessNextEvent() {
|
||||
@@ -645,7 +593,7 @@ static bool JSBDebug_enterNestedEventLoop(State &s) {
|
||||
uint32_t nestLevel = ++s_nestedLoopLevel;
|
||||
|
||||
while (NS_SUCCEEDED(rv) && s_nestedLoopLevel >= nestLevel) {
|
||||
drainJobQueue();
|
||||
js::RunJobs(se::ScriptEngine::getInstance()->_getContext());
|
||||
if (!NS_ProcessNextEvent())
|
||||
rv = NS_ERROR_UNEXPECTED;
|
||||
}
|
||||
@@ -821,16 +769,15 @@ bool ScriptEngine::start() {
|
||||
return false;
|
||||
|
||||
if (isDebuggerEnabled() && _debugGlobalObj == nullptr) {
|
||||
JS::CompartmentOptions options;
|
||||
options.behaviors().setVersion(JSVERSION_LATEST);
|
||||
JS::RealmOptions options;
|
||||
options.creationOptions().setSharedMemoryAndAtomicsEnabled(true);
|
||||
|
||||
JS::RootedObject debugGlobal(_cx, JS_NewGlobalObject(_cx, &__globalClass, nullptr, JS::DontFireOnNewGlobalHook, options));
|
||||
_debugGlobalObj = Object::_createJSObject(nullptr, debugGlobal);
|
||||
_debugGlobalObj->root();
|
||||
|
||||
JSCompartment *globalCpt = JS_EnterCompartment(_cx, debugGlobal);
|
||||
JS_InitStandardClasses(_cx, debugGlobal);
|
||||
JS::Realm *globalCpt = JS::EnterRealm(_cx, debugGlobal);
|
||||
JS::InitRealmStandardClasses(_cx);
|
||||
JS_FireOnNewGlobalObject(_cx, debugGlobal);
|
||||
JS_DefineDebuggerObject(_cx, debugGlobal);
|
||||
|
||||
@@ -859,12 +806,20 @@ bool ScriptEngine::start() {
|
||||
auto t = std::thread(&serverEntryPoint, _debuggerServerPort);
|
||||
t.detach();
|
||||
|
||||
JS_LeaveCompartment(_cx, globalCpt);
|
||||
JS::LeaveRealm(_cx, globalCpt);
|
||||
}
|
||||
|
||||
bool ok = false;
|
||||
_startTime = std::chrono::steady_clock::now();
|
||||
|
||||
for (auto cb : _permRegisterCallbackArray) {
|
||||
ok = cb(_globalObj);
|
||||
assert(ok);
|
||||
if (!ok) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (auto cb : _registerCallbackArray) {
|
||||
ok = cb(_globalObj);
|
||||
assert(ok);
|
||||
@@ -947,15 +902,20 @@ bool ScriptEngine::compileScript(const std::string &path, JS::MutableHandleScrip
|
||||
/* Clear any pending exception from previous failed decoding. */
|
||||
clearException();
|
||||
|
||||
ok = false;
|
||||
std::string jsFileContent = _fileOperationDelegate.onGetStringFromFile(path);
|
||||
if (!jsFileContent.empty()) {
|
||||
JS::CompileOptions op(_cx);
|
||||
op.setUTF8(true);
|
||||
op.setFileAndLine(path.c_str(), 1);
|
||||
ok = JS::Compile(_cx, op, jsFileContent.c_str(), jsFileContent.size(), script);
|
||||
if (ok) {
|
||||
|
||||
JS::SourceText<mozilla::Utf8Unit> srcBuf;
|
||||
bool succeed = srcBuf.init(_cx, jsFileContent.c_str(), jsFileContent.length(),
|
||||
JS::SourceOwnership::Borrowed);
|
||||
|
||||
assert(succeed);
|
||||
JSScript* compiledScript = JS::Compile(_cx, op, srcBuf);
|
||||
if (compiledScript != nullptr) {
|
||||
compileSucceed = true;
|
||||
script.set(compiledScript);
|
||||
std::string fullPath = _fileOperationDelegate.onGetFullPath(path);
|
||||
_filenameScriptMap[fullPath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get());
|
||||
}
|
||||
@@ -982,12 +942,15 @@ bool ScriptEngine::evalString(const char *script, ssize_t length /* = -1 */, Val
|
||||
fileName = "(no filename)";
|
||||
|
||||
JS::CompileOptions options(_cx);
|
||||
options.setFile(fileName)
|
||||
.setUTF8(true)
|
||||
.setVersion(JSVERSION_LATEST);
|
||||
options.setFile(fileName);
|
||||
|
||||
JS::RootedValue rval(_cx);
|
||||
bool ok = JS::Evaluate(_cx, options, script, length, &rval);
|
||||
|
||||
JS::SourceText<mozilla::Utf8Unit> srcBuf;
|
||||
bool succeed = srcBuf.init(_cx, script, length, JS::SourceOwnership::Borrowed);
|
||||
assert(succeed);
|
||||
|
||||
bool ok = JS::Evaluate(_cx, options, srcBuf, &rval);
|
||||
if (!ok) {
|
||||
clearException();
|
||||
}
|
||||
@@ -1052,7 +1015,7 @@ void ScriptEngine::clearException() {
|
||||
snprintf(column, sizeof(column), "%u", report->column);
|
||||
const std::string location = filePath + ":" + line + ":" + column;
|
||||
|
||||
char *stack = nullptr; // Need to be freed by JS_free
|
||||
JS::UniqueChars stack;
|
||||
|
||||
JS::RootedValue stackVal(_cx);
|
||||
if (JS_GetProperty(_cx, exceptionObj, "stack", &stackVal) && stackVal.isString()) {
|
||||
@@ -1064,12 +1027,12 @@ void ScriptEngine::clearException() {
|
||||
exceptionStr += ", location: " + location;
|
||||
if (stack != nullptr) {
|
||||
exceptionStr += "\nSTACK:\n";
|
||||
exceptionStr += stack;
|
||||
exceptionStr += stack.get();
|
||||
}
|
||||
|
||||
SE_LOGE("ERROR: %s\n", exceptionStr.c_str());
|
||||
if (_exceptionCallback != nullptr) {
|
||||
_exceptionCallback(location.c_str(), message, stack);
|
||||
_exceptionCallback(location.c_str(), message, stack.get());
|
||||
}
|
||||
|
||||
if (!_isErrorHandleWorking) {
|
||||
@@ -1081,7 +1044,14 @@ void ScriptEngine::clearException() {
|
||||
args.push_back(Value(filePath));
|
||||
args.push_back(Value(report->lineno));
|
||||
args.push_back(Value(message));
|
||||
args.push_back(Value(stack));
|
||||
if (stack)
|
||||
{
|
||||
args.push_back(Value(stack.get()));
|
||||
}
|
||||
else
|
||||
{
|
||||
args.push_back(Value(""));
|
||||
}
|
||||
errorHandler.toObject()->call(args, _globalObj);
|
||||
}
|
||||
|
||||
@@ -1089,11 +1059,6 @@ void ScriptEngine::clearException() {
|
||||
} else {
|
||||
SE_LOGE("ERROR: __errorHandler has exception\n");
|
||||
}
|
||||
|
||||
if (stack != nullptr) {
|
||||
JS_free(_cx, stack);
|
||||
stack = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1101,6 +1066,10 @@ void ScriptEngine::setExceptionCallback(const ExceptionCallback &cb) {
|
||||
_exceptionCallback = cb;
|
||||
}
|
||||
|
||||
void ScriptEngine::setJSExceptionCallback(const ExceptionCallback &cb) { //TODO(cjh)
|
||||
|
||||
}
|
||||
|
||||
void ScriptEngine::enableDebugger(const std::string &serverAddr, uint32_t port, bool isWait) {
|
||||
_debuggerServerAddr = serverAddr;
|
||||
_debuggerServerPort = port;
|
||||
@@ -1111,6 +1080,11 @@ bool ScriptEngine::isDebuggerEnabled() const {
|
||||
}
|
||||
|
||||
void ScriptEngine::mainLoopUpdate() {
|
||||
js::RunJobs(_cx);
|
||||
|
||||
if (!isDebuggerEnabled()) {
|
||||
return;
|
||||
}
|
||||
std::string message;
|
||||
size_t messageCount = 0;
|
||||
while (true) {
|
||||
@@ -1133,6 +1107,56 @@ void ScriptEngine::mainLoopUpdate() {
|
||||
}
|
||||
}
|
||||
|
||||
bool ScriptEngine::callFunction(Object *targetObj, const char *funcName, uint32_t argc, Value *args, Value *rval /* = nullptr*/) {
|
||||
JS::RootedValueVector jsarr(_cx);
|
||||
if (!jsarr.reserve(argc)) {
|
||||
SE_LOGE("ScriptEngine::callFunction out of memory!");
|
||||
return false;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < argc; ++i) {
|
||||
JS::RootedValue jsval(_cx);
|
||||
internal::seToJsValue(_cx, args[i], &jsval);
|
||||
jsarr.append(jsval);
|
||||
}
|
||||
|
||||
JS::RootedObject contextObject(_cx);
|
||||
if (targetObj != nullptr) {
|
||||
contextObject.set(targetObj->_getJSObject());
|
||||
}
|
||||
|
||||
bool found = false;
|
||||
bool ok = JS_HasProperty(_cx, contextObject, funcName, &found);
|
||||
|
||||
if (!ok || !found) {
|
||||
return false;
|
||||
}
|
||||
|
||||
JS::RootedValue funcValue(_cx);
|
||||
ok = JS_GetProperty(_cx, contextObject, funcName, &funcValue);
|
||||
|
||||
if (!ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
JS::RootedValue rcValue(_cx);
|
||||
JSAutoRealm autoRealm(_cx, funcValue.toObjectOrNull());
|
||||
ok = JS_CallFunctionValue(_cx, contextObject, funcValue, jsarr, &rcValue);
|
||||
|
||||
if (ok) {
|
||||
if (rval != nullptr)
|
||||
internal::jsToSeValue(_cx, rcValue, rval);
|
||||
} else {
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
}
|
||||
|
||||
return ok;
|
||||
}
|
||||
|
||||
void ScriptEngine::handlePromiseExceptions() {
|
||||
clearException();
|
||||
} //TODO(cjh)
|
||||
|
||||
} // namespace se
|
||||
|
||||
#endif // #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
|
||||
|
||||
@@ -83,6 +83,13 @@ public:
|
||||
*/
|
||||
void addRegisterCallback(RegisterCallback cb);
|
||||
|
||||
/**
|
||||
* @brief Adds a callback for registering a native binding module, which will not be removed by ScriptEngine::cleanup.
|
||||
* @param[in] cb A callback for registering a native binding module.
|
||||
* @note This method just add a callback to a vector, callbacks is invoked in `start` method.
|
||||
*/
|
||||
void addPermanentRegisterCallback(RegisterCallback cb);
|
||||
|
||||
/**
|
||||
* @brief Starts the script engine.
|
||||
* @return true if succeed, otherwise false.
|
||||
@@ -141,6 +148,20 @@ public:
|
||||
*/
|
||||
bool evalString(const char *scriptStr, ssize_t length = -1, Value *rval = nullptr, const char *fileName = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Compile script file into v8::ScriptCompiler::CachedData and save to file.
|
||||
* @param[in] path The path of script file.
|
||||
* @param[in] pathBc The location where bytecode file should be written to. The path should be ends with ".bc", which indicates a bytecode file.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool saveByteCodeToFile(const std::string &path, const std::string &pathBc) { assert(false); return false; } //cjh
|
||||
|
||||
/**
|
||||
* @brief Grab a snapshot of the current JavaScript execution stack.
|
||||
* @return current stack trace string
|
||||
*/
|
||||
std::string getCurrentStackTrace() { return ""; } //cjh
|
||||
|
||||
/**
|
||||
* Delegate class for file operation
|
||||
*/
|
||||
@@ -209,6 +230,11 @@ public:
|
||||
*/
|
||||
bool isValid() { return _isValid; }
|
||||
|
||||
/**
|
||||
* @brief Throw JS exception
|
||||
*/
|
||||
void throwException(const std::string &errorMessage) { assert(false); } //cjh
|
||||
|
||||
/**
|
||||
* @brief Clears all exceptions.
|
||||
*/
|
||||
@@ -222,6 +248,12 @@ public:
|
||||
*/
|
||||
void setExceptionCallback(const ExceptionCallback &cb);
|
||||
|
||||
/**
|
||||
* @brief Sets the callback function while an exception is fired in JS.
|
||||
* @param[in] cb The callback function to notify that an exception is fired.
|
||||
*/
|
||||
void setJSExceptionCallback(const ExceptionCallback &cb);
|
||||
|
||||
/**
|
||||
* @brief Gets the start time of script engine.
|
||||
* @return The start time of script engine.
|
||||
@@ -252,6 +284,17 @@ public:
|
||||
*/
|
||||
uint32_t getVMId() const { return _vmId; }
|
||||
|
||||
/**
|
||||
* @brief Fast version of call script function, faster than Object::call
|
||||
*/
|
||||
bool callFunction(Object *targetObj, const char *funcName, uint32_t argc, Value *args, Value *rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Handle all exceptions throwed by promise
|
||||
*/
|
||||
void handlePromiseExceptions();
|
||||
|
||||
|
||||
// Private API used in wrapper
|
||||
JSContext *_getContext() { return _cx; }
|
||||
void _setGarbageCollecting(bool isGarbageCollecting);
|
||||
@@ -261,14 +304,14 @@ private:
|
||||
ScriptEngine();
|
||||
~ScriptEngine();
|
||||
|
||||
static void onWeakPointerCompartmentCallback(JSContext *cx, JSCompartment *comp, void *data);
|
||||
static void onWeakPointerZoneGroupCallback(JSContext *cx, void *data);
|
||||
static void onWeakPointerCompartmentCallback(JSTracer* trc, JS::Compartment *comp, void *data);
|
||||
static void onWeakPointerZoneGroupCallback(JSTracer *trc, void *data);
|
||||
|
||||
bool getScript(const std::string &path, JS::MutableHandleScript script);
|
||||
bool compileScript(const std::string &path, JS::MutableHandleScript script);
|
||||
|
||||
JSContext * _cx;
|
||||
JSCompartment *_oldCompartment;
|
||||
JS::Realm *_oldCompartment;
|
||||
|
||||
Object *_globalObj;
|
||||
Object *_debugGlobalObj;
|
||||
@@ -276,6 +319,7 @@ private:
|
||||
FileOperationDelegate _fileOperationDelegate;
|
||||
|
||||
std::vector<RegisterCallback> _registerCallbackArray;
|
||||
std::vector<RegisterCallback> _permRegisterCallbackArray;
|
||||
std::chrono::steady_clock::time_point _startTime;
|
||||
|
||||
std::vector<std::function<void()>> _beforeInitHookArray;
|
||||
|
||||
@@ -36,6 +36,22 @@ namespace se {
|
||||
|
||||
namespace internal {
|
||||
|
||||
void* SE_JS_GetPrivate(JSObject* obj, uint32_t slot) {
|
||||
assert(slot >= 0 && slot < 2);
|
||||
const auto& v = JS::GetReservedSlot(obj, slot);
|
||||
return v.isNullOrUndefined() ? nullptr : v.toPrivate();
|
||||
}
|
||||
|
||||
void SE_JS_SetPrivate(JSObject* obj, uint32_t slot, void* data) {
|
||||
assert(slot >= 0 && slot < 2);
|
||||
JS::SetReservedSlot(obj, slot, JS::PrivateValue(data));
|
||||
}
|
||||
|
||||
bool isJSBClass(JSObject* obj) {
|
||||
const JSClass *cls = JS::GetClass(obj);
|
||||
return (cls->flags & (JSCLASS_HAS_RESERVED_SLOTS(2)) && (cls->flags & JSCLASS_USERBIT1));
|
||||
}
|
||||
|
||||
void forceConvertJsValueToStdString(JSContext *cx, JS::HandleValue jsval, std::string *ret) {
|
||||
assert(ret != nullptr);
|
||||
JS::RootedString jsStr(cx, JS::ToString(cx, jsval));
|
||||
@@ -43,22 +59,18 @@ void forceConvertJsValueToStdString(JSContext *cx, JS::HandleValue jsval, std::s
|
||||
}
|
||||
|
||||
std::string jsToStdString(JSContext *cx, JS::HandleString jsStr) {
|
||||
char * str = JS_EncodeStringToUTF8(cx, jsStr);
|
||||
std::string ret(str);
|
||||
JS_free(cx, str);
|
||||
JS::UniqueChars str = JS_EncodeStringToUTF8(cx, jsStr);
|
||||
std::string ret(str.get());
|
||||
return ret;
|
||||
}
|
||||
|
||||
void jsToSeArgs(JSContext *cx, int argc, const JS::CallArgs &argv, ValueArray *outArr) {
|
||||
outArr->reserve(argc);
|
||||
void jsToSeArgs(JSContext *cx, int argc, const JS::CallArgs &argv, ValueArray &outArr) {
|
||||
for (int i = 0; i < argc; ++i) {
|
||||
Value v;
|
||||
jsToSeValue(cx, argv[i], &v);
|
||||
outArr->push_back(v);
|
||||
jsToSeValue(cx, argv[i], &outArr[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void seToJsArgs(JSContext *cx, const ValueArray &args, JS::AutoValueVector *outArr) {
|
||||
void seToJsArgs(JSContext *cx, const ValueArray &args, JS::RootedValueVector *outArr) {
|
||||
for (const auto &arg : args) {
|
||||
JS::RootedValue v(cx);
|
||||
seToJsValue(cx, arg, &v);
|
||||
@@ -104,6 +116,12 @@ void seToJsValue(JSContext *cx, const Value &arg, JS::MutableHandleValue outVal)
|
||||
value.setUndefined();
|
||||
outVal.set(value);
|
||||
} break;
|
||||
case Value::Type::BigInt: {
|
||||
JS::RootedValue value(cx);
|
||||
JS::BigInt* bi = JS::NumberToBigInt(cx, arg.toUint64());
|
||||
outVal.setBigInt(bi);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
assert(false);
|
||||
break;
|
||||
@@ -122,21 +140,25 @@ void jsToSeValue(JSContext *cx, JS::HandleValue jsval, Value *v) {
|
||||
Object *object = nullptr;
|
||||
|
||||
JS::RootedObject jsobj(cx, jsval.toObjectOrNull());
|
||||
void * nativeObj = getPrivate(cx, jsobj);
|
||||
|
||||
PrivateObjectBase *privateObject = static_cast<PrivateObjectBase *>(internal::getPrivate(cx, jsobj, 0));
|
||||
void *nativeObj = privateObject ? privateObject->getRaw() : nullptr;
|
||||
bool needRoot = false;
|
||||
if (nativeObj != nullptr) {
|
||||
object = Object::getObjectWithPtr(nativeObj);
|
||||
}
|
||||
|
||||
if (object == nullptr) {
|
||||
object = Object::_createJSObject(nullptr, jsval.toObjectOrNull());
|
||||
object = Object::_createJSObject(nullptr, jsobj);
|
||||
needRoot = true;
|
||||
}
|
||||
v->setObject(object, true);
|
||||
v->setObject(object, needRoot);
|
||||
object->decRef();
|
||||
} else if (jsval.isNull()) {
|
||||
v->setNull();
|
||||
} else if (jsval.isUndefined()) {
|
||||
v->setUndefined();
|
||||
} else if (jsval.isBigInt()) {
|
||||
v->setUint64(JS::ToBigUint64(jsval.toBigInt()));
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
@@ -151,10 +173,7 @@ void setReturnValue(JSContext *cx, const Value &data, const JS::CallArgs &argv)
|
||||
const char *KEY_PRIVATE_DATA = "__cc_private_data";
|
||||
|
||||
bool hasPrivate(JSContext *cx, JS::HandleObject obj) {
|
||||
bool found = false;
|
||||
const JSClass *cls = JS_GetClass(obj);
|
||||
found = !!(cls->flags & JSCLASS_HAS_PRIVATE);
|
||||
|
||||
bool found = isJSBClass(obj);
|
||||
if (!found) {
|
||||
JS::RootedObject jsobj(cx, obj);
|
||||
if (JS_HasProperty(cx, jsobj, KEY_PRIVATE_DATA, &found) && found) {
|
||||
@@ -165,19 +184,16 @@ bool hasPrivate(JSContext *cx, JS::HandleObject obj) {
|
||||
return found;
|
||||
}
|
||||
|
||||
void *getPrivate(JSContext *cx, JS::HandleObject obj) {
|
||||
bool found = false;
|
||||
const JSClass *cls = JS_GetClass(obj);
|
||||
found = !!(cls->flags & JSCLASS_HAS_PRIVATE);
|
||||
|
||||
void *getPrivate(JSContext *cx, JS::HandleObject obj, uint32_t slot) {
|
||||
bool found = isJSBClass(obj);
|
||||
if (found) {
|
||||
return JS_GetPrivate(obj);
|
||||
return SE_JS_GetPrivate(obj, slot);
|
||||
}
|
||||
|
||||
if (JS_HasProperty(cx, obj, KEY_PRIVATE_DATA, &found) && found) {
|
||||
JS::RootedValue jsData(cx);
|
||||
if (JS_GetProperty(cx, obj, KEY_PRIVATE_DATA, &jsData)) {
|
||||
PrivateData *privateData = (PrivateData *)JS_GetPrivate(jsData.toObjectOrNull());
|
||||
PrivateData *privateData = (PrivateData *)SE_JS_GetPrivate(jsData.toObjectOrNull(), slot);
|
||||
return privateData->data;
|
||||
}
|
||||
}
|
||||
@@ -185,41 +201,45 @@ void *getPrivate(JSContext *cx, JS::HandleObject obj) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void setPrivate(JSContext *cx, JS::HandleObject obj, void *data, JSFinalizeOp finalizeCb) {
|
||||
bool found = false;
|
||||
const JSClass *jsCls = JS_GetClass(obj);
|
||||
found = !!(jsCls->flags & JSCLASS_HAS_PRIVATE);
|
||||
void setPrivate(JSContext *cx, JS::HandleObject obj, PrivateObjectBase *data, Object *seObj, PrivateData **outInternalData, JSFinalizeOp finalizeCb) {
|
||||
bool found = isJSBClass(obj);
|
||||
|
||||
if (found) {
|
||||
JS_SetPrivate(obj, data);
|
||||
SE_JS_SetPrivate(obj, 0, data);
|
||||
SE_JS_SetPrivate(obj, 1, seObj);
|
||||
if (outInternalData != nullptr) {
|
||||
*outInternalData = nullptr;
|
||||
}
|
||||
} else {
|
||||
assert(finalizeCb);
|
||||
Object * privateObj = Object::createObjectWithClass(__jsb_CCPrivateData_class);
|
||||
PrivateData *privateData = (PrivateData *)malloc(sizeof(PrivateData));
|
||||
privateData->data = data;
|
||||
privateData->seObj = privateObj;
|
||||
privateData->finalizeCb = finalizeCb;
|
||||
JS_SetPrivate(privateObj->_getJSObject(), privateData);
|
||||
|
||||
JS::RootedObject jsPrivateObj(cx, privateObj->_getJSObject());
|
||||
SE_JS_SetPrivate(jsPrivateObj, 0 , se::make_shared_private_object(privateData));
|
||||
SE_JS_SetPrivate(jsPrivateObj, 1, seObj);
|
||||
|
||||
JS::RootedValue privateVal(cx, JS::ObjectValue(*privateObj->_getJSObject()));
|
||||
JS_SetProperty(cx, obj, KEY_PRIVATE_DATA, privateVal);
|
||||
privateObj->decRef();
|
||||
// privateObj->decRef(); // NOTE: it's released in ScriptEngine::privateDataFinalize
|
||||
}
|
||||
}
|
||||
|
||||
void clearPrivate(JSContext *cx, JS::HandleObject obj) {
|
||||
bool found = false;
|
||||
const JSClass *cls = JS_GetClass(obj);
|
||||
found = !!(cls->flags & JSCLASS_HAS_PRIVATE);
|
||||
|
||||
bool found = isJSBClass(obj);
|
||||
if (found) {
|
||||
JS_SetPrivate(obj, nullptr);
|
||||
SE_JS_SetPrivate(obj, 0, nullptr);
|
||||
SE_JS_SetPrivate(obj, 1, nullptr);
|
||||
} else if (JS_HasProperty(cx, obj, KEY_PRIVATE_DATA, &found) && found) {
|
||||
JS::RootedValue jsData(cx);
|
||||
assert(JS_GetProperty(cx, obj, KEY_PRIVATE_DATA, &jsData));
|
||||
|
||||
PrivateData *privateData = (PrivateData *)JS_GetPrivate(jsData.toObjectOrNull());
|
||||
PrivateData *privateData = (PrivateData *)SE_JS_GetPrivate(jsData.toObjectOrNull(), 0);
|
||||
free(privateData);
|
||||
JS_SetPrivate(jsData.toObjectOrNull(), nullptr);
|
||||
SE_JS_SetPrivate(jsData.toObjectOrNull(), 0, nullptr);
|
||||
bool ok = JS_DeleteProperty(cx, obj, KEY_PRIVATE_DATA);
|
||||
assert(ok);
|
||||
}
|
||||
|
||||
@@ -40,26 +40,30 @@ class Class;
|
||||
|
||||
namespace internal {
|
||||
|
||||
struct PrivateData {
|
||||
void * data;
|
||||
JSFinalizeOp finalizeCb;
|
||||
struct PrivateData {
|
||||
PrivateObjectBase *data{nullptr};
|
||||
Object * seObj{nullptr};
|
||||
JSFinalizeOp finalizeCb{nullptr};
|
||||
};
|
||||
|
||||
void forceConvertJsValueToStdString(JSContext *cx, JS::HandleValue jsval, std::string *ret);
|
||||
std::string jsToStdString(JSContext *cx, JS::HandleString jsStr);
|
||||
|
||||
void jsToSeArgs(JSContext *cx, int argc, const JS::CallArgs &argv, ValueArray *outArr);
|
||||
void jsToSeArgs(JSContext *cx, int argc, const JS::CallArgs &argv, ValueArray &outArr);
|
||||
void jsToSeValue(JSContext *cx, JS::HandleValue jsval, Value *v);
|
||||
void seToJsArgs(JSContext *cx, const ValueArray &args, JS::AutoValueVector *outArr);
|
||||
void seToJsArgs(JSContext *cx, const ValueArray &args, JS::RootedValueVector *outArr);
|
||||
void seToJsValue(JSContext *cx, const Value &v, JS::MutableHandleValue outVal);
|
||||
|
||||
void setReturnValue(JSContext *cx, const Value &data, const JS::CallArgs &argv);
|
||||
|
||||
bool hasPrivate(JSContext *cx, JS::HandleObject obj);
|
||||
void *getPrivate(JSContext *cx, JS::HandleObject obj);
|
||||
void setPrivate(JSContext *cx, JS::HandleObject obj, void *data, JSFinalizeOp finalizeCb);
|
||||
void *getPrivate(JSContext *cx, JS::HandleObject obj, uint32_t slot);
|
||||
void setPrivate(JSContext *cx, JS::HandleObject obj, PrivateObjectBase *data, Object *seObj, PrivateData **outInternalData, JSFinalizeOp finalizeCb);
|
||||
void clearPrivate(JSContext *cx, JS::HandleObject obj);
|
||||
|
||||
void* SE_JS_GetPrivate(JSObject* obj, uint32_t slot);
|
||||
void SE_JS_SetPrivate(JSObject* obj, uint32_t slot, void* data);
|
||||
|
||||
} // namespace internal
|
||||
|
||||
} // namespace se
|
||||
|
||||
@@ -200,6 +200,18 @@ Object *Object::createArrayBufferObject(const void *data, size_t byteLength) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
/* static */
|
||||
Object *Object::createExternalArrayBufferObject(void* contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void* freeUserData/* = nullptr*/) {
|
||||
std::shared_ptr<v8::BackingStore> backingStore = v8::ArrayBuffer::NewBackingStore(contents, byteLength, freeFunc, freeUserData);
|
||||
Object* obj = nullptr;
|
||||
v8::Local<v8::ArrayBuffer> jsobj = v8::ArrayBuffer::New(__isolate, backingStore);
|
||||
if (!jsobj.IsEmpty())
|
||||
{
|
||||
obj = Object::_createJSObject(nullptr, jsobj);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object *Object::createTypedArray(TypedArrayType type, const void *data, size_t byteLength) {
|
||||
if (type == TypedArrayType::NONE) {
|
||||
SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!");
|
||||
|
||||
@@ -131,6 +131,10 @@ public:
|
||||
*/
|
||||
static Object *createArrayBufferObject(const void *data, size_t byteLength);
|
||||
|
||||
using BufferContentsFreeFunc = void (*)(void* contents, size_t byteLength, void* userData);
|
||||
static Object *createExternalArrayBufferObject(void* contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void* freeUserData = nullptr);
|
||||
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Object from a JSON formatted string.
|
||||
* @param[in] jsonStr The utf-8 string containing the JSON string to be parsed.
|
||||
|
||||
@@ -52,16 +52,6 @@ static bool js_assets_Asset_getNativeDep(se::State &s) // NOLINT(readability-ide
|
||||
}
|
||||
SE_BIND_PROP_GET(js_assets_Asset_getNativeDep) // NOLINT(readability-identifier-naming)
|
||||
|
||||
static bool js_assets_ImageAsset_getData(se::State &s) // NOLINT(readability-identifier-naming)
|
||||
{
|
||||
auto *cobj = SE_THIS_OBJECT<cc::ImageAsset>(s);
|
||||
SE_PRECONDITION2(cobj, false, "js_assets_ImageAsset_getData : Invalid Native Object");
|
||||
|
||||
s.rval().setUint64(reinterpret_cast<intptr_t>(cobj->getData()));
|
||||
return false;
|
||||
}
|
||||
SE_BIND_PROP_GET(js_assets_ImageAsset_getData) // NOLINT(readability-identifier-naming)
|
||||
|
||||
static bool js_assets_ImageAsset_setData(se::State &s) // NOLINT(readability-identifier-naming)
|
||||
{
|
||||
auto *cobj = SE_THIS_OBJECT<cc::ImageAsset>(s);
|
||||
|
||||
@@ -812,6 +812,33 @@ SE_BIND_FUNC(JSB_hideInputBox)
|
||||
|
||||
#endif
|
||||
|
||||
static bool jsb_createExternalArrayBuffer(se::State& s) {
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
uint32_t byteLength{0};
|
||||
ok &= sevalue_to_native(args[0], &byteLength, s.thisObject());
|
||||
SE_PRECONDITION2(ok, false, "jsb_createExternalArrayBuffer : Error processing arguments");
|
||||
if (byteLength > 0) {
|
||||
void *buffer = malloc(byteLength);
|
||||
memset(buffer, 0x00, byteLength);
|
||||
se::HandleObject arrayBuffer{se::Object::createExternalArrayBufferObject(buffer, byteLength, [](void* contents, size_t /*byteLength*/, void*/* userData */){
|
||||
if (contents != nullptr) {
|
||||
free(contents);
|
||||
}
|
||||
})};
|
||||
s.rval().setObject(arrayBuffer);
|
||||
} else {
|
||||
s.rval().setNull();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(jsb_createExternalArrayBuffer)
|
||||
|
||||
bool jsb_register_global_variables(se::Object *global) { //NOLINT
|
||||
gThreadPool = LegacyThreadPool::newFixedThreadPool(3);
|
||||
|
||||
@@ -820,9 +847,6 @@ bool jsb_register_global_variables(se::Object *global) { //NOLINT
|
||||
|
||||
getOrCreatePlainObject_r("jsb", global, &__jsbObj);
|
||||
|
||||
auto glContextCls = se::Class::create("WebGLRenderingContext", global, nullptr, nullptr);
|
||||
glContextCls->install();
|
||||
|
||||
__jsbObj->defineFunction("garbageCollect", _SE(jsc_garbageCollect));
|
||||
__jsbObj->defineFunction("dumpNativePtrToSeObjectMap", _SE(jsc_dumpNativePtrToSeObjectMap));
|
||||
|
||||
@@ -837,6 +861,8 @@ bool jsb_register_global_variables(se::Object *global) { //NOLINT
|
||||
#endif
|
||||
__jsbObj->defineFunction("setCursorEnabled", _SE(JSB_setCursorEnabled));
|
||||
__jsbObj->defineFunction("saveByteCode", _SE(JSB_saveByteCode));
|
||||
__jsbObj->defineFunction("createExternalArrayBuffer", _SE(jsb_createExternalArrayBuffer));
|
||||
|
||||
global->defineFunction("__getPlatform", _SE(JSBCore_platform));
|
||||
global->defineFunction("__getOS", _SE(JSBCore_os));
|
||||
global->defineFunction("__getOSVersion", _SE(JSB_getOSVersion));
|
||||
|
||||
@@ -210,15 +210,5 @@ bool jsb_enable_debugger(const std::string &debuggerServerAddr, uint32_t port, b
|
||||
|
||||
auto *se = se::ScriptEngine::getInstance();
|
||||
se->enableDebugger(debuggerServerAddr, port, isWaitForConnect);
|
||||
|
||||
// For debugger main loop
|
||||
class SimpleRunLoop {
|
||||
public:
|
||||
void update(float dt) { //NOLINT
|
||||
se::ScriptEngine::getInstance()->mainLoopUpdate();
|
||||
}
|
||||
};
|
||||
// static SimpleRunLoop runLoop;
|
||||
//cjh IDEA: Director::getInstance()->getScheduler()->scheduleUpdate(&runLoop, 0, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -153,6 +153,7 @@ public:
|
||||
* GFX 设备
|
||||
*/
|
||||
inline gfx::Device *getDevice() const { return _device; }
|
||||
inline void setDevice(gfx::Device* device) { _device = device; }
|
||||
|
||||
/**
|
||||
* @zh
|
||||
|
||||
@@ -222,6 +222,7 @@ void Engine::tick() {
|
||||
|
||||
se::ScriptEngine::getInstance()->handlePromiseExceptions();
|
||||
cc::EventDispatcher::dispatchTickEvent(dt);
|
||||
se::ScriptEngine::getInstance()->mainLoopUpdate();
|
||||
|
||||
cc::DeferredReleasePool::clear();
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ set(TARGET_IOS_VERSION "10.0" CACHE STRING "Target iOS version" FORCE)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 14)
|
||||
option(USE_SE_V8 "Use V8 JavaScript Engine" ON)
|
||||
option(USE_SE_SM "Use Spidermonkey JavaScript Engine" OFF)
|
||||
option(USE_V8_DEBUGGER "Enable Chrome Remote inspector" ON)
|
||||
option(USE_SOCKET "Enable WebSocket & SocketIO" ON)
|
||||
option(USE_AUDIO "Enable Audio" ON) #Enable AudioEngine
|
||||
|
||||
Reference in New Issue
Block a user