Merge pull request #803 from dumganhar/jsb2.0

[jsb2.0] SpiderMonkey debugger works. Adds ScriptEngine::enableDebugger, mainLoopUpdate interfaces.
This commit is contained in:
James Chen
2017-09-07 20:41:36 -05:00
committed by GitHub
11 changed files with 484 additions and 70 deletions
@@ -432,6 +432,16 @@ namespace se {
return true;
}
void ScriptEngine::enableDebugger(unsigned int port/* = 5086*/)
{
//FIXME:
}
void ScriptEngine::mainLoopUpdate()
{
//FIXME:
}
} // namespace se {
#endif // SCRIPT_ENGINE_CHAKRACORE
@@ -120,6 +120,8 @@ namespace se {
void setExceptionCallback(const ExceptionCallback& cb);
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
void enableDebugger(unsigned int port = 5086);
void mainLoopUpdate();
void _retainScriptObject(void* owner, void* target);
void _releaseScriptObject(void* owner, void* target);
@@ -504,6 +504,16 @@ namespace se {
//FIXME:
}
void ScriptEngine::enableDebugger(unsigned int port/* = 5086*/)
{
// empty implementation
}
void ScriptEngine::mainLoopUpdate()
{
// empty implementation
}
} // namespace se {
#endif // SCRIPT_ENGINE_JSC
@@ -207,6 +207,17 @@ namespace se {
*/
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
/**
* @brief Enables JavaScript debugger
* @param[in] port The port of debugger server will use.
*/
void enableDebugger(unsigned int port = 5086);
/**
* @brief Main loop update trigger, it's need to invoked in main thread every frame.
*/
void mainLoopUpdate();
// Private API used in wrapper
void _retainScriptObject(void* owner, void* target);
void _releaseScriptObject(void* owner, void* target);
@@ -6,6 +6,27 @@
#include "Class.hpp"
#include "Utils.hpp"
#include "../MappingUtils.hpp"
#include "../State.hpp"
// for debug socket
#ifdef _WIN32
#include <io.h>
#include <WS2tcpip.h>
#else
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#endif
#include <mutex>
#include <thread>
#include <sstream>
#if SE_DEBUG
#define TRACE_DEBUGGER_SERVER(...) LOGD(__VA_ARGS__)
#else
#define TRACE_DEBUGGER_SERVER(...)
#endif // #if COCOS2D_DEBUG
namespace se {
@@ -17,7 +38,7 @@ namespace se {
ScriptEngine* __instance = nullptr;
const JSClassOps sandbox_classOps = {
const JSClassOps __sandboxClassOps = {
nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr,
nullptr, nullptr,
@@ -25,10 +46,10 @@ namespace se {
JS_GlobalObjectTraceHook
};
JSClass globalClass = {
JSClass __globalClass = {
"global",
JSCLASS_GLOBAL_FLAGS,
&sandbox_classOps
&__sandboxClassOps
};
void reportWarning(JSContext* cx, JSErrorReport* report)
@@ -225,6 +246,7 @@ namespace se {
ScriptEngine::ScriptEngine()
: _cx(nullptr)
, _globalObj(nullptr)
, _debugGlobalObj(nullptr)
, _oldCompartment(nullptr)
, _isGarbageCollecting(false)
, _isValid(false)
@@ -344,7 +366,7 @@ namespace se {
.setNativeRegExp(true);
#endif
JSObject* globalObj = JS_NewGlobalObject(_cx, &globalClass, nullptr, JS::DontFireOnNewGlobalHook, options);
JSObject* globalObj = JS_NewGlobalObject(_cx, &__globalClass, nullptr, JS::DontFireOnNewGlobalHook, options);
if (nullptr == globalObj)
return false;
@@ -789,6 +811,346 @@ namespace se {
_exceptionCallback = cb;
}
#pragma mark - Debug
static std::string inData;
static std::string outData;
static std::vector<std::string> g_queue;
static std::mutex g_qMutex;
static std::mutex g_rwMutex;
static int clientSocket = -1;
static uint32_t s_nestedLoopLevel = 0;
static void cc_closesocket(int fd)
{
#ifdef _WIN32
closesocket(fd);
#else
close(fd);
#endif
}
void ScriptEngine::_debugProcessInput(const std::string& str)
{
JS::RootedObject debugGlobal(_cx, _debugGlobalObj->_getJSObject());
JSCompartment *globalCpt = JS_EnterCompartment(_cx, debugGlobal);
Value func;
if (_debugGlobalObj->getProperty("processInput", &func) && func.isObject() && func.toObject()->isFunction())
{
ValueArray args;
args.push_back(Value(str));
func.toObject()->call(args, _debugGlobalObj);
}
JS_LeaveCompartment(_cx, globalCpt);
}
static bool NS_ProcessNextEvent()
{
std::string message;
size_t messageCount = 0;
while (true)
{
g_qMutex.lock();
messageCount = g_queue.size();
if (messageCount > 0)
{
auto first = g_queue.begin();
message = *first;
g_queue.erase(first);
--messageCount;
}
g_qMutex.unlock();
if (!message.empty())
{
ScriptEngine::getInstance()->_debugProcessInput(message);
}
if (messageCount == 0)
break;
}
// std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
return true;
}
static bool JSBDebug_enterNestedEventLoop(State& s)
{
enum {
NS_OK = 0,
NS_ERROR_UNEXPECTED
};
#define NS_SUCCEEDED(v) ((v) == NS_OK)
int rv = NS_OK;
uint32_t nestLevel = ++s_nestedLoopLevel;
while (NS_SUCCEEDED(rv) && s_nestedLoopLevel >= nestLevel) {
drainJobQueue();
if (!NS_ProcessNextEvent())
rv = NS_ERROR_UNEXPECTED;
}
assert(s_nestedLoopLevel <= nestLevel);
s.rval().setInt32(s_nestedLoopLevel);
return true;
}
SE_BIND_FUNC(JSBDebug_enterNestedEventLoop)
static bool JSBDebug_exitNestedEventLoop(State& s)
{
if (s_nestedLoopLevel > 0) {
--s_nestedLoopLevel;
} else {
s.rval().setInt32(0);
return true;
}
return true;
}
SE_BIND_FUNC(JSBDebug_exitNestedEventLoop)
static bool JSBDebug_getEventLoopNestLevel(State& s)
{
s.rval().setInt32(s_nestedLoopLevel);
return true;
}
SE_BIND_FUNC(JSBDebug_getEventLoopNestLevel)
static void _clientSocketWriteAndClearString(std::string& s)
{
::send(clientSocket, s.c_str(), s.length(), 0);
s.clear();
}
static void processInput(const std::string& data) {
std::lock_guard<std::mutex> lk(g_qMutex);
g_queue.push_back(data);
}
static void clearBuffers() {
std::lock_guard<std::mutex> lk(g_rwMutex);
// only process input if there's something and we're not locked
if (!inData.empty()) {
processInput(inData);
inData.clear();
}
if (!outData.empty()) {
_clientSocketWriteAndClearString(outData);
}
}
static void serverEntryPoint(unsigned int port)
{
// start a server, accept the connection and keep reading data from it
struct addrinfo hints, *result = nullptr, *rp = nullptr;
int s = 0;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
std::stringstream portstr;
portstr << port;
int err = 0;
#ifdef _WIN32
WSADATA wsaData;
err = WSAStartup(MAKEWORD(2, 2),&wsaData);
#endif
if ((err = getaddrinfo(NULL, portstr.str().c_str(), &hints, &result)) != 0) {
LOGD("getaddrinfo error : %s\n", gai_strerror(err));
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
if ((s = socket(rp->ai_family, rp->ai_socktype, 0)) < 0) {
continue;
}
int optval = 1;
if ((setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval))) < 0) {
cc_closesocket(s);
TRACE_DEBUGGER_SERVER("debug server : error setting socket option SO_REUSEADDR");
return;
}
#ifdef __APPLE__
if ((setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval))) < 0) {
close(s);
TRACE_DEBUGGER_SERVER("debug server : error setting socket option SO_NOSIGPIPE");
return;
}
#endif
if ((::bind(s, rp->ai_addr, rp->ai_addrlen)) == 0) {
break;
}
cc_closesocket(s);
s = -1;
}
if (s < 0 || rp == NULL) {
TRACE_DEBUGGER_SERVER("debug server : error creating/binding socket");
return;
}
freeaddrinfo(result);
listen(s, 1);
#define MAX_RECEIVED_SIZE 1024
#define BUF_SIZE MAX_RECEIVED_SIZE + 1
char buf[BUF_SIZE] = {0};
int readBytes = 0;
while (true) {
clientSocket = accept(s, NULL, NULL);
if (clientSocket < 0)
{
TRACE_DEBUGGER_SERVER("debug server : error on accept");
return;
}
else
{
// read/write data
TRACE_DEBUGGER_SERVER("debug server : client connected");
inData = "connected";
// process any input, send any output
clearBuffers();
while ((readBytes = (int)::recv(clientSocket, buf, MAX_RECEIVED_SIZE, 0)) > 0)
{
buf[readBytes] = '\0';
// TRACE_DEBUGGER_SERVER("debug server : received command >%s", buf);
// no other thread is using this
inData.append(buf);
// process any input, send any output
clearBuffers();
} // while(read)
cc_closesocket(clientSocket);
}
} // while(true)
#undef BUF_SIZE
#undef MAX_RECEIVED_SIZE
}
static bool JSBDebug_require(State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc >= 1)
{
ScriptEngine::getInstance()->runScript(args[0].toString());
return true;
}
SE_REPORT_ERROR("Wrong number of arguments: %d, expected: %d", argc, 1);
return false;
}
SE_BIND_FUNC(JSBDebug_require)
static bool JSBDebug_BufferWrite(State& s)
{
const auto& args = s.args();
int argc = (int)args.size();
if (argc == 1)
{
// this is safe because we're already inside a lock (from clearBuffers)
outData.append(args[0].toString());
_clientSocketWriteAndClearString(outData);
}
return true;
}
SE_BIND_FUNC(JSBDebug_BufferWrite)
void ScriptEngine::enableDebugger(unsigned int port)
{
if (_debugGlobalObj != nullptr)
{
LOGD("Debugger was enabled!");
return;
}
JS::CompartmentOptions options;
options.behaviors().setVersion(JSVERSION_LATEST);
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);
//cjh registerDefaultClasses(_cx, debugGlobal);
JS_FireOnNewGlobalObject(_cx, debugGlobal);
JS_DefineDebuggerObject(_cx, debugGlobal);
// these are used in the debug program
JS_DefineFunction(_cx, debugGlobal, "log", __log, 0, JSPROP_PERMANENT);
_debugGlobalObj->defineFunction("require", _SE(JSBDebug_require));
_debugGlobalObj->defineFunction("_bufferWrite", _SE(JSBDebug_BufferWrite));
_debugGlobalObj->defineFunction("_enterNestedEventLoop", _SE(JSBDebug_enterNestedEventLoop));
_debugGlobalObj->defineFunction("_exitNestedEventLoop", _SE(JSBDebug_exitNestedEventLoop));
_debugGlobalObj->defineFunction("_getEventLoopNestLevel", _SE(JSBDebug_getEventLoopNestLevel));
JS::RootedObject globalObj(_cx, _globalObj->_getJSObject());
JS_WrapObject(_cx, &globalObj);
runScript("script/jsb_debugger.js");
// prepare the debugger
Value prepareDebuggerFunc;
assert(_debugGlobalObj->getProperty("_prepareDebugger", &prepareDebuggerFunc) && prepareDebuggerFunc.isObject() && prepareDebuggerFunc.toObject()->isFunction());
ValueArray args;
args.push_back(Value(_globalObj));
prepareDebuggerFunc.toObject()->call(args, _debugGlobalObj);
// start bg thread
auto t = std::thread(&serverEntryPoint, port);
t.detach();
JS_LeaveCompartment(_cx, globalCpt);
}
void ScriptEngine::mainLoopUpdate()
{
std::string message;
size_t messageCount = 0;
while (true)
{
g_qMutex.lock();
messageCount = g_queue.size();
if (messageCount > 0)
{
auto first = g_queue.begin();
message = *first;
g_queue.erase(first);
--messageCount;
}
g_qMutex.unlock();
if (!message.empty())
{
_debugProcessInput(message);
}
if (messageCount == 0)
break;
}
}
} // namespace se {
#endif // SCRIPT_ENGINE_SM
@@ -106,6 +106,9 @@ namespace se {
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
void enableDebugger(unsigned int port = 5086);
void mainLoopUpdate();
void _retainScriptObject(void* owner, void* target);
void _releaseScriptObject(void* owner, void* target);
@@ -122,6 +125,8 @@ namespace se {
using NodeEventListener = bool(*)(void*, NodeEventType);
bool _setNodeEventListener(NodeEventListener listener);
void _debugProcessInput(const std::string& str);
private:
static void onWeakPointerCompartmentCallback(JSContext* cx, JSCompartment* comp, void* data);
static void onWeakPointerZoneGroupCallback(JSContext* cx, void* data);
@@ -133,6 +138,7 @@ namespace se {
JSCompartment* _oldCompartment;
Object* _globalObj;
Object* _debugGlobalObj;
bool _isGarbageCollecting;
bool _isValid;
@@ -285,21 +285,6 @@ namespace se {
__jsb_CCPrivateData_class->setCreateProto(false);
__jsb_CCPrivateData_class->install();
#if SE_ENABLE_INSPECTOR
// V8 inspector stuff, most code are taken from NodeJS.
_isolateData = node::CreateIsolateData(_isolate, uv_default_loop());
_env = node::CreateEnvironment(_isolateData, _context.Get(_isolate), 0, nullptr, 0, nullptr);
node::DebugOptions options;
options.set_wait_for_connect(true);
options.set_inspector_enabled(true);
// options.set_host_name("192.168.2.4"); // Change IP while remote debugging on Android device.
_env->inspector_agent()->Start(_platform, "", options);
//
#endif
_isValid = true;
for (const auto& hook : _afterInitHookArray)
@@ -582,6 +567,31 @@ namespace se {
return _context.Get(_isolate);
}
void ScriptEngine::enableDebugger(unsigned int port/* = 5086*/)
{
#if SE_ENABLE_INSPECTOR
AutoHandleScope hs;
// V8 inspector stuff, most code are taken from NodeJS.
_isolateData = node::CreateIsolateData(_isolate, uv_default_loop());
_env = node::CreateEnvironment(_isolateData, _context.Get(_isolate), 0, nullptr, 0, nullptr);
node::DebugOptions options;
options.set_wait_for_connect(true);
options.set_inspector_enabled(true);
options.set_port((int)port);
// options.set_host_name("192.168.2.4"); // Change IP while remote debugging on Android device.
_env->inspector_agent()->Start(_platform, "", options);
//
#endif
}
void ScriptEngine::mainLoopUpdate()
{
// empty implementation
}
} // namespace se {
#endif // SCRIPT_ENGINE_V8
@@ -140,6 +140,9 @@ namespace se {
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
void enableDebugger(unsigned int port = 5086);
void mainLoopUpdate();
void _retainScriptObject(void* owner, void* target);
void _releaseScriptObject(void* owner, void* target);
@@ -1,22 +1,6 @@
#include "AppDelegate.h"
#include "platform/CCGLView.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "platform/ios/CCGLViewImpl-ios.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCGLViewImpl-android.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "platform/desktop/CCGLViewImpl-desktop.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "platform/desktop/CCGLViewImpl-desktop.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC
#include "base/CCDirector.h"
#include "base/CCEventDispatcher.h"
#include "cocos2d.h"
#include "cocos/scripting/js-bindings/manual/ScriptingCore.h"
#include "cocos/scripting/js-bindings/manual/jsb_module_register.hpp"
@@ -85,6 +69,22 @@ bool AppDelegate::applicationDidFinishLaunching()
se->start();
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
se->enableDebugger(); // Enable debugger here
class SimpleRunLoop
{
public:
void update(float dt)
{
se::ScriptEngine::getInstance()->update();
}
};
static SimpleRunLoop runLoop;
director->getScheduler()->scheduleUpdate(&runLoop, 0, false);
#endif
jsb_run_script("main.js");
return true;
@@ -1,22 +1,6 @@
#include "AppDelegate.h"
#include "platform/CCGLView.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "platform/ios/CCGLViewImpl-ios.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCGLViewImpl-android.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "platform/desktop/CCGLViewImpl-desktop.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "platform/desktop/CCGLViewImpl-desktop.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC
#include "base/CCDirector.h"
#include "base/CCEventDispatcher.h"
#include "cocos2d.h"
#include "cocos/scripting/js-bindings/manual/ScriptingCore.h"
#include "cocos/scripting/js-bindings/manual/jsb_module_register.hpp"
@@ -85,6 +69,22 @@ bool AppDelegate::applicationDidFinishLaunching()
se->start();
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
se->enableDebugger(); // Enable debugger here
class SimpleRunLoop
{
public:
void update(float dt)
{
se::ScriptEngine::getInstance()->mainLoopUpdate();
}
};
static SimpleRunLoop runLoop;
director->getScheduler()->scheduleUpdate(&runLoop, 0, false);
#endif
jsb_run_script("main.js");
return true;
@@ -1,22 +1,6 @@
#include "AppDelegate.h"
#include "platform/CCGLView.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "platform/ios/CCGLViewImpl-ios.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCGLViewImpl-android.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "platform/desktop/CCGLViewImpl-desktop.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "platform/desktop/CCGLViewImpl-desktop.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC
#include "base/CCDirector.h"
#include "base/CCEventDispatcher.h"
#include "cocos2d.h"
#include "cocos/scripting/js-bindings/manual/ScriptingCore.h"
#include "cocos/scripting/js-bindings/manual/jsb_module_register.hpp"
@@ -85,6 +69,22 @@ bool AppDelegate::applicationDidFinishLaunching()
se->start();
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
se->enableDebugger(); // Enable debugger here
class SimpleRunLoop
{
public:
void update(float dt)
{
se::ScriptEngine::getInstance()->mainLoopUpdate();
}
};
static SimpleRunLoop runLoop;
director->getScheduler()->scheduleUpdate(&runLoop, 0, false);
#endif
jsb_run_script("main.js");
return true;