From c3602eb1e3d89e94ec53ec0eae69adc4fe7f398a Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 15 Mar 2018 18:12:38 +0800 Subject: [PATCH 01/13] [runtime] Android testcase works. (#1148) * Adds jsb_run_script_module for CommonJS module, reverts original `require`. * Uses window.gameTick for sending tick event. * Removes unused scripts. * Android testcase works. --- .../CCCanvasRenderingContext2D-android.cpp | 12 +- native/cocos/platform/android/jni/JniImp.cpp | 76 +- native/cocos/platform/ios/CCEAGLView-ios.mm | 2 - .../js-bindings/event/EventDispatcher.cpp | 3 +- .../js-bindings/manual/jsb_global.cpp | 33 +- .../scripting/js-bindings/manual/jsb_global.h | 1 + .../script/debugger/DevToolsUtils.js | 834 ------ .../js-bindings/script/debugger/README.md | 54 - .../script/debugger/actors/breakpoint.js | 200 -- .../script/debugger/actors/common.js | 512 ---- .../script/debugger/actors/environment.js | 221 -- .../script/debugger/actors/frame.js | 109 - .../script/debugger/actors/object.js | 2250 ---------------- .../script/debugger/actors/root.js | 536 ---- .../script/debugger/actors/script.js | 2372 ----------------- .../script/debugger/actors/source.js | 937 ------- .../debugger/actors/utils/ScriptStore.js | 219 -- .../debugger/actors/utils/TabSources.js | 847 ------ .../script/debugger/actors/webconsole.js | 2313 ---------------- .../script/debugger/event-emitter.js | 218 -- .../js-bindings/script/debugger/main.js | 1797 ------------- .../js-bindings/script/debugger/protocol.js | 1517 ----------- .../script/debugger/sdk/event-core.js | 187 -- .../script/debugger/sdk/heritage.js | 204 -- .../js-bindings/script/debugger/sdk/object.js | 136 - .../js-bindings/script/debugger/sdk/target.js | 60 - .../js-bindings/script/debugger/transport.js | 921 ------- .../script/debugger/webconsole/utils.js | 1063 -------- .../script/extension/jsb_cocos2d_extension.js | 218 -- .../cocos/scripting/js-bindings/script/jsb.js | 56 - .../js-bindings/script/jsb_audioengine.js | 38 - .../scripting/js-bindings/script/jsb_boot.js | 793 ------ .../js-bindings/script/jsb_cocos2d.js | 1146 -------- .../js-bindings/script/jsb_cocosanalytics.js | 734 ----- .../js-bindings/script/jsb_common.js | 334 --- .../js-bindings/script/jsb_create_apis.js | 516 ---- .../js-bindings/script/jsb_debugger.js | 294 -- .../js-bindings/script/jsb_dragonbones.js | 57 - .../js-bindings/script/jsb_opengl.js | 389 --- .../script/jsb_opengl_constants.js | 863 ------ .../js-bindings/script/jsb_prepare.js | 278 -- .../js-bindings/script/jsb_property_apis.js | 278 -- .../js-bindings/script/jsb_property_impls.js | 215 -- .../scripting/js-bindings/script/jsb_spine.js | 82 - 44 files changed, 77 insertions(+), 23848 deletions(-) delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/README.md delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/actors/common.js delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/actors/environment.js delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/actors/frame.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/actors/object.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/actors/root.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/actors/script.js delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/actors/source.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/actors/utils/ScriptStore.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/actors/webconsole.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/event-emitter.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/main.js delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/protocol.js delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/sdk/event-core.js delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/sdk/heritage.js delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/sdk/object.js delete mode 100644 native/cocos/scripting/js-bindings/script/debugger/sdk/target.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/transport.js delete mode 100755 native/cocos/scripting/js-bindings/script/debugger/webconsole/utils.js delete mode 100644 native/cocos/scripting/js-bindings/script/extension/jsb_cocos2d_extension.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_audioengine.js delete mode 100755 native/cocos/scripting/js-bindings/script/jsb_boot.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_cocos2d.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_cocosanalytics.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_common.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_create_apis.js delete mode 100755 native/cocos/scripting/js-bindings/script/jsb_debugger.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_dragonbones.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_opengl.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_opengl_constants.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_prepare.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_property_apis.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_property_impls.js delete mode 100644 native/cocos/scripting/js-bindings/script/jsb_spine.js diff --git a/native/cocos/platform/android/CCCanvasRenderingContext2D-android.cpp b/native/cocos/platform/android/CCCanvasRenderingContext2D-android.cpp index a3e0a07ae6..4956ae1d98 100644 --- a/native/cocos/platform/android/CCCanvasRenderingContext2D-android.cpp +++ b/native/cocos/platform/android/CCCanvasRenderingContext2D-android.cpp @@ -27,8 +27,8 @@ public: CanvasRenderingContext2DImpl() { - _obj = JniHelper::newObject("org/cocos2dx/lib/CanvasRenderingContext2DImpl"); - JniHelper::getEnv()->NewGlobalRef(_obj); + jobject obj = JniHelper::newObject("org/cocos2dx/lib/CanvasRenderingContext2DImpl"); + _obj = JniHelper::getEnv()->NewGlobalRef(obj); } ~CanvasRenderingContext2DImpl() @@ -38,6 +38,8 @@ public: void recreateBuffer(float w, float h) { + if (w < 1.0f || h < 1.0f) + return; JniHelper::callObjectVoidMethod(_obj, _className, "recreateBuffer", w, h); } @@ -55,18 +57,24 @@ public: void fillText(const std::string& text, float x, float y, float maxWidth) { + if (text.empty()) + return; JniHelper::callObjectVoidMethod(_obj, _className, "fillText", text, x, y, maxWidth); fillData(); } void strokeText(const std::string& text, float x, float y, float maxWidth) { + if (text.empty()) + return; JniHelper::callObjectVoidMethod(_obj, _className, "strokeText", text, x, y, maxWidth); fillData(); } float measureText(const std::string& text) { + if (text.empty()) + return 0.0f; return JniHelper::callObjectFloatMethod(_obj, _className, "measureText", text); } diff --git a/native/cocos/platform/android/jni/JniImp.cpp b/native/cocos/platform/android/jni/JniImp.cpp index ea7b5ea369..ed492c2fbf 100644 --- a/native/cocos/platform/android/jni/JniImp.cpp +++ b/native/cocos/platform/android/jni/JniImp.cpp @@ -195,52 +195,64 @@ extern "C" * Touches native functions implementation. ***********************************************************/ + static void dispatchTouchEventWithOnePoint(JNIEnv* env, cocos2d::TouchEvent::Type type, jint id, jfloat x, jfloat y) + { + cocos2d::TouchEvent touchEvent; + touchEvent.type = type; + + cocos2d::TouchInfo touchInfo; + touchInfo.index = id; + touchInfo.x = x; + touchInfo.y = y; + touchEvent.touches.push_back(touchInfo); + + cocos2d::EventDispatcher::dispatchTouchEvent(touchEvent); + } + + static void dispatchTouchEventWithPoints(JNIEnv* env, cocos2d::TouchEvent::Type type, jintArray ids, jfloatArray xs, jfloatArray ys) + { + cocos2d::TouchEvent touchEvent; + touchEvent.type = type; + + int size = env->GetArrayLength(ids); + jint id[size]; + jfloat x[size]; + jfloat y[size]; + + env->GetIntArrayRegion(ids, 0, size, id); + env->GetFloatArrayRegion(xs, 0, size, x); + env->GetFloatArrayRegion(ys, 0, size, y); + + for(int i = 0; i < size; i++) + { + cocos2d::TouchInfo touchInfo; + touchInfo.index = id[i]; + touchInfo.x = x[i]; + touchInfo.y = y[i]; + touchEvent.touches.push_back(touchInfo); + } + + cocos2d::EventDispatcher::dispatchTouchEvent(touchEvent); + } + JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) { - //TODO + dispatchTouchEventWithOnePoint(env, cocos2d::TouchEvent::Type::BEGAN, id, x, y); } JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) { - //TODO + dispatchTouchEventWithOnePoint(env, cocos2d::TouchEvent::Type::ENDED, id, x, y); } JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) { - int size = env->GetArrayLength(ids); - jint id[size]; - jfloat x[size]; - jfloat y[size]; - - env->GetIntArrayRegion(ids, 0, size, id); - env->GetFloatArrayRegion(xs, 0, size, x); - env->GetFloatArrayRegion(ys, 0, size, y); - - intptr_t idlong[size]; - for(int i = 0; i < size; i++) - idlong[i] = id[i]; - - //TODO - // cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(size, idlong, x, y); + dispatchTouchEventWithPoints(env, cocos2d::TouchEvent::Type::MOVED, ids, xs, ys); } JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) { - int size = env->GetArrayLength(ids); - jint id[size]; - jfloat x[size]; - jfloat y[size]; - - env->GetIntArrayRegion(ids, 0, size, id); - env->GetFloatArrayRegion(xs, 0, size, x); - env->GetFloatArrayRegion(ys, 0, size, y); - - intptr_t idlong[size]; - for(int i = 0; i < size; i++) - idlong[i] = id[i]; - - //TODO - // cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(size, idlong, x, y); + dispatchTouchEventWithPoints(env, cocos2d::TouchEvent::Type::CANCELLED, ids, xs, ys); } JNIEXPORT jboolean JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeKeyEvent(JNIEnv * env, jobject thiz, jint keyCode, jboolean isPressed) diff --git a/native/cocos/platform/ios/CCEAGLView-ios.mm b/native/cocos/platform/ios/CCEAGLView-ios.mm index 6ac06b6fa7..a67eb208b0 100644 --- a/native/cocos/platform/ios/CCEAGLView-ios.mm +++ b/native/cocos/platform/ios/CCEAGLView-ios.mm @@ -516,8 +516,6 @@ namespace } } - - - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (_isKeyboardShown) diff --git a/native/cocos/scripting/js-bindings/event/EventDispatcher.cpp b/native/cocos/scripting/js-bindings/event/EventDispatcher.cpp index 7caf2bb716..1ac1be9e3a 100644 --- a/native/cocos/scripting/js-bindings/event/EventDispatcher.cpp +++ b/native/cocos/scripting/js-bindings/event/EventDispatcher.cpp @@ -70,6 +70,7 @@ namespace cocos2d void EventDispatcher::dispatchTouchEvent(const struct TouchEvent& touchEvent) { + se::AutoHandleScope scope; assert(_inited); if (_jsbNameSpaceObj == nullptr) { @@ -152,7 +153,7 @@ void EventDispatcher::dispatchTickEvent(float dt) if (_tickVal.isUndefined()) { - jsb_run_script("jsb/index.js", &_tickVal); + se::ScriptEngine::getInstance()->getGlobalObject()->getProperty("gameTick", &_tickVal); } prevTime = std::chrono::steady_clock::now(); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_global.cpp b/native/cocos/scripting/js-bindings/manual/jsb_global.cpp index 8f3c928d5d..e1a2baf02e 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_global.cpp +++ b/native/cocos/scripting/js-bindings/manual/jsb_global.cpp @@ -197,16 +197,16 @@ namespace { std::unordered_map __moduleCache; -// static bool require(se::State& s) -// { -// const auto& args = s.args(); -// int argc = (int)args.size(); -// assert(argc >= 1); -// assert(args[0].isString()); -// -// return jsb_run_script(args[0].toString(), &s.rval()); -// } -// SE_BIND_FUNC(require) + static bool require(se::State& s) + { + const auto& args = s.args(); + int argc = (int)args.size(); + assert(argc >= 1); + assert(args[0].isString()); + + return jsb_run_script(args[0].toString(), &s.rval()); + } + SE_BIND_FUNC(require) static bool doModuleRequire(const std::string& path, se::Value* ret, const std::string& prevScriptFileDir) { @@ -269,7 +269,7 @@ namespace { snprintf(suffix, sizeof(suffix), "\nwindow.module.exports = window.module.exports || exports;\n})('%s'); ", currentScriptFileDir.c_str()); // Add current script path to require function invocation - scriptBuffer = prefix + std::regex_replace(scriptBuffer, std::regex("([^A-Za-z0-9]|^)require\\((.*?)\\)"), "$1require($2, currentScriptDir)") + suffix; + scriptBuffer = prefix + std::regex_replace(scriptBuffer, std::regex("([^A-Za-z0-9]|^)requireModule\\((.*?)\\)"), "$1requireModule($2, currentScriptDir)") + suffix; // FILE* fp = fopen("/Users/james/Downloads/test.txt", "wb"); // fwrite(scriptBuffer.c_str(), scriptBuffer.length(), 1, fp); @@ -296,7 +296,7 @@ namespace { auto se = se::ScriptEngine::getInstance(); bool succeed = se->evalString(scriptBuffer.c_str(), scriptBuffer.length(), nullptr, reletivePath.c_str()); se::Value moduleVal; - if (se->getGlobalObject()->getProperty("module", &moduleVal) && moduleVal.isObject()) + if (succeed && se->getGlobalObject()->getProperty("module", &moduleVal) && moduleVal.isObject()) { se::Value exportsVal; if (moduleVal.toObject()->getProperty("exports", &exportsVal)) @@ -743,6 +743,12 @@ namespace { } bool jsb_run_script(const std::string& filePath, se::Value* rval/* = nullptr */) +{ + se::AutoHandleScope hs; + return se::ScriptEngine::getInstance()->runScript(filePath, rval); +} + +bool jsb_run_script_module(const std::string& filePath, se::Value* rval/* = nullptr */) { return doModuleRequire(filePath, rval, ""); } @@ -953,7 +959,8 @@ SE_BIND_FUNC(js_performance_now) bool jsb_register_global_variables(se::Object* global) { - global->defineFunction("require", _SE(moduleRequire)); + global->defineFunction("require", _SE(require)); + global->defineFunction("requireModule", _SE(moduleRequire)); getOrCreatePlainObject_r("cc", global, &__ccObj); diff --git a/native/cocos/scripting/js-bindings/manual/jsb_global.h b/native/cocos/scripting/js-bindings/manual/jsb_global.h index e6d01cafac..0d022cc1fa 100644 --- a/native/cocos/scripting/js-bindings/manual/jsb_global.h +++ b/native/cocos/scripting/js-bindings/manual/jsb_global.h @@ -18,5 +18,6 @@ void jsb_init_file_operation_delegate(); bool jsb_enable_debugger(const std::string& debuggerServerAddr, uint32_t port); bool jsb_set_extend_property(const char* ns, const char* clsName); bool jsb_run_script(const std::string& filePath, se::Value* rval = nullptr); +bool jsb_run_script_module(const std::string& filePath, se::Value* rval = nullptr); void jsb_set_xxtea_key(const std::string& key); diff --git a/native/cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js b/native/cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js deleted file mode 100755 index d69f27187d..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/DevToolsUtils.js +++ /dev/null @@ -1,834 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -/* General utilities used throughout devtools. */ - -// var { Ci, Cu, Cc, components } = require("chrome"); -// var Services = require("Services"); -// var promise = require("promise"); - -// loader.lazyRequireGetter(this, "FileUtils", -// "resource://gre/modules/FileUtils.jsm", true); - -function DevToolsUtils() { - -} - -DevToolsUtils.utf16to8 = function utf16to8(str) { - var out, i, len, c; - - out = ""; - len = str.length; - for(i = 0; i < len; i++) - { - c = str.charCodeAt(i); - if ((c >= 0x0001) && (c <= 0x007F)) - { - out += str.charAt(i); - } - else if (c > 0x07FF) - { - out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); - out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); - out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); - } - else - { - out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); - out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); - } - } - return out; -} - -DevToolsUtils.utf8to16 = function utf8to16(str) { - var out, i, len, c; - var char2, char3; - - out = ""; - len = str.length; - i = 0; - while(i < len) { c = str.charCodeAt(i++); switch(c >> 4) - { - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - // 0xxxxxxx - out += str.charAt(i-1); - break; - case 12: case 13: - // 110x xxxx 10xx xxxx - char2 = str.charCodeAt(i++); - out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); - break; - case 14: - // 1110 xxxx 10xx xxxx 10xx xxxx - char2 = str.charCodeAt(i++); - char3 = str.charCodeAt(i++); - out += String.fromCharCode(((c & 0x0F) << 12) | - ((char2 & 0x3F) << 6) | - ((char3 & 0x3F) << 0)); - break; - } - } - - return out; - } - -/** - * Turn the error |aError| into a string, without fail. - */ -DevToolsUtils.safeErrorString = function safeErrorString(aError) { - try { - let errorString = aError.toString(); - if (typeof errorString == "string") { - // Attempt to attach a stack to |errorString|. If it throws an error, or - // isn't a string, don't use it. - try { - if (aError.stack) { - let stack = aError.stack.toString(); - if (typeof stack == "string") { - errorString += "\nStack: " + stack; - } - } - } catch (ee) { } - - // Append additional line and column number information to the output, - // since it might not be part of the stringified error. - if (typeof aError.lineNumber == "number" && typeof aError.columnNumber == "number") { - errorString += "Line: " + aError.lineNumber + ", column: " + aError.columnNumber; - } - - return errorString; - } - } catch (ee) { } - - // We failed to find a good error description, so do the next best thing. - return Object.prototype.toString.call(aError); -} - -/** - * Report that |aWho| threw an exception, |aException|. - */ -DevToolsUtils.reportException = function reportException(aWho, aException) { - let msg = "" + aWho + " threw an exception: " + DevToolsUtils.safeErrorString(aException); - - log(msg + "\n"); - - // if (Cu && Cu.reportError) { - - // * Note that the xpcshell test harness registers an observer for - // * console messages, so when we're running tests, this will cause - // * the test to quit. - - // Cu.reportError(msg); - // } -} - -/** - * Given a handler function that may throw, return an infallible handler - * function that calls the fallible handler, and logs any exceptions it - * throws. - * - * @param aHandler function - * A handler function, which may throw. - * @param aName string - * A name for aHandler, for use in error messages. If omitted, we use - * aHandler.name. - * - * (SpiderMonkey does generate good names for anonymous functions, but we - * don't have a way to get at them from JavaScript at the moment.) - */ -DevToolsUtils.makeInfallible = function makeInfallible(aHandler, aName) { - if (!aName) - aName = aHandler.name; - - return function (/* arguments */) { - try { - return aHandler.apply(this, arguments); - } catch (ex) { - let who = "Handler function"; - if (aName) { - who += " " + aName; - } - return DevToolsUtils.reportException(who, ex); - } - } -} -/** - * Interleaves two arrays element by element, returning the combined array, like - * a zip. In the case of arrays with different sizes, undefined values will be - * interleaved at the end along with the extra values of the larger array. - * - * @param Array a - * @param Array b - * @returns Array - * The combined array, in the form [a1, b1, a2, b2, ...] - */ -DevToolsUtils.zip = function zip(a, b) { - if (!b) { - return a; - } - if (!a) { - return b; - } - const pairs = []; - for (let i = 0, aLength = a.length, bLength = b.length; - i < aLength || i < bLength; - i++) { - pairs.push([a[i], b[i]]); - } - return pairs; -}; - - -/** - * Converts an object into an array with 2-element arrays as key/value - * pairs of the object. `{ foo: 1, bar: 2}` would become - * `[[foo, 1], [bar 2]]` (order not guaranteed); - * - * @param object obj - * @returns array - */ -DevToolsUtils.entries = function entries(obj) { - return Object.keys(obj).map(k => [k, obj[k]]); -} - -/** - * Composes the given functions into a single function, which will - * apply the results of each function right-to-left, starting with - * applying the given arguments to the right-most function. - * `compose(foo, bar, baz)` === `args => foo(bar(baz(args)` - * - * @param ...function funcs - * @returns function - */ -DevToolsUtils.compose = function compose(...funcs) { - return (...args) => { - const initialValue = funcs[funcs.length - 1].apply(null, args); - const leftFuncs = funcs.slice(0, -1); - return leftFuncs.reduceRight((composed, f) => f(composed), - initialValue); - }; -} - - -/** - * Waits for the next tick in the event loop to execute a callback. - */ -DevToolsUtils.executeSoon = function executeSoon(aFn) { - if (isWorker) { - setImmediate(aFn); - } else { - let executor; - // Only enable async stack reporting when DEBUG_JS_MODULES is set - // (customized local builds) to avoid a performance penalty. - if (AppConstants.DEBUG_JS_MODULES || flags.testing) { - let stack = getStack(); - executor = () => { - callFunctionWithAsyncStack(aFn, stack, "DevToolsUtils.executeSoon"); - }; - } else { - executor = aFn; - } - Services.tm.mainThread.dispatch({ - run: DevToolsUtils.makeInfallible(executor) - }, Ci.nsIThread.DISPATCH_NORMAL); - } -}; - -/** - * Waits for the next tick in the event loop. - * - * @return Promise - * A promise that is resolved after the next tick in the event loop. - */ -DevToolsUtils.waitForTick = function waitForTick() { - let deferred = Promise.defer(); - DevToolsUtils.executeSoon(deferred.resolve); - return deferred.promise; -}; - -/** - * Waits for the specified amount of time to pass. - * - * @param number aDelay - * The amount of time to wait, in milliseconds. - * @return Promise - * A promise that is resolved after the specified amount of time passes. - */ -DevToolsUtils.waitForTime = function waitForTime(aDelay) { - let deferred = Promise.defer(); - require("Timer").setTimeout(deferred.resolve, aDelay); - return deferred.promise; -}; - -/** - * Like Array.prototype.forEach, but doesn't cause jankiness when iterating over - * very large arrays by yielding to the browser and continuing execution on the - * next tick. - * - * @param Array aArray - * The array being iterated over. - * @param Function aFn - * The function called on each item in the array. If a promise is - * returned by this function, iterating over the array will be paused - * until the respective promise is resolved. - * @returns Promise - * A promise that is resolved once the whole array has been iterated - * over, and all promises returned by the aFn callback are resolved. - */ -DevToolsUtils.yieldingEach = function yieldingEach(aArray, aFn) { - const deferred = Promise.defer(); - - let i = 0; - let len = aArray.length; - let outstanding = [deferred.promise]; - - (function loop() { - const start = Date.now(); - - while (i < len) { - // Don't block the main thread for longer than 16 ms at a time. To - // maintain 60fps, you have to render every frame in at least 16ms; we - // aren't including time spent in non-JS here, but this is Good - // Enough(tm). - if (Date.now() - start > 16) { - DevToolsUtils.executeSoon(loop); - return; - } - - try { - outstanding.push(aFn(aArray[i], i++)); - } catch (e) { - deferred.reject(e); - return; - } - } - - deferred.resolve(); - }()); - - return Promise.all(outstanding); -} - -/** - * Like XPCOMUtils.defineLazyGetter, but with a |this| sensitive getter that - * allows the lazy getter to be defined on a prototype and work correctly with - * instances. - * - * @param Object aObject - * The prototype object to define the lazy getter on. - * @param String aKey - * The key to define the lazy getter on. - * @param Function aCallback - * The callback that will be called to determine the value. Will be - * called with the |this| value of the current instance. - */ -DevToolsUtils.defineLazyPrototypeGetter = -function defineLazyPrototypeGetter(aObject, aKey, aCallback) { - Object.defineProperty(aObject, aKey, { - configurable: true, - get: function() { - const value = aCallback.call(this); - - Object.defineProperty(this, aKey, { - configurable: true, - writable: true, - value: value - }); - - return value; - } - }); -} - -/** - * Safely get the property value from a Debugger.Object for a given key. Walks - * the prototype chain until the property is found. - * - * @param Debugger.Object aObject - * The Debugger.Object to get the value from. - * @param String aKey - * The key to look for. - * @return Any - */ -DevToolsUtils.getProperty = function getProperty(aObj, aKey) { - let root = aObj; - try { - do { - const desc = aObj.getOwnPropertyDescriptor(aKey); - if (desc) { - if ("value" in desc) { - return desc.value; - } - // Call the getter if it's safe. - return DevToolsUtils.hasSafeGetter(desc) ? desc.get.call(root).return : undefined; - } - aObj = aObj.proto; - } while (aObj); - } catch (e) { - // If anything goes wrong report the error and return undefined. - DevToolsUtils.reportException("getProperty", e); - } - return undefined; -}; - -/** - * Determines if a descriptor has a getter which doesn't call into JavaScript. - * - * @param Object aDesc - * The descriptor to check for a safe getter. - * @return Boolean - * Whether a safe getter was found. - */ -DevToolsUtils.hasSafeGetter = function hasSafeGetter(aDesc) { - // Scripted functions that are CCWs will not appear scripted until after - // unwrapping. - try { - // let fn = aDesc.get.unwrap(); - let fn = aDesc.get; - return fn && fn.callable && fn.class == "Function" && fn.script === undefined; - } catch (e) { - // Avoid exception 'Object in compartment marked as invisible to Debugger' - return false; - } -}; - -/** - * Check if it is safe to read properties and execute methods from the given JS - * object. Safety is defined as being protected from unintended code execution - * from content scripts (or cross-compartment code). - * - * See bugs 945920 and 946752 for discussion. - * - * @type Object aObj - * The object to check. - * @return Boolean - * True if it is safe to read properties from aObj, or false otherwise. - */ -DevToolsUtils.isSafeJSObject = function isSafeJSObject(aObj) { - return true; - // If we are running on a worker thread, Cu is not available. In this case, - // we always return false, just to be on the safe side. - // if (isWorker) { - // return false; - // } - - // if (Cu.getGlobalForObject(aObj) == - // Cu.getGlobalForObject(DevToolsUtils.isSafeJSObject)) { - // return true; // aObj is not a cross-compartment wrapper. - // } - - // let principal = Cu.getObjectPrincipal(aObj); - // if (Services.scriptSecurityManager.isSystemPrincipal(principal)) { - // return true; // allow chrome objects - // } - - // return Cu.isXrayWrapper(aObj); -}; - -DevToolsUtils.dumpn = function dumpn(str) { - if (DevToolsUtils.dumpn.wantLogging) { - dump("DBG-SERVER: " + str + "\n"); - } -} - -// We want wantLogging to be writable. The DevToolsUtils object is frozen by the -// loader, so define it on dumpn instead. -DevToolsUtils.dumpn.wantLogging = false; - -/** - * A verbose logger for low-level tracing. - */ -DevToolsUtils.dumpv = function(msg) { - if (DevToolsUtils.dumpv.wantVerbose) { - DevToolsUtils.dumpn(msg); - } -}; - -// We want wantLogging to be writable. The DevToolsUtils object is frozen by the -// loader, so define it on dumpn instead. -DevToolsUtils.dumpv.wantVerbose = false; - -DevToolsUtils.assert = function assert(cond, e) { - if (!cond) { - return e; - } -}; - - -/** - * Utility function for updating an object with the properties of - * other objects. - * - * @param aTarget Object - * The object being updated. - * @param aNewAttrs Object - * The rest params are objects to update aTarget with. You - * can pass as many as you like. - */ -DevToolsUtils.update = function update(aTarget, ...aArgs) { - for (let attrs of aArgs) { - for (let key in attrs) { - let desc = Object.getOwnPropertyDescriptor(attrs, key); - - if (desc) { - Object.defineProperty(aTarget, key, desc); - } - } - } - - return aTarget; -} - -/** - * Utility function for getting the values from an object as an array - * - * @param aObject Object - * The object to iterate over - */ -DevToolsUtils.values = function values(aObject) { - return Object.keys(aObject).map(k => aObject[k]); -} - -/** - * Defines a getter on a specified object that will be created upon first use. - * - * @param aObject - * The object to define the lazy getter on. - * @param aName - * The name of the getter to define on aObject. - * @param aLambda - * A function that returns what the getter should return. This will - * only ever be called once. - */ -DevToolsUtils.defineLazyGetter = function defineLazyGetter(aObject, aName, aLambda) { - Object.defineProperty(aObject, aName, { - get: function () { - delete aObject[aName]; - return aObject[aName] = aLambda.apply(aObject); - }, - configurable: true, - enumerable: true - }); -}; - -/** - * Defines a getter on a specified object for a module. The module will not - * be imported until first use. - * - * @param aObject - * The object to define the lazy getter on. - * @param aName - * The name of the getter to define on aObject for the module. - * @param aResource - * The URL used to obtain the module. - * @param aSymbol - * The name of the symbol exported by the module. - * This parameter is optional and defaults to aName. - */ -DevToolsUtils.defineLazyModuleGetter = function defineLazyModuleGetter(aObject, aName, - aResource, - aSymbol) -{ - this.defineLazyGetter(aObject, aName, function XPCU_moduleLambda() { - var temp = {}; - Cu.import(aResource, temp); - return temp[aSymbol || aName]; - }); -}; - -DevToolsUtils.defineLazyGetter(this, "NetUtil", () => { - return Cu.import("resource://gre/modules/NetUtil.jsm", {}).NetUtil; -}); - -DevToolsUtils.defineLazyGetter(this, "OS", () => { - return Cu.import("resource://gre/modules/osfile.jsm", {}).OS; -}); - -DevToolsUtils.defineLazyGetter(this, "TextDecoder", () => { - return Cu.import("resource://gre/modules/osfile.jsm", {}).TextDecoder; -}); - -DevToolsUtils.defineLazyGetter(this, "NetworkHelper", () => { - return require("devtools/shared/webconsole/network-helper"); -}); - -/** - * Performs a request to load the desired URL and returns a promise. - * - * @param aURL String - * The URL we will request. - * @param aOptions Object - * An object with the following optional properties: - * - loadFromCache: if false, will bypass the cache and - * always load fresh from the network (default: true) - * - policy: the nsIContentPolicy type to apply when fetching the URL - * (only works when loading from system principal) - * - window: the window to get the loadGroup from - * - charset: the charset to use if the channel doesn't provide one - * - principal: the principal to use, if omitted, the request is loaded - * with a codebase principal corresponding to the url being - * loaded, using the origin attributes of the window, if any. - * - cacheKey: when loading from cache, use this key to retrieve a cache - * specific to a given SHEntry. (Allows loading POST - * requests from cache) - * @returns Promise that resolves with an object with the following members on - * success: - * - content: the document at that URL, as a string, - * - contentType: the content type of the document - * - * If an error occurs, the promise is rejected with that error. - * - * XXX: It may be better to use nsITraceableChannel to get to the sources - * without relying on caching when we can (not for eval, etc.): - * http://www.softwareishard.com/blog/firebug/nsitraceablechannel-intercept-http-traffic/ - */ -function mainThreadFetch(aURL, aOptions = { loadFromCache: true, - policy: Ci.nsIContentPolicy.TYPE_OTHER, - window: null, - charset: null, - principal: null, - cacheKey: null }) { - // Create a channel. - let url = aURL.split(" -> ").pop(); - let channel; - try { - channel = newChannelForURL(url, aOptions); - } catch (ex) { - return Promise.reject(ex); - } - - // Set the channel options. - channel.loadFlags = aOptions.loadFromCache - ? channel.LOAD_FROM_CACHE - : channel.LOAD_BYPASS_CACHE; - - if (aOptions.window) { - // Respect private browsing. - channel.loadGroup = aOptions.window.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIWebNavigation) - .QueryInterface(Ci.nsIDocumentLoader) - .loadGroup; - } - - let deferred = Promise.defer(); - let onResponse = (stream, status, request) => { -// if (!components.isSuccessCode(status)) { -// deferred.reject(new Error('Failed to fetch ${url}. Code ${status}.')); -// return; -// } - - try { - // We cannot use NetUtil to do the charset conversion as if charset - // information is not available and our default guess is wrong the method - // might fail and we lose the stream data. This means we can't fall back - // to using the locale default encoding (bug 1181345). - - // Read and decode the data according to the locale default encoding. - let available = stream.available(); - let source = NetUtil.readInputStreamToString(stream, available); - stream.close(); - - // If the channel or the caller has correct charset information, the - // content will be decoded correctly. If we have to fall back to UTF-8 and - // the guess is wrong, the conversion fails and convertToUnicode returns - // the input unmodified. Essentially we try to decode the data as UTF-8 - // and if that fails, we use the locale specific default encoding. This is - // the best we can do if the source does not provide charset info. - let charset = channel.contentCharset || aOptions.charset || "UTF-8"; - let unicodeSource = NetworkHelper.convertToUnicode(source, charset); - - deferred.resolve({ - content: unicodeSource, - contentType: request.contentType - }); - } catch (ex) { - let uri = request.originalURI; - if (ex.name === "NS_BASE_STREAM_CLOSED" && uri instanceof Ci.nsIFileURL) { - // Empty files cause NS_BASE_STREAM_CLOSED exception. Use OS.File to - // differentiate between empty files and other errors (bug 1170864). - // This can be removed when bug 982654 is fixed. - - uri.QueryInterface(Ci.nsIFileURL); - let result = OS.File.read(uri.file.path).then(bytes => { - // Convert the bytearray to a String. - let decoder = new TextDecoder(); - let content = decoder.decode(bytes); - - // We can't detect the contentType without opening a channel - // and that failed already. This is the best we can do here. - return { - content, - contentType: "text/plain" - }; - }); - - deferred.resolve(result); - } else { - deferred.reject(ex); - } - } - }; - - // Open the channel - try { - NetUtil.asyncFetch(channel, onResponse); - } catch (ex) { - return Promise.reject(ex); - } - - return deferred.promise; -} - -/** - * Opens a channel for given URL. Tries a bit harder than NetUtil.newChannel. - * - * @param {String} url - The URL to open a channel for. - * @param {Object} options - The options object passed to @method fetch. - * @return {nsIChannel} - The newly created channel. Throws on failure. - */ -function newChannelForURL(url, { policy }) { - let channelOptions = { - contentPolicyType: policy, - loadUsingSystemPrincipal: true, - uri: url - }; - - try { - return NetUtil.newChannel(channelOptions); - } catch (e) { - // In the xpcshell tests, the script url is the absolute path of the test - // file, which will make a malformed URI error be thrown. Add the file - // scheme to see if it helps. - channelOptions.uri = "file://" + url; - - return NetUtil.newChannel(channelOptions); - } -} - -// Fetch is defined differently depending on whether we are on the main thread -// or a worker thread. -if (!this.isWorker) { - DevToolsUtils.fetch = mainThreadFetch; -} else { - // Services is not available in worker threads, nor is there any other way - // to fetch a URL. We need to enlist the help from the main thread here, by - // issuing an rpc request, to fetch the URL on our behalf. - DevToolsUtils.fetch = function (url, options) { - return rpc("fetch", url, options); - } -} - -/** - * Returns a promise that is resolved or rejected when all promises have settled - * (resolved or rejected). - * - * This differs from Promise.all, which will reject immediately after the first - * rejection, instead of waiting for the remaining promises to settle. - * - * @param values - * Iterable of promises that may be pending, resolved, or rejected. When - * when all promises have settled (resolved or rejected), the returned - * promise will be resolved or rejected as well. - * - * @return A new promise that is fulfilled when all values have settled - * (resolved or rejected). Its resolution value will be an array of all - * resolved values in the given order, or undefined if values is an - * empty array. The reject reason will be forwarded from the first - * promise in the list of given promises to be rejected. - */ -DevToolsUtils.settleAll = values => { - if (values === null || typeof(values[Symbol.iterator]) != "function") { - throw new Error("settleAll() expects an iterable."); - } - - let deferred = Promise.defer(); - - values = Array.isArray(values) ? values : [...values]; - let countdown = values.length; - let resolutionValues = new Array(countdown); - let rejectionValue; - let rejectionOccurred = false; - - if (!countdown) { - deferred.resolve(resolutionValues); - return deferred.promise; - } - - function checkForCompletion() { - if (--countdown > 0) { - return; - } - if (!rejectionOccurred) { - deferred.resolve(resolutionValues); - } else { - deferred.reject(rejectionValue); - } - } - - for (let i = 0; i < values.length; i++) { - let index = i; - let value = values[i]; - let resolver = result => { - resolutionValues[index] = result; - checkForCompletion(); - }; - let rejecter = error => { - if (!rejectionOccurred) { - rejectionValue = error; - rejectionOccurred = true; - } - checkForCompletion(); - }; - - if (value && typeof(value.then) == "function") { - value.then(resolver, rejecter); - } else { - // Given value is not a promise, forward it as a resolution value. - resolver(value); - } - } - - return deferred.promise; -}; - -/** - * When the testing flag is set, various behaviors may be altered from - * production mode, typically to enable easier testing or enhanced debugging. - */ -var testing = false; -Object.defineProperty(DevToolsUtils, "testing", { - get: function() { - return testing; - }, - set: function(state) { - testing = state; - } -}); - -/** - * Open the file at the given path for reading. - * - * @param {String} filePath - * - * @returns Promise - */ -DevToolsUtils.openFileStream = function (filePath) { - return new Promise((resolve, reject) => { - const uri = NetUtil.newURI(new FileUtils.File(filePath)); - NetUtil.asyncFetch( - { uri, loadUsingSystemPrincipal: true }, - (stream, result) => { -// if (!components.isSuccessCode(result)) { -// reject(new Error('Could not open "${filePath}": result = ${result}')); -// return; -// } - - Promise.resolve(stream); - } - ); - }); -} diff --git a/native/cocos/scripting/js-bindings/script/debugger/README.md b/native/cocos/scripting/js-bindings/script/debugger/README.md deleted file mode 100755 index 9e1d7bebd0..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/README.md +++ /dev/null @@ -1,54 +0,0 @@ -Remote Debugging By Using FireFox -================================= - -Requirement ------------ - -* Firefox: From v24 - -How To Use ----------- - -### Prepare ### - -Please refer to https://developer.mozilla.org/en-US/docs/Tools/Remote_Debugging . - -### Enable Debugger Support For Your JSB Project ### - -``` -bool AppDelegate::applicationDidFinishLaunching() -{ - ... - - ScriptingCore* sc = ScriptingCore::getInstance(); - sc->addRegisterCallback(register_all_cocos2dx); - sc->addRegisterCallback(register_all_cocos2dx_extension); - sc->addRegisterCallback(register_cocos2dx_js_extensions); - sc->addRegisterCallback(jsb_register_chipmunk); - sc->addRegisterCallback(register_all_cocos2dx_extension_manual); - sc->addRegisterCallback(register_CCBuilderReader); - sc->addRegisterCallback(jsb_register_system); - sc->addRegisterCallback(JSB_register_opengl); - - sc->start(); - -#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) - sc->enableDebugger(); // Enable debugger here -#endif - - ... -} -``` - -Run your game. - -### Open Firefox And Follow The Step As Follows ### - - -![pic 1](https://lh5.googleusercontent.com/-HoxLGBdV2J0/UlZ7ZoFUjyI/AAAAAAAAADM/68GDaCQ1vP0/s0-I/Firefox-Remote-Debug01.jpg) -![pic 2](https://lh6.googleusercontent.com/-7FDIHAYsKAY/UlZ7Yf8W-pI/AAAAAAAAAFQ/joG0AymnuBk/s0-I/Firefox-Remote-Debug02.jpg) -![pic 3](https://lh4.googleusercontent.com/-idvnMRGcGy8/UlZ7Wj6DDuI/AAAAAAAAAC0/L9IVyHLNqeQ/s0-I/Firefox-Remote-Debug04.jpg) -![pic 4](https://lh6.googleusercontent.com/-YuZj7JGAtFE/UlZ9DDGDczI/AAAAAAAAAEQ/D2qIedjP5FU/s0-I/Firefox-Remote-Debug04.png.png) -![pic 5](https://lh3.googleusercontent.com/-cdIcNa3jT5c/UlZ9uapf3OI/AAAAAAAAAEg/MGq3vLHsauw/s0-I/Firefox-Remote-Debug05.png) -![pic 6](https://lh5.googleusercontent.com/-T79-o5ylJKI/UlZ_JJQe3MI/AAAAAAAAAE8/F63fSVxlJKs/s0-I/Firefox-Remote-Debug06.png) - diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js b/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js deleted file mode 100644 index 758d06d506..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/breakpoint.js +++ /dev/null @@ -1,200 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public -* License, v. 2.0. If a copy of the MPL was not distributed with this -* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// const { ActorClassWithSpec } = require("devtools/shared/protocol"); -// const { breakpointSpec } = require("devtools/shared/specs/breakpoint"); - -// from "devtools/shared/specs/breakpoint" -const breakpointSpec = generateActorSpec({ - typeName: "breakpoint", - - methods: { - delete: {} - }, -}); - -// --------------- - -/** - * Set breakpoints on all the given entry points with the given - * BreakpointActor as the handler. - * - * @param BreakpointActor actor - * The actor handling the breakpoint hits. - * @param Array entryPoints - * An array of objects of the form `{ script, offsets }`. - */ -function setBreakpointAtEntryPoints(actor, entryPoints) { - for (let { script, offsets } of entryPoints) { - actor.addScript(script); - for (let offset of offsets) { - script.setBreakpoint(offset, actor); - } - } -} - -// exports.setBreakpointAtEntryPoints = setBreakpointAtEntryPoints; - -/** - * BreakpointActors exist for the lifetime of their containing thread and are - * responsible for deleting breakpoints, handling breakpoint hits and - * associating breakpoints with scripts. - */ -let BreakpointActor = ActorClassWithSpec(breakpointSpec, { - /** - * Create a Breakpoint actor. - * - * @param ThreadActor threadActor - * The parent thread actor that contains this breakpoint. - * @param OriginalLocation originalLocation - * The original location of the breakpoint. - */ - initialize: function (threadActor, originalLocation) { - // The set of Debugger.Script instances that this breakpoint has been set - // upon. - this.scripts = new Set(); - - this.threadActor = threadActor; - this.originalLocation = originalLocation; - this.condition = null; - this.isPending = true; - }, - - disconnect: function () { - this.removeScripts(); - }, - - hasScript: function (script) { - return this.scripts.has(script); - }, - - /** - * Called when this same breakpoint is added to another Debugger.Script - * instance. - * - * @param script Debugger.Script - * The new source script on which the breakpoint has been set. - */ - addScript: function (script) { - this.scripts.add(script); - this.isPending = false; - }, - - /** - * Remove the breakpoints from associated scripts and clear the script cache. - */ - removeScripts: function () { - for (let script of this.scripts) { - script.clearBreakpoint(this); - } - this.scripts.clear(); - }, - - /** - * Check if this breakpoint has a condition that doesn't error and - * evaluates to true in frame. - * - * @param frame Debugger.Frame - * The frame to evaluate the condition in - * @returns Object - * - result: boolean|undefined - * True when the conditional breakpoint should trigger a pause, - * false otherwise. If the condition evaluation failed/killed, - * `result` will be `undefined`. - * - message: string - * If the condition throws, this is the thrown message. - */ - checkCondition: function (frame) { - let completion = frame.eval(this.condition); - if (completion) { - if (completion.throw) { - // The evaluation failed and threw - let message = "Unknown exception"; - try { - if (completion.throw.getOwnPropertyDescriptor) { - message = completion.throw.getOwnPropertyDescriptor("message") - .value; - } else if (completion.toString) { - message = completion.toString(); - } - } catch (ex) {} - return { - result: true, - message: message - }; - } else if (completion.yield) { - assert(false, "Shouldn't ever get yield completions from an eval"); - } else { - return { result: completion.return ? true : false }; - } - } else { - // The evaluation was killed (possibly by the slow script dialog) - return { result: undefined }; - } - }, - - /** - * A function that the engine calls when a breakpoint has been hit. - * - * @param frame Debugger.Frame - * The stack frame that contained the breakpoint. - */ - hit: function (frame) { - // Don't pause if we are currently stepping (in or over) or the frame is - // black-boxed. - let generatedLocation = this.threadActor.sources.getFrameLocation(frame); - let { originalSourceActor } = this.threadActor.unsafeSynchronize( - this.threadActor.sources.getOriginalLocation(generatedLocation)); - let url = originalSourceActor.url; - - if (this.threadActor.sources.isBlackBoxed(url) - || frame.onStep) { - return undefined; - } - - let reason = {}; - - if (this.threadActor._hiddenBreakpoints.has(this.actorID)) { - reason.type = "pauseOnDOMEvents"; - } else if (!this.condition) { - reason.type = "breakpoint"; - // TODO: add the rest of the breakpoints on that line (bug 676602). - reason.actors = [ this.actorID ]; - } else { - let { result, message } = this.checkCondition(frame); - - if (result) { - if (!message) { - reason.type = "breakpoint"; - } else { - reason.type = "breakpointConditionThrown"; - reason.message = message; - } - reason.actors = [ this.actorID ]; - } else { - return undefined; - } - } - return this.threadActor._pauseAndRespond(frame, reason); - }, - - /** - * Handle a protocol request to remove this breakpoint. - */ - delete: function () { - // Remove from the breakpoint store. - if (this.originalLocation) { - this.threadActor.breakpointActorMap.deleteActor(this.originalLocation); - } - this.threadActor.threadLifetimePool.removeActor(this); - // Remove the actual breakpoint from the associated scripts. - this.removeScripts(); - } -}); - -// exports.BreakpointActor = BreakpointActor; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/common.js b/native/cocos/scripting/js-bindings/script/debugger/actors/common.js deleted file mode 100755 index b5312bbd8d..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/common.js +++ /dev/null @@ -1,512 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -/** - * Creates "registered" actors factory meant for creating another kind of - * factories, ObservedActorFactory, during the call to listTabs. - * These factories live in DebuggerServer.{tab|global}ActorFactories. - * - * These actors only exposes: - * - `name` string attribute used to match actors by constructor name - * in DebuggerServer.remove{Global,Tab}Actor. - * - `createObservedActorFactory` function to create "observed" actors factory - * - * @param options object, function - * Either an object or a function. - * If given an object: - * - * If given a function (deprecated): - * Constructor function of an actor. - * The constructor function for this actor type. - * This expects to be called as a constructor (i.e. with 'new'), - * and passed two arguments: the DebuggerServerConnection, and - * the BrowserTabActor with which it will be associated. - * Only used for deprecated eagerly loaded actors. - * - */ -function RegisteredActorFactory(options, prefix) { - // By default the actor name will also be used for the actorID prefix. - this._prefix = prefix; - if (typeof (options) != "function") { - // actors definition registered by actorRegistryActor - if (options.constructorFun) { - this._getConstructor = () => options.constructorFun; - } else { - // Lazy actor definition, where options contains all the information - // required to load the actor lazily. - this._getConstructor = function () { - // Load the module - let mod; - try { - mod = require(options.id); - } catch (e) { - throw new Error("Unable to load actor module '" + options.id + "'.\n" + - e.message + "\n" + e.stack + "\n"); - } - // Fetch the actor constructor - let c = mod[options.constructorName]; - if (!c) { - throw new Error("Unable to find actor constructor named '" + - options.constructorName + "'. (Is it exported?)"); - } - return c; - }; - } - // Exposes `name` attribute in order to allow removeXXXActor to match - // the actor by its actor constructor name. - this.name = options.constructorName; - } else { - // Old actor case, where options is a function that is the actor constructor. - this._getConstructor = () => options; - // Exposes `name` attribute in order to allow removeXXXActor to match - // the actor by its actor constructor name. - this.name = options.name; - - // For old actors, we allow the use of a different prefix for actorID - // than for listTabs actor names, by fetching a prefix on the actor prototype. - // (Used by ChromeDebuggerActor) - if (options.prototype && options.prototype.actorPrefix) { - this._prefix = options.prototype.actorPrefix; - } - } -} -RegisteredActorFactory.prototype.createObservedActorFactory = function (conn, parentActor) { - return new ObservedActorFactory(this._getConstructor, this._prefix, conn, parentActor); -}; -// exports.RegisteredActorFactory = RegisteredActorFactory; - -/** - * Creates "observed" actors factory meant for creating real actor instances. - * These factories lives in actor pools and fake various actor attributes. - * They will be replaced in actor pools by final actor instances during - * the first request for the same actorID from DebuggerServer._getOrCreateActor. - * - * ObservedActorFactory fakes the following actors attributes: - * actorPrefix (string) Used by ActorPool.addActor to compute the actor id - * actorID (string) Set by ActorPool.addActor just after being instantiated - * registeredPool (object) Set by ActorPool.addActor just after being - * instantiated - * And exposes the following method: - * createActor (function) Instantiate an actor that is going to replace - * this factory in the actor pool. - */ -function ObservedActorFactory(getConstructor, prefix, conn, parentActor) { - this._getConstructor = getConstructor; - this._conn = conn; - this._parentActor = parentActor; - - this.actorPrefix = prefix; - - this.actorID = null; - this.registeredPool = null; -} -ObservedActorFactory.prototype.createActor = function () { - // Fetch the actor constructor - let c = this._getConstructor(); - // Instantiate a new actor instance - let instance = new c(this._conn, this._parentActor); - instance.conn = this._conn; - instance.parentID = this._parentActor.actorID; - // We want the newly-constructed actor to completely replace the factory - // actor. Reusing the existing actor ID will make sure ActorPool.addActor - // does the right thing. - instance.actorID = this.actorID; - this.registeredPool.addActor(instance); - return instance; -}; -// exports.ObservedActorFactory = ObservedActorFactory; - - -/** - * Methods shared between RootActor and BrowserTabActor. - */ - -/** - * Populate |this._extraActors| as specified by |aFactories|, reusing whatever - * actors are already there. Add all actors in the final extra actors table to - * |aPool|. - * - * The root actor and the tab actor use this to instantiate actors that other - * parts of the browser have specified with DebuggerServer.addTabActor and - * DebuggerServer.addGlobalActor. - * - * @param aFactories - * An object whose own property names are the names of properties to add to - * some reply packet (say, a tab actor grip or the "listTabs" response - * form), and whose own property values are actor constructor functions, as - * documented for addTabActor and addGlobalActor. - * - * @param this - * The BrowserRootActor or BrowserTabActor with which the new actors will - * be associated. It should support whatever API the |aFactories| - * constructor functions might be interested in, as it is passed to them. - * For the sake of CommonCreateExtraActors itself, it should have at least - * the following properties: - * - * - _extraActors - * An object whose own property names are factory table (and packet) - * property names, and whose values are no-argument actor constructors, - * of the sort that one can add to an ActorPool. - * - * - conn - * The DebuggerServerConnection in which the new actors will participate. - * - * - actorID - * The actor's name, for use as the new actors' parentID. - */ -function createExtraActors(aFactories, aPool) { - // Walk over global actors added by extensions. - for (let name in aFactories) { - let actor = this._extraActors[name]; - if (!actor) { - // Register another factory, but this time specific to this connection. - // It creates a fake actor that looks like an regular actor in the pool, - // but without actually instantiating the actor. - // It will only be instantiated on the first request made to the actor. - actor = aFactories[name].createObservedActorFactory(this.conn, this); - this._extraActors[name] = actor; - } - - // If the actor already exists in the pool, it may have been instantiated, - // so make sure not to overwrite it by a non-instantiated version. - if (!aPool.has(actor.actorID)) { - aPool.addActor(actor); - } - } -}; - -/** - * Append the extra actors in |this._extraActors|, constructed by a prior call - * to CommonCreateExtraActors, to |aObject|. - * - * @param aObject - * The object to which the extra actors should be added, under the - * property names given in the |aFactories| table passed to - * CommonCreateExtraActors. - * - * @param this - * The BrowserRootActor or BrowserTabActor whose |_extraActors| table we - * should use; see above. - */ -function appendExtraActors(aObject) { - for (let name in this._extraActors) { - let actor = this._extraActors[name]; - aObject[name] = actor.actorID; - } -}; - -/** - * Construct an ActorPool. - * - * ActorPools are actorID -> actor mapping and storage. These are - * used to accumulate and quickly dispose of groups of actors that - * share a lifetime. - */ -function ActorPool(aConnection) -{ - this.conn = aConnection; - this._actors = {}; -} - -ActorPool.prototype = { - /** - * Destroy the pool. This will remove all actors from the pool. - */ - destroy: function AP_destroy() { - for (let id in this._actors) { - this.removeActor(this._actors[id]); - } - }, - - /** - * Add an actor to the pool. If the actor doesn't have an ID, allocate one - * from the connection. - * - * @param Object aActor - * The actor to be added to the pool. - */ - addActor: function AP_addActor(aActor) { - aActor.conn = this.conn; - if (!aActor.actorID) { - let prefix = aActor.actorPrefix; - if (!prefix && typeof aActor == "function") { - // typeName is a convention used with protocol.js-based actors - prefix = aActor.prototype.actorPrefix || aActor.prototype.typeName; - } - aActor.actorID = this.conn.allocID(prefix || undefined); - } - - // If the actor is already in a pool, remove it without destroying it. - if (aActor.registeredPool) { - delete aActor.registeredPool._actors[aActor.actorID]; - } - aActor.registeredPool = this; - - this._actors[aActor.actorID] = aActor; - }, - - /** - * Remove an actor from the pool. If the actor has a disconnect method, call - * it. - */ - removeActor: function AP_remove(aActor) { - delete this._actors[aActor.actorID]; - if (aActor.disconnect) { - aActor.disconnect(); - } - }, - - get: function AP_get(aActorID) { - return this._actors[aActorID] || undefined; - }, - - has: function AP_has(aActorID) { - return aActorID in this._actors; - }, - - /** - * Returns true if the pool is empty. - */ - isEmpty: function AP_isEmpty() { - return Object.keys(this._actors).length == 0; - }, - - /** - * Match the api expected by the protocol library. - */ - unmanage: function (aActor) { - return this.removeActor(aActor); - }, - - forEach: function (callback) { - for (let name in this._actors) { - callback(this._actors[name]); - } - }, -}; - -// exports.ActorPool = ActorPool; - -/** - * An OriginalLocation represents a location in an original source. - * - * @param SourceActor actor - * A SourceActor representing an original source. - * @param Number line - * A line within the given source. - * @param Number column - * A column within the given line. - * @param String name - * The name of the symbol corresponding to this OriginalLocation. - */ - -function OriginalLocation(actor, line, column, name) { - this._connection = actor ? actor.conn : null; - this._actorID = actor ? actor.actorID : undefined; - this._line = line; - this._column = column; - this._name = name; -} - -OriginalLocation.fromGeneratedLocation = function (generatedLocation) { - return new OriginalLocation( - generatedLocation.generatedSourceActor, - generatedLocation.generatedLine, - generatedLocation.generatedColumn - ); -}; - -OriginalLocation.prototype = { - get originalSourceActor() { - return this._connection ? this._connection.getActor(this._actorID) : null; - }, - - get originalUrl() { - let actor = this.originalSourceActor; - let source = actor.source; - return source ? source.url : actor._originalUrl; - }, - - get originalLine() { - return this._line; - }, - - get originalColumn() { - return this._column; - }, - - get originalName() { - return this._name; - }, - - get generatedSourceActor() { - throw new Error("Shouldn't access generatedSourceActor from an OriginalLocation"); - }, - - get generatedLine() { - throw new Error("Shouldn't access generatedLine from an OriginalLocation"); - }, - - get generatedColumn() { - throw new Error("Shouldn't access generatedColumn from an Originallocation"); - }, - - equals: function (other) { - return this.originalSourceActor.url == other.originalSourceActor.url && - this.originalLine === other.originalLine && - (this.originalColumn === undefined || - other.originalColumn === undefined || - this.originalColumn === other.originalColumn); - }, - - toJSON: function () { - return { - source: this.originalSourceActor.form(), - line: this.originalLine, - column: this.originalColumn - }; - } -}; - -/** - * A GeneratedLocation represents a location in a generated source. - * - * @param SourceActor actor - * A SourceActor representing a generated source. - * @param Number line - * A line within the given source. - * @param Number column - * A column within the given line. - */ -function GeneratedLocation(actor, line, column, lastColumn) { - this._connection = actor ? actor.conn : null; - this._actorID = actor ? actor.actorID : undefined; - this._line = line; - this._column = column; - this._lastColumn = (lastColumn !== undefined) ? lastColumn : column + 1; -} - -GeneratedLocation.fromOriginalLocation = function (originalLocation) { - return new GeneratedLocation( - originalLocation.originalSourceActor, - originalLocation.originalLine, - originalLocation.originalColumn - ); -}; - -GeneratedLocation.prototype = { - get originalSourceActor() { - throw new Error(); - }, - - get originalUrl() { - throw new Error("Shouldn't access originalUrl from a GeneratedLocation"); - }, - - get originalLine() { - throw new Error("Shouldn't access originalLine from a GeneratedLocation"); - }, - - get originalColumn() { - throw new Error("Shouldn't access originalColumn from a GeneratedLocation"); - }, - - get originalName() { - throw new Error("Shouldn't access originalName from a GeneratedLocation"); - }, - - get generatedSourceActor() { - return this._connection ? this._connection.getActor(this._actorID) : null; - }, - - get generatedLine() { - return this._line; - }, - - get generatedColumn() { - return this._column; - }, - - get generatedLastColumn() { - return this._lastColumn; - }, - - equals: function (other) { - return this.generatedSourceActor.url == other.generatedSourceActor.url && - this.generatedLine === other.generatedLine && - (this.generatedColumn === undefined || - other.generatedColumn === undefined || - this.generatedColumn === other.generatedColumn); - }, - - toJSON: function () { - return { - source: this.generatedSourceActor.form(), - line: this.generatedLine, - column: this.generatedColumn, - lastColumn: this.generatedLastColumn - }; - } -}; - -/** - * A method decorator that ensures the actor is in the expected state before - * proceeding. If the actor is not in the expected state, the decorated method - * returns a rejected promise. - * - * The actor's state must be at this.state property. - * - * @param String expectedState - * The expected state. - * @param String activity - * Additional info about what's going on. - * @param Function method - * The actor method to proceed with when the actor is in the expected - * state. - * - * @returns Function - * The decorated method. - */ -function expectState(expectedState, method, activity) { - return function (...args) { - if (this.state !== expectedState) { - const msg = `Wrong state while ${activity}:` + - `Expected '${expectedState}', ` + - `but current state is '${this.state}'.`; - return Promise.reject(new Error(msg)); - } - - return method.apply(this, args); - }; -} - -/** - * Proxies a call from an actor to an underlying module, stored - * as `bridge` on the actor. This allows a module to be defined in one - * place, usable by other modules/actors on the server, but a separate - * module defining the actor/RDP definition. - * - * @see Framerate implementation: devtools/server/performance/framerate.js - * @see Framerate actor definition: devtools/server/actors/framerate.js - */ -function actorBridge(methodName, definition = {}) { - return method(function () { - return this.bridge[methodName].apply(this.bridge, arguments); - }, definition); -} - -/** - * Like `actorBridge`, but without a spec definition, for when the actor is - * created with `ActorClassWithSpec` rather than vanilla `ActorClass`. - */ -function actorBridgeWithSpec (methodName) { - return method(function () { - return this.bridge[methodName].apply(this.bridge, arguments); - }); -} - diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/environment.js b/native/cocos/scripting/js-bindings/script/debugger/actors/environment.js deleted file mode 100644 index c1dd473578..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/environment.js +++ /dev/null @@ -1,221 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -"use strict"; - -// const { ActorClassWithSpec } = require("devtools/shared/protocol"); -// const { createValueGrip } = require("devtools/server/actors/object"); -// const { environmentSpec } = require("devtools/shared/specs/environment"); - -// from "devtools/shared/specs/environment" -const environmentSpec = generateActorSpec({ - typeName: "environment", - - methods: { - assign: { - request: { - name: Arg(1), - value: Arg(2) - } - }, - bindings: { - request: {}, - response: { - bindings: RetVal("json") - } - }, - }, -}); - -// ------------ - -/** - * Creates an EnvironmentActor. EnvironmentActors are responsible for listing - * the bindings introduced by a lexical environment and assigning new values to - * those identifier bindings. - * - * @param Debugger.Environment aEnvironment - * The lexical environment that will be used to create the actor. - * @param ThreadActor aThreadActor - * The parent thread actor that contains this environment. - */ -let EnvironmentActor = ActorClassWithSpec(environmentSpec, { - initialize: function (environment, threadActor) { - this.obj = environment; - this.threadActor = threadActor; - }, - - /** - * Return an environment form for use in a protocol message. - */ - form: function () { - let form = { actor: this.actorID }; - - // What is this environment's type? - if (this.obj.type == "declarative") { - form.type = this.obj.callee ? "function" : "block"; - } else { - form.type = this.obj.type; - } - - // Does this environment have a parent? - if (this.obj.parent) { - form.parent = (this.threadActor - .createEnvironmentActor(this.obj.parent, - this.registeredPool) - .form()); - } - - // Does this environment reflect the properties of an object as variables? - if (this.obj.type == "object" || this.obj.type == "with") { - form.object = createValueGrip(this.obj.object, - this.registeredPool, this.threadActor.objectGrip); - } - - // Is this the environment created for a function call? - if (this.obj.callee) { - form.function = createValueGrip(this.obj.callee, - this.registeredPool, this.threadActor.objectGrip); - } - - // Shall we list this environment's bindings? - if (this.obj.type == "declarative") { - form.bindings = this.bindings(); - } - - return form; - }, - - /** - * Handle a protocol request to change the value of a variable bound in this - * lexical environment. - * - * @param string name - * The name of the variable to be changed. - * @param any value - * The value to be assigned. - */ - assign: function (name, value) { - // TODO: enable the commented-out part when getVariableDescriptor lands - // (bug 725815). - /* let desc = this.obj.getVariableDescriptor(name); - - if (!desc.writable) { - return { error: "immutableBinding", - message: "Changing the value of an immutable binding is not " + - "allowed" }; - }*/ - - try { - this.obj.setVariable(name, value); - } catch (e) { - if (e instanceof Debugger.DebuggeeWouldRun) { - throw { - error: "threadWouldRun", - message: "Assigning a value would cause the debuggee to run" - }; - } else { - throw e; - } - } - return { from: this.actorID }; - }, - - /** - * Handle a protocol request to fully enumerate the bindings introduced by the - * lexical environment. - */ - bindings: function () { - let bindings = { arguments: [], variables: {} }; - - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands (bug 725815). - if (typeof this.obj.getVariable != "function") { - // if (typeof this.obj.getVariableDescriptor != "function") { - return bindings; - } - - let parameterNames; - if (this.obj.callee) { - parameterNames = this.obj.callee.parameterNames; - } else { - parameterNames = []; - } - for (let name of parameterNames) { - let arg = {}; - let value = this.obj.getVariable(name); - - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands (bug 725815). - let desc = { - value: value, - configurable: false, - writable: !(value && value.optimizedOut), - enumerable: true - }; - - // let desc = this.obj.getVariableDescriptor(name); - let descForm = { - enumerable: true, - configurable: desc.configurable - }; - if ("value" in desc) { - descForm.value = createValueGrip(desc.value, - this.registeredPool, this.threadActor.objectGrip); - descForm.writable = desc.writable; - } else { - descForm.get = createValueGrip(desc.get, this.registeredPool, - this.threadActor.objectGrip); - descForm.set = createValueGrip(desc.set, this.registeredPool, - this.threadActor.objectGrip); - } - arg[name] = descForm; - bindings.arguments.push(arg); - } - - for (let name of this.obj.names()) { - if (bindings.arguments.some(function exists(element) { - return !!element[name]; - })) { - continue; - } - - let value = this.obj.getVariable(name); - - // TODO: this part should be removed in favor of the commented-out part - // below when getVariableDescriptor lands. - let desc = { - value: value, - configurable: false, - writable: !(value && - (value.optimizedOut || - value.uninitialized || - value.missingArguments)), - enumerable: true - }; - - // let desc = this.obj.getVariableDescriptor(name); - let descForm = { - enumerable: true, - configurable: desc.configurable - }; - if ("value" in desc) { - descForm.value = createValueGrip(desc.value, - this.registeredPool, this.threadActor.objectGrip); - descForm.writable = desc.writable; - } else { - descForm.get = createValueGrip(desc.get || undefined, - this.registeredPool, this.threadActor.objectGrip); - descForm.set = createValueGrip(desc.set || undefined, - this.registeredPool, this.threadActor.objectGrip); - } - bindings.variables[name] = descForm; - } - - return bindings; - } -}); - -// exports.EnvironmentActor = EnvironmentActor; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/frame.js b/native/cocos/scripting/js-bindings/script/debugger/actors/frame.js deleted file mode 100644 index 06cc2f584d..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/frame.js +++ /dev/null @@ -1,109 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// const { ActorPool } = require("devtools/server/actors/common"); -// const { createValueGrip } = require("devtools/server/actors/object"); -// const { ActorClassWithSpec } = require("devtools/shared/protocol"); -// const { frameSpec } = require("devtools/shared/specs/frame"); - -// from "devtools/shared/specs/frame" -const frameSpec = generateActorSpec({ - typeName: "frame", - - methods: {}, -}); - -// -------------- - -/** - * An actor for a specified stack frame. - */ -let FrameActor = ActorClassWithSpec(frameSpec, { - /** - * Creates the Frame actor. - * - * @param frame Debugger.Frame - * The debuggee frame. - * @param threadActor ThreadActor - * The parent thread actor for this frame. - */ - initialize: function (frame, threadActor) { - this.frame = frame; - this.threadActor = threadActor; - }, - - /** - * A pool that contains frame-lifetime objects, like the environment. - */ - _frameLifetimePool: null, - get frameLifetimePool() { - if (!this._frameLifetimePool) { - this._frameLifetimePool = new ActorPool(this.conn); - this.conn.addActorPool(this._frameLifetimePool); - } - return this._frameLifetimePool; - }, - - /** - * Finalization handler that is called when the actor is being evicted from - * the pool. - */ - disconnect: function () { - this.conn.removeActorPool(this._frameLifetimePool); - this._frameLifetimePool = null; - }, - - /** - * Returns a frame form for use in a protocol message. - */ - form: function () { - let threadActor = this.threadActor; - let form = { actor: this.actorID, - type: this.frame.type }; - if (this.frame.type === "call") { - form.callee = createValueGrip(this.frame.callee, threadActor._pausePool, - threadActor.objectGrip); - } - - if (this.frame.environment) { - let envActor = threadActor.createEnvironmentActor( - this.frame.environment, - this.frameLifetimePool - ); - form.environment = envActor.form(); - } - form.this = createValueGrip(this.frame.this, threadActor._pausePool, - threadActor.objectGrip); - form.arguments = this._args(); - if (this.frame.script) { - var generatedLocation = this.threadActor.sources.getFrameLocation(this.frame); - form.where = { - source: generatedLocation.generatedSourceActor.form(), - line: generatedLocation.generatedLine, - column: generatedLocation.generatedColumn - }; - } - - if (!this.frame.older) { - form.oldest = true; - } - - return form; - }, - - _args: function () { - if (!this.frame.arguments) { - return []; - } - - return this.frame.arguments.map(arg => createValueGrip(arg, - this.threadActor._pausePool, this.threadActor.objectGrip)); - } -}); - -// exports.FrameActor = FrameActor; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/object.js b/native/cocos/scripting/js-bindings/script/debugger/actors/object.js deleted file mode 100755 index a7085082d1..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/object.js +++ /dev/null @@ -1,2250 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// const { Cu, Ci } = require("chrome"); -// const { GeneratedLocation } = require("devtools/server/actors/common"); -// const { DebuggerServer } = require("devtools/server/main"); -// const DevToolsUtils = require("devtools/shared/DevToolsUtils"); -// const { assert, dumpn } = DevToolsUtils; -// const PromiseDebugging = require("PromiseDebugging"); - -const TYPED_ARRAY_CLASSES = ["Uint8Array", "Uint8ClampedArray", "Uint16Array", - "Uint32Array", "Int8Array", "Int16Array", "Int32Array", "Float32Array", - "Float64Array"]; - -// Number of items to preview in objects, arrays, maps, sets, lists, -// collections, etc. -const OBJECT_PREVIEW_MAX_ITEMS = 10; - -/** - * Creates an actor for the specified object. - * - * @param obj Debugger.Object - * The debuggee object. - * @param hooks Object - * A collection of abstract methods that are implemented by the caller. - * ObjectActor requires the following functions to be implemented by - * the caller: - * - createValueGrip - * Creates a value grip for the given object - * - sources - * TabSources getter that manages the sources of a thread - * - createEnvironmentActor - * Creates and return an environment actor - * - getGripDepth - * An actor's grip depth getter - * - incrementGripDepth - * Increment the actor's grip depth - * - decrementGripDepth - * Decrement the actor's grip depth - * - globalDebugObject - * The Debuggee Global Object as given by the ThreadActor - */ -function ObjectActor(obj, { - createValueGrip, - sources, - createEnvironmentActor, - getGripDepth, - incrementGripDepth, - decrementGripDepth, - getGlobalDebugObject -}) { - assert(!obj.optimizedOut, - "Should not create object actors for optimized out values!"); - this.obj = obj; - this.hooks = { - createValueGrip, - sources, - createEnvironmentActor, - getGripDepth, - incrementGripDepth, - decrementGripDepth, - getGlobalDebugObject - }; - this.iterators = new Set(); -} - -ObjectActor.prototype = { - actorPrefix: "obj", - - /** - * Returns a grip for this actor for returning in a protocol message. - */ - grip: function () { - this.hooks.incrementGripDepth(); - - let g = { - "type": "object", - "actor": this.actorID - }; - - // If it's a proxy, lie and tell that it belongs to an invented - // "Proxy" class, and avoid calling the [[IsExtensible]] trap - if(this.obj.isProxy) { - g.class = "Proxy"; - g.proxyTarget = this.hooks.createValueGrip(this.obj.proxyTarget); - g.proxyHandler = this.hooks.createValueGrip(this.obj.proxyHandler); - } else { - g.class = this.obj.class; - g.extensible = this.obj.isExtensible(); - g.frozen = this.obj.isFrozen(); - g.sealed = this.obj.isSealed(); - } - - if (g.class != "DeadObject") { - if (g.class == "Promise") { - g.promiseState = this._createPromiseState(); - } - - // FF40+: Allow to know how many properties an object has - // to lazily display them when there is a bunch. - // Throws on some MouseEvent object in tests. - try { - // Bug 1163520: Assert on internal functions - if (!["Function", "Proxy"].includes(g.class)) { - g.ownPropertyLength = this.obj.getOwnPropertyNames().length; - } - } catch (e) {} - - let raw = this.obj.unsafeDereference(); - - // If Cu is not defined, we are running on a worker thread, where xrays - // don't exist. - // if (Cu) { - // raw = Cu.unwaiveXrays(raw); - // } - - if (!DevToolsUtils.isSafeJSObject(raw)) { - raw = null; - } - - // let previewers = DebuggerServer.ObjectActorPreviewers[g.class] || - // DebuggerServer.ObjectActorPreviewers.Object; - // for (let fn of previewers) { - // try { - // if (fn(this, g, raw)) { - // break; - // } - // } catch (e) { - // let msg = "ObjectActor.prototype.grip previewer function"; - // DevToolsUtils.reportException(msg, e); - // } - // } - } - - this.hooks.decrementGripDepth(); - return g; - }, - - /** - * Returns an object exposing the internal Promise state. - */ - _createPromiseState: function () { - const { state, value, reason } = getPromiseState(this.obj); - let promiseState = { state }; - - if (state == "fulfilled") { - promiseState.value = this.hooks.createValueGrip(value); - } else if (state == "rejected") { - promiseState.reason = this.hooks.createValueGrip(reason); - } - - promiseState.creationTimestamp = Date.now() - this.obj.promiseLifetime; - - // Only add the timeToSettle property if the Promise isn't pending. - if (state !== "pending") { - promiseState.timeToSettle = this.obj.promiseTimeToResolution; - } - - return promiseState; - }, - - /** - * Releases this actor from the pool. - */ - release: function () { - if (this.registeredPool.objectActors) { - this.registeredPool.objectActors.delete(this.obj); - } - this.iterators.forEach(actor => this.registeredPool.removeActor(actor)); - this.iterators.clear(); - this.registeredPool.removeActor(this); - }, - - /** - * Handle a protocol request to provide the definition site of this function - * object. - */ - onDefinitionSite: function () { - if (this.obj.class != "Function") { - return { - from: this.actorID, - error: "objectNotFunction", - message: this.actorID + " is not a function." - }; - } - - if (!this.obj.script) { - return { - from: this.actorID, - error: "noScript", - message: this.actorID + " has no Debugger.Script" - }; - } - - return this.hooks.sources().getOriginalLocation(new GeneratedLocation( - this.hooks.sources().createNonSourceMappedActor(this.obj.script.source), - this.obj.script.startLine, - 0 // TODO bug 901138: use Debugger.Script.prototype.startColumn - )).then((originalLocation) => { - return { - source: originalLocation.originalSourceActor.form(), - line: originalLocation.originalLine, - column: originalLocation.originalColumn - }; - }); - }, - - /** - * Handle a protocol request to provide the names of the properties defined on - * the object and not its prototype. - */ - onOwnPropertyNames: function () { - return { from: this.actorID, - ownPropertyNames: this.obj.getOwnPropertyNames() }; - }, - - /** - * Creates an actor to iterate over an object property names and values. - * See PropertyIteratorActor constructor for more info about options param. - * - * @param request object - * The protocol request object. - */ - onEnumProperties: function (request) { - let actor = new PropertyIteratorActor(this, request.options); - this.registeredPool.addActor(actor); - this.iterators.add(actor); - return { iterator: actor.grip() }; - }, - - /** - * Creates an actor to iterate over entries of a Map/Set-like object. - */ - onEnumEntries: function () { - let actor = new PropertyIteratorActor(this, { enumEntries: true }); - this.registeredPool.addActor(actor); - this.iterators.add(actor); - return { iterator: actor.grip() }; - }, - - /** - * Handle a protocol request to provide the prototype and own properties of - * the object. - */ - onPrototypeAndProperties: function () { - let ownProperties = Object.create(null); - let names; - try { - names = this.obj.getOwnPropertyNames(); - } catch (ex) { - // The above can throw if this.obj points to a dead object. - // TODO: we should use Cu.isDeadWrapper() - see bug 885800. - return { from: this.actorID, - prototype: this.hooks.createValueGrip(null), - ownProperties: ownProperties, - safeGetterValues: Object.create(null) }; - } - for (let name of names) { - ownProperties[name] = this._propertyDescriptor(name); - } - return { from: this.actorID, - prototype: this.hooks.createValueGrip(this.obj.proto), - ownProperties: ownProperties, - safeGetterValues: this._findSafeGetterValues(names) }; - }, - - /** - * Find the safe getter values for the current Debugger.Object, |this.obj|. - * - * @private - * @param array ownProperties - * The array that holds the list of known ownProperties names for - * |this.obj|. - * @param number [limit=0] - * Optional limit of getter values to find. - * @return object - * An object that maps property names to safe getter descriptors as - * defined by the remote debugging protocol. - */ - _findSafeGetterValues: function (ownProperties, limit = 0) { - let safeGetterValues = Object.create(null); - let obj = this.obj; - let level = 0, i = 0; - - // Most objects don't have any safe getters but inherit some from their - // prototype. Avoid calling getOwnPropertyNames on objects that may have - // many properties like Array, strings or js objects. That to avoid - // freezing firefox when doing so. - if (TYPED_ARRAY_CLASSES.includes(this.obj.class) || - ["Array", "Object", "String"].includes(this.obj.class)) { - obj = obj.proto; - level++; - } - - while (obj) { - let getters = this._findSafeGetters(obj); - for (let name of getters) { - // Avoid overwriting properties from prototypes closer to this.obj. Also - // avoid providing safeGetterValues from prototypes if property |name| - // is already defined as an own property. - if (name in safeGetterValues || - (obj != this.obj && ownProperties.indexOf(name) !== -1)) { - continue; - } - - // Ignore __proto__ on Object.prototye. - if (!obj.proto && name == "__proto__") { - continue; - } - - let desc = null, getter = null; - try { - desc = obj.getOwnPropertyDescriptor(name); - getter = desc.get; - } catch (ex) { - // The above can throw if the cache becomes stale. - } - if (!getter) { - obj._safeGetters = null; - continue; - } - - let result = getter.call(this.obj); - if (result && !("throw" in result)) { - let getterValue = undefined; - if ("return" in result) { - getterValue = result.return; - } else if ("yield" in result) { - getterValue = result.yield; - } - // WebIDL attributes specified with the LenientThis extended attribute - // return undefined and should be ignored. - if (getterValue !== undefined) { - safeGetterValues[name] = { - getterValue: this.hooks.createValueGrip(getterValue), - getterPrototypeLevel: level, - enumerable: desc.enumerable, - writable: level == 0 ? desc.writable : true, - }; - if (limit && ++i == limit) { - break; - } - } - } - } - if (limit && i == limit) { - break; - } - - obj = obj.proto; - level++; - } - - return safeGetterValues; - }, - - /** - * Find the safe getters for a given Debugger.Object. Safe getters are native - * getters which are safe to execute. - * - * @private - * @param Debugger.Object object - * The Debugger.Object where you want to find safe getters. - * @return Set - * A Set of names of safe getters. This result is cached for each - * Debugger.Object. - */ - _findSafeGetters: function (object) { - if (object._safeGetters) { - return object._safeGetters; - } - - let getters = new Set(); - let names = []; - try { - names = object.getOwnPropertyNames(); - } catch (ex) { - // Calling getOwnPropertyNames() on some wrapped native prototypes is not - // allowed: "cannot modify properties of a WrappedNative". See bug 952093. - } - - for (let name of names) { - let desc = null; - try { - desc = object.getOwnPropertyDescriptor(name); - } catch (e) { - // Calling getOwnPropertyDescriptor on wrapped native prototypes is not - // allowed (bug 560072). - } - if (!desc || desc.value !== undefined || !("get" in desc)) { - continue; - } - - if (DevToolsUtils.hasSafeGetter(desc)) { - getters.add(name); - } - } - - object._safeGetters = getters; - return getters; - }, - - /** - * Handle a protocol request to provide the prototype of the object. - */ - onPrototype: function () { - return { from: this.actorID, - prototype: this.hooks.createValueGrip(this.obj.proto) }; - }, - - /** - * Handle a protocol request to provide the property descriptor of the - * object's specified property. - * - * @param request object - * The protocol request object. - */ - onProperty: function (request) { - if (!request.name) { - return { error: "missingParameter", - message: "no property name was specified" }; - } - - return { from: this.actorID, - descriptor: this._propertyDescriptor(request.name) }; - }, - - /** - * Handle a protocol request to provide the display string for the object. - */ - onDisplayString: function () { - const string = stringify(this.obj); - return { from: this.actorID, - displayString: this.hooks.createValueGrip(string) }; - }, - - /** - * A helper method that creates a property descriptor for the provided object, - * properly formatted for sending in a protocol response. - * - * @private - * @param string name - * The property that the descriptor is generated for. - * @param boolean [onlyEnumerable] - * Optional: true if you want a descriptor only for an enumerable - * property, false otherwise. - * @return object|undefined - * The property descriptor, or undefined if this is not an enumerable - * property and onlyEnumerable=true. - */ - _propertyDescriptor: function (name, onlyEnumerable) { - let desc; - try { - desc = this.obj.getOwnPropertyDescriptor(name); - } catch (e) { - // Calling getOwnPropertyDescriptor on wrapped native prototypes is not - // allowed (bug 560072). Inform the user with a bogus, but hopefully - // explanatory, descriptor. - return { - configurable: false, - writable: false, - enumerable: false, - value: e.name - }; - } - - if (!desc || onlyEnumerable && !desc.enumerable) { - return undefined; - } - - let retval = { - configurable: desc.configurable, - enumerable: desc.enumerable - }; - - if ("value" in desc) { - retval.writable = desc.writable; - retval.value = this.hooks.createValueGrip(desc.value); - } else { - if ("get" in desc) { - retval.get = this.hooks.createValueGrip(desc.get); - } - if ("set" in desc) { - retval.set = this.hooks.createValueGrip(desc.set); - } - } - return retval; - }, - - /** - * Handle a protocol request to provide the source code of a function. - * - * @param request object - * The protocol request object. - */ - onDecompile: function (request) { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "decompile request is only valid for object grips " + - "with a 'Function' class." }; - } - - return { from: this.actorID, - decompiledCode: this.obj.decompile(!!request.pretty) }; - }, - - /** - * Handle a protocol request to provide the parameters of a function. - */ - onParameterNames: function () { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "'parameterNames' request is only valid for object " + - "grips with a 'Function' class." }; - } - - return { parameterNames: this.obj.parameterNames }; - }, - - /** - * Handle a protocol request to release a thread-lifetime grip. - */ - onRelease: function () { - this.release(); - return {}; - }, - - /** - * Handle a protocol request to provide the lexical scope of a function. - */ - onScope: function () { - if (this.obj.class !== "Function") { - return { error: "objectNotFunction", - message: "scope request is only valid for object grips with a" + - " 'Function' class." }; - } - - let envActor = this.hooks.createEnvironmentActor(this.obj.environment, - this.registeredPool); - if (!envActor) { - return { error: "notDebuggee", - message: "cannot access the environment of this function." }; - } - - return { from: this.actorID, scope: envActor.form() }; - }, - - /** - * Handle a protocol request to get the list of dependent promises of a - * promise. - * - * @return object - * Returns an object containing an array of object grips of the - * dependent promises - */ - onDependentPromises: function () { - if (this.obj.class != "Promise") { - return { error: "objectNotPromise", - message: "'dependentPromises' request is only valid for " + - "object grips with a 'Promise' class." }; - } - - let promises = this.obj.promiseDependentPromises.map(p => this.hooks.createValueGrip(p)); - - return { promises }; - }, - - /** - * Handle a protocol request to get the allocation stack of a promise. - */ - onAllocationStack: function () { - if (this.obj.class != "Promise") { - return { error: "objectNotPromise", - message: "'allocationStack' request is only valid for " + - "object grips with a 'Promise' class." }; - } - - let stack = this.obj.promiseAllocationSite; - let allocationStacks = []; - - while (stack) { - if (stack.source) { - let source = this._getSourceOriginalLocation(stack); - - if (source) { - allocationStacks.push(source); - } - } - stack = stack.parent; - } - - return Promise.all(allocationStacks).then(stacks => { - return { allocationStack: stacks }; - }); - }, - - /** - * Handle a protocol request to get the fulfillment stack of a promise. - */ - onFulfillmentStack: function () { - if (this.obj.class != "Promise") { - return { error: "objectNotPromise", - message: "'fulfillmentStack' request is only valid for " + - "object grips with a 'Promise' class." }; - } - - let stack = this.obj.promiseResolutionSite; - let fulfillmentStacks = []; - - while (stack) { - if (stack.source) { - let source = this._getSourceOriginalLocation(stack); - - if (source) { - fulfillmentStacks.push(source); - } - } - stack = stack.parent; - } - - return Promise.all(fulfillmentStacks).then(stacks => { - return { fulfillmentStack: stacks }; - }); - }, - - /** - * Handle a protocol request to get the rejection stack of a promise. - */ - onRejectionStack: function () { - if (this.obj.class != "Promise") { - return { error: "objectNotPromise", - message: "'rejectionStack' request is only valid for " + - "object grips with a 'Promise' class." }; - } - - let stack = this.obj.promiseResolutionSite; - let rejectionStacks = []; - - while (stack) { - if (stack.source) { - let source = this._getSourceOriginalLocation(stack); - - if (source) { - rejectionStacks.push(source); - } - } - stack = stack.parent; - } - - return Promise.all(rejectionStacks).then(stacks => { - return { rejectionStack: stacks }; - }); - }, - - /** - * Helper function for fetching the source location of a SavedFrame stack. - * - * @param SavedFrame stack - * The promise allocation stack frame - * @return object - * Returns an object containing the source location of the SavedFrame - * stack. - */ - _getSourceOriginalLocation: function (stack) { - let source; - - // Catch any errors if the source actor cannot be found - try { - source = this.hooks.sources().getSourceActorByURL(stack.source); - } catch (e) {} - - if (!source) { - return null; - } - - return this.hooks.sources().getOriginalLocation(new GeneratedLocation( - source, - stack.line, - stack.column - )).then((originalLocation) => { - return { - source: originalLocation.originalSourceActor.form(), - line: originalLocation.originalLine, - column: originalLocation.originalColumn, - functionDisplayName: stack.functionDisplayName - }; - }); - } -}; - -ObjectActor.prototype.requestTypes = { - "definitionSite": ObjectActor.prototype.onDefinitionSite, - "parameterNames": ObjectActor.prototype.onParameterNames, - "prototypeAndProperties": ObjectActor.prototype.onPrototypeAndProperties, - "enumProperties": ObjectActor.prototype.onEnumProperties, - "prototype": ObjectActor.prototype.onPrototype, - "property": ObjectActor.prototype.onProperty, - "displayString": ObjectActor.prototype.onDisplayString, - "ownPropertyNames": ObjectActor.prototype.onOwnPropertyNames, - "decompile": ObjectActor.prototype.onDecompile, - "release": ObjectActor.prototype.onRelease, - "scope": ObjectActor.prototype.onScope, - "dependentPromises": ObjectActor.prototype.onDependentPromises, - "allocationStack": ObjectActor.prototype.onAllocationStack, - "fulfillmentStack": ObjectActor.prototype.onFulfillmentStack, - "rejectionStack": ObjectActor.prototype.onRejectionStack, - "enumEntries": ObjectActor.prototype.onEnumEntries, -}; - -/** - * Creates an actor to iterate over an object's property names and values. - * - * @param objectActor ObjectActor - * The object actor. - * @param options Object - * A dictionary object with various boolean attributes: - * - enumEntries Boolean - * If true, enumerates the entries of a Map or Set object - * instead of enumerating properties. - * - ignoreIndexedProperties Boolean - * If true, filters out Array items. - * e.g. properties names between `0` and `object.length`. - * - ignoreNonIndexedProperties Boolean - * If true, filters out items that aren't array items - * e.g. properties names that are not a number between `0` - * and `object.length`. - * - sort Boolean - * If true, the iterator will sort the properties by name - * before dispatching them. - * - query String - * If non-empty, will filter the properties by names and values - * containing this query string. The match is not case-sensitive. - * Regarding value filtering it just compare to the stringification - * of the property value. - */ -function PropertyIteratorActor(objectActor, options) { - if (options.enumEntries) { - let cls = objectActor.obj.class; - if (cls == "Map") { - this.iterator = enumMapEntries(objectActor); - } else if (cls == "WeakMap") { - this.iterator = enumWeakMapEntries(objectActor); - } else if (cls == "Set") { - this.iterator = enumSetEntries(objectActor); - } else if (cls == "WeakSet") { - this.iterator = enumWeakSetEntries(objectActor); - } else { - throw new Error("Unsupported class to enumerate entries from: " + cls); - } - } else if (options.ignoreNonIndexedProperties && !options.query) { - this.iterator = enumArrayProperties(objectActor, options); - } else { - this.iterator = enumObjectProperties(objectActor, options); - } -} - -PropertyIteratorActor.prototype = { - actorPrefix: "propertyIterator", - - grip() { - return { - type: this.actorPrefix, - actor: this.actorID, - count: this.iterator.size - }; - }, - - names({ indexes }) { - let list = []; - for (let idx of indexes) { - list.push(this.iterator.propertyName(idx)); - } - return { - names: indexes - }; - }, - - slice({ start, count }) { - let ownProperties = Object.create(null); - for (let i = start, m = start + count; i < m; i++) { - let name = this.iterator.propertyName(i); - ownProperties[name] = this.iterator.propertyDescription(i); - } - return { - ownProperties - }; - }, - - all() { - return this.slice({ start: 0, count: this.length }); - } -}; - -PropertyIteratorActor.prototype.requestTypes = { - "names": PropertyIteratorActor.prototype.names, - "slice": PropertyIteratorActor.prototype.slice, - "all": PropertyIteratorActor.prototype.all, -}; - -function enumArrayProperties(objectActor, options) { - let length = DevToolsUtils.getProperty(objectActor.obj, "length"); - if (typeof length !== "number") { - // Pseudo arrays are flagged as ArrayLike if they have - // subsequent indexed properties without having any length attribute. - length = 0; - let names = objectActor.obj.getOwnPropertyNames(); - for (let key of names) { - if (isNaN(key) || key != length++) { - break; - } - } - } - - return { - size: length, - propertyName(index) { - return index; - }, - propertyDescription(index) { - return objectActor._propertyDescriptor(index); - } - }; -} - -function enumObjectProperties(objectActor, options) { - let names = []; - try { - names = objectActor.obj.getOwnPropertyNames(); - } catch (ex) { - // Calling getOwnPropertyNames() on some wrapped native prototypes is not - // allowed: "cannot modify properties of a WrappedNative". See bug 952093. - } - - if (options.ignoreNonIndexedProperties || options.ignoreIndexedProperties) { - let length = DevToolsUtils.getProperty(objectActor.obj, "length"); - if (typeof length !== "number") { - // Pseudo arrays are flagged as ArrayLike if they have - // subsequent indexed properties without having any length attribute. - length = 0; - for (let key of names) { - if (isNaN(key) || key != length++) { - break; - } - } - } - - // It appears that getOwnPropertyNames always returns indexed properties - // first, so we can safely slice `names` for/against indexed properties. - // We do such clever operation to optimize very large array inspection, - // like webaudio buffers. - if (options.ignoreIndexedProperties) { - // Keep items after `length` index - names = names.slice(length); - } else if (options.ignoreNonIndexedProperties) { - // Remove `length` first items - names.splice(length); - } - } - - let safeGetterValues = objectActor._findSafeGetterValues(names, 0); - let safeGetterNames = Object.keys(safeGetterValues); - // Merge the safe getter values into the existing properties list. - for (let name of safeGetterNames) { - if (!names.includes(name)) { - names.push(name); - } - } - - if (options.query) { - let { query } = options; - query = query.toLowerCase(); - names = names.filter(name => { - // Filter on attribute names - if (name.toLowerCase().includes(query)) { - return true; - } - // and then on attribute values - let desc; - try { - desc = objectActor.obj.getOwnPropertyDescriptor(name); - } catch (e) { - // Calling getOwnPropertyDescriptor on wrapped native prototypes is not - // allowed (bug 560072). - } - if (desc && desc.value && - String(desc.value).includes(query)) { - return true; - } - return false; - }); - } - - if (options.sort) { - names.sort(); - } - - return { - size: names.length, - propertyName(index) { - return names[index]; - }, - propertyDescription(index) { - let name = names[index]; - let desc = objectActor._propertyDescriptor(name); - if (!desc) { - desc = safeGetterValues[name]; - } else if (name in safeGetterValues) { - // Merge the safe getter values into the existing properties list. - let { getterValue, getterPrototypeLevel } = safeGetterValues[name]; - desc.getterValue = getterValue; - desc.getterPrototypeLevel = getterPrototypeLevel; - } - return desc; - } - }; -} - -/** - * Helper function to create a grip from a Map/Set entry - */ -function gripFromEntry({ obj, hooks }, entry) { - return hooks.createValueGrip( - makeDebuggeeValueIfNeeded(obj, Cu.unwaiveXrays(entry))); -} - -function enumMapEntries(objectActor) { - // Iterating over a Map via .entries goes through various intermediate - // objects - an Iterator object, then a 2-element Array object, then the - // actual values we care about. We don't have Xrays to Iterator objects, - // so we get Opaque wrappers for them. And even though we have Xrays to - // Arrays, the semantics often deny access to the entires based on the - // nature of the values. So we need waive Xrays for the iterator object - // and the tupes, and then re-apply them on the underlying values until - // we fix bug 1023984. - // - // Even then though, we might want to continue waiving Xrays here for the - // same reason we do so for Arrays above - this filtering behavior is likely - // to be more confusing than beneficial in the case of Object previews. - let raw = objectActor.obj.unsafeDereference(); - - let keys = [...Cu.waiveXrays(Map.prototype.keys.call(raw))]; - return { - [Symbol.iterator]: function* () { - for (let key of keys) { - let value = Map.prototype.get.call(raw, key); - yield [ key, value ].map(val => gripFromEntry(objectActor, val)); - } - }, - size: keys.length, - propertyName(index) { - return index; - }, - propertyDescription(index) { - let key = keys[index]; - let val = Map.prototype.get.call(raw, key); - return { - enumerable: true, - value: { - type: "mapEntry", - preview: { - key: gripFromEntry(objectActor, key), - value: gripFromEntry(objectActor, val) - } - } - }; - } - }; -} - -function enumWeakMapEntries(objectActor) { - // We currently lack XrayWrappers for WeakMap, so when we iterate over - // the values, the temporary iterator objects get created in the target - // compartment. However, we _do_ have Xrays to Object now, so we end up - // Xraying those temporary objects, and filtering access to |it.value| - // based on whether or not it's Xrayable and/or callable, which breaks - // the for/of iteration. - // - // This code is designed to handle untrusted objects, so we can safely - // waive Xrays on the iterable, and relying on the Debugger machinery to - // make sure we handle the resulting objects carefully. - let raw = objectActor.obj.unsafeDereference(); - let keys = Cu.waiveXrays( - ThreadSafeChromeUtils.nondeterministicGetWeakMapKeys(raw)); - - return { - [Symbol.iterator]: function* () { - for (let key of keys) { - let value = WeakMap.prototype.get.call(raw, key); - yield [ key, value ].map(val => gripFromEntry(objectActor, val)); - } - }, - size: keys.length, - propertyName(index) { - return index; - }, - propertyDescription(index) { - let key = keys[index]; - let val = WeakMap.prototype.get.call(raw, key); - return { - enumerable: true, - value: { - type: "mapEntry", - preview: { - key: gripFromEntry(objectActor, key), - value: gripFromEntry(objectActor, val) - } - } - }; - } - }; -} - -function enumSetEntries(objectActor) { - // We currently lack XrayWrappers for Set, so when we iterate over - // the values, the temporary iterator objects get created in the target - // compartment. However, we _do_ have Xrays to Object now, so we end up - // Xraying those temporary objects, and filtering access to |it.value| - // based on whether or not it's Xrayable and/or callable, which breaks - // the for/of iteration. - // - // This code is designed to handle untrusted objects, so we can safely - // waive Xrays on the iterable, and relying on the Debugger machinery to - // make sure we handle the resulting objects carefully. - let raw = objectActor.obj.unsafeDereference(); - let values = [...Cu.waiveXrays(Set.prototype.values.call(raw))]; - - return { - [Symbol.iterator]: function* () { - for (let item of values) { - yield gripFromEntry(objectActor, item); - } - }, - size: values.length, - propertyName(index) { - return index; - }, - propertyDescription(index) { - let val = values[index]; - return { - enumerable: true, - value: gripFromEntry(objectActor, val) - }; - } - }; -} - -function enumWeakSetEntries(objectActor) { - // We currently lack XrayWrappers for WeakSet, so when we iterate over - // the values, the temporary iterator objects get created in the target - // compartment. However, we _do_ have Xrays to Object now, so we end up - // Xraying those temporary objects, and filtering access to |it.value| - // based on whether or not it's Xrayable and/or callable, which breaks - // the for/of iteration. - // - // This code is designed to handle untrusted objects, so we can safely - // waive Xrays on the iterable, and relying on the Debugger machinery to - // make sure we handle the resulting objects carefully. - let raw = objectActor.obj.unsafeDereference(); - let keys = Cu.waiveXrays( - ThreadSafeChromeUtils.nondeterministicGetWeakSetKeys(raw)); - - return { - [Symbol.iterator]: function* () { - for (let item of keys) { - yield gripFromEntry(objectActor, item); - } - }, - size: keys.length, - propertyName(index) { - return index; - }, - propertyDescription(index) { - let val = keys[index]; - return { - enumerable: true, - value: gripFromEntry(objectActor, val) - }; - } - }; -} - -/** - * Functions for adding information to ObjectActor grips for the purpose of - * having customized output. This object holds arrays mapped by - * Debugger.Object.prototype.class. - * - * In each array you can add functions that take three - * arguments: - * - the ObjectActor instance and its hooks to make a preview for, - * - the grip object being prepared for the client, - * - the raw JS object after calling Debugger.Object.unsafeDereference(). This - * argument is only provided if the object is safe for reading properties and - * executing methods. See DevToolsUtils.isSafeJSObject(). - * - * Functions must return false if they cannot provide preview - * information for the debugger object, or true otherwise. - */ -DebuggerServer.ObjectActorPreviewers = { - String: [function (objectActor, grip, rawObj) { - return wrappedPrimitivePreviewer("String", String, objectActor, grip, rawObj); - }], - - Boolean: [function (objectActor, grip, rawObj) { - return wrappedPrimitivePreviewer("Boolean", Boolean, objectActor, grip, rawObj); - }], - - Number: [function (objectActor, grip, rawObj) { - return wrappedPrimitivePreviewer("Number", Number, objectActor, grip, rawObj); - }], - - Function: [function ({obj, hooks}, grip) { - if (obj.name) { - grip.name = obj.name; - } - - if (obj.displayName) { - grip.displayName = obj.displayName.substr(0, 500); - } - - if (obj.parameterNames) { - grip.parameterNames = obj.parameterNames; - } - - // Check if the developer has added a de-facto standard displayName - // property for us to use. - let userDisplayName; - try { - userDisplayName = obj.getOwnPropertyDescriptor("displayName"); - } catch (e) { - // Calling getOwnPropertyDescriptor with displayName might throw - // with "permission denied" errors for some functions. - dumpn(e); - } - - if (userDisplayName && typeof userDisplayName.value == "string" && - userDisplayName.value) { - grip.userDisplayName = hooks.createValueGrip(userDisplayName.value); - } - - let dbgGlobal = hooks.getGlobalDebugObject(); - if (dbgGlobal) { - let script = dbgGlobal.makeDebuggeeValue(obj.unsafeDereference()).script; - if (script) { - grip.location = { - url: script.url, - line: script.startLine - }; - } - } - - return true; - }], - - RegExp: [function ({obj, hooks}, grip) { - // Avoid having any special preview for the RegExp.prototype itself. - if (!obj.proto || obj.proto.class != "RegExp") { - return false; - } - - let str = RegExp.prototype.toString.call(obj.unsafeDereference()); - grip.displayString = hooks.createValueGrip(str); - return true; - }], - - Date: [function ({obj, hooks}, grip) { - let time = Date.prototype.getTime.call(obj.unsafeDereference()); - - grip.preview = { - timestamp: hooks.createValueGrip(time), - }; - return true; - }], - - Array: [function ({obj, hooks}, grip) { - let length = DevToolsUtils.getProperty(obj, "length"); - if (typeof length != "number") { - return false; - } - - grip.preview = { - kind: "ArrayLike", - length: length, - }; - - if (hooks.getGripDepth() > 1) { - return true; - } - - let raw = obj.unsafeDereference(); - let items = grip.preview.items = []; - - for (let i = 0; i < length; ++i) { - // Array Xrays filter out various possibly-unsafe properties (like - // functions, and claim that the value is undefined instead. This - // is generally the right thing for privileged code accessing untrusted - // objects, but quite confusing for Object previews. So we manually - // override this protection by waiving Xrays on the array, and re-applying - // Xrays on any indexed value props that we pull off of it. - let desc = Object.getOwnPropertyDescriptor(Cu.waiveXrays(raw), i); - if (desc && !desc.get && !desc.set) { - let value = Cu.unwaiveXrays(desc.value); - value = makeDebuggeeValueIfNeeded(obj, value); - items.push(hooks.createValueGrip(value)); - } else { - items.push(null); - } - - if (items.length == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - - return true; - }], - - Set: [function (objectActor, grip) { - let size = DevToolsUtils.getProperty(objectActor.obj, "size"); - if (typeof size != "number") { - return false; - } - - grip.preview = { - kind: "ArrayLike", - length: size, - }; - - // Avoid recursive object grips. - if (objectActor.hooks.getGripDepth() > 1) { - return true; - } - - let items = grip.preview.items = []; - for (let item of enumSetEntries(objectActor)) { - items.push(item); - if (items.length == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - - return true; - }], - - WeakSet: [function (objectActor, grip) { - let enumEntries = enumWeakSetEntries(objectActor); - - grip.preview = { - kind: "ArrayLike", - length: enumEntries.size - }; - - // Avoid recursive object grips. - if (objectActor.hooks.getGripDepth() > 1) { - return true; - } - - let items = grip.preview.items = []; - for (let item of enumEntries) { - items.push(item); - if (items.length == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - - return true; - }], - - Map: [function (objectActor, grip) { - let size = DevToolsUtils.getProperty(objectActor.obj, "size"); - if (typeof size != "number") { - return false; - } - - grip.preview = { - kind: "MapLike", - size: size, - }; - - if (objectActor.hooks.getGripDepth() > 1) { - return true; - } - - let entries = grip.preview.entries = []; - for (let entry of enumMapEntries(objectActor)) { - entries.push(entry); - if (entries.length == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - - return true; - }], - - WeakMap: [function (objectActor, grip) { - let enumEntries = enumWeakMapEntries(objectActor); - - grip.preview = { - kind: "MapLike", - size: enumEntries.size - }; - - if (objectActor.hooks.getGripDepth() > 1) { - return true; - } - - let entries = grip.preview.entries = []; - for (let entry of enumEntries) { - entries.push(entry); - if (entries.length == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - - return true; - }], - - DOMStringMap: [function ({obj, hooks}, grip, rawObj) { - if (!rawObj) { - return false; - } - - let keys = obj.getOwnPropertyNames(); - grip.preview = { - kind: "MapLike", - size: keys.length, - }; - - if (hooks.getGripDepth() > 1) { - return true; - } - - let entries = grip.preview.entries = []; - for (let key of keys) { - let value = makeDebuggeeValueIfNeeded(obj, rawObj[key]); - entries.push([key, hooks.createValueGrip(value)]); - if (entries.length == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - - return true; - }], - - Proxy: [function ({obj, hooks}, grip, rawObj) { - grip.preview = { - kind: "Object", - ownProperties: Object.create(null), - ownPropertiesLength: 2 - }; - - if (hooks.getGripDepth() > 1) { - return true; - } - - grip.preview.ownProperties[''] = {value: grip.proxyTarget}; - grip.preview.ownProperties[''] = {value: grip.proxyHandler}; - - return true; - }], -}; - -/** - * Generic previewer for classes wrapping primitives, like String, - * Number and Boolean. - * - * @param string className - * Class name to expect. - * @param object classObj - * The class to expect, eg. String. The valueOf() method of the class is - * invoked on the given object. - * @param ObjectActor objectActor - * The object actor - * @param Object grip - * The result grip to fill in - * @return Booolean true if the object was handled, false otherwise - */ -function wrappedPrimitivePreviewer(className, classObj, objectActor, grip, rawObj) { - let {obj, hooks} = objectActor; - - if (!obj.proto || obj.proto.class != className) { - return false; - } - - let v = null; - try { - v = classObj.prototype.valueOf.call(rawObj); - } catch (ex) { - // valueOf() can throw if the raw JS object is "misbehaved". - return false; - } - - if (v === null) { - return false; - } - - let canHandle = GenericObject(objectActor, grip, rawObj, className === "String"); - if (!canHandle) { - return false; - } - - grip.preview.wrappedValue = - hooks.createValueGrip(makeDebuggeeValueIfNeeded(obj, v)); - return true; -} - -function GenericObject(objectActor, grip, rawObj, specialStringBehavior = false) { - let {obj, hooks} = objectActor; - if (grip.preview || grip.displayString || hooks.getGripDepth() > 1) { - return false; - } - - let i = 0, names = []; - let preview = grip.preview = { - kind: "Object", - ownProperties: Object.create(null), - }; - - try { - names = obj.getOwnPropertyNames(); - } catch (ex) { - // Calling getOwnPropertyNames() on some wrapped native prototypes is not - // allowed: "cannot modify properties of a WrappedNative". See bug 952093. - } - - preview.ownPropertiesLength = names.length; - - let length; - if (specialStringBehavior) { - length = DevToolsUtils.getProperty(obj, "length"); - if (typeof length != "number") { - specialStringBehavior = false; - } - } - - for (let name of names) { - if (specialStringBehavior && /^[0-9]+$/.test(name)) { - let num = parseInt(name, 10); - if (num.toString() === name && num >= 0 && num < length) { - continue; - } - } - - let desc = objectActor._propertyDescriptor(name, true); - if (!desc) { - continue; - } - - preview.ownProperties[name] = desc; - if (++i == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - - if (i < OBJECT_PREVIEW_MAX_ITEMS) { - preview.safeGetterValues = objectActor._findSafeGetterValues( - Object.keys(preview.ownProperties), - OBJECT_PREVIEW_MAX_ITEMS - i); - } - - return true; -} - -// Preview functions that do not rely on the object class. -DebuggerServer.ObjectActorPreviewers.Object = [ - function TypedArray({obj, hooks}, grip) { - if (TYPED_ARRAY_CLASSES.indexOf(obj.class) == -1) { - return false; - } - - let length = DevToolsUtils.getProperty(obj, "length"); - if (typeof length != "number") { - return false; - } - - grip.preview = { - kind: "ArrayLike", - length: length, - }; - - if (hooks.getGripDepth() > 1) { - return true; - } - - let raw = obj.unsafeDereference(); - let global = Cu.getGlobalForObject(DebuggerServer); - let classProto = global[obj.class].prototype; - // The Xray machinery for TypedArrays denies indexed access on the grounds - // that it's slow, and advises callers to do a structured clone instead. - let safeView = Cu.cloneInto(classProto.subarray.call(raw, 0, - OBJECT_PREVIEW_MAX_ITEMS), global); - let items = grip.preview.items = []; - for (let i = 0; i < safeView.length; i++) { - items.push(safeView[i]); - } - - return true; - }, - - function Error({obj, hooks}, grip) { - switch (obj.class) { - case "Error": - case "EvalError": - case "RangeError": - case "ReferenceError": - case "SyntaxError": - case "TypeError": - case "URIError": - let name = DevToolsUtils.getProperty(obj, "name"); - let msg = DevToolsUtils.getProperty(obj, "message"); - let stack = DevToolsUtils.getProperty(obj, "stack"); - let fileName = DevToolsUtils.getProperty(obj, "fileName"); - let lineNumber = DevToolsUtils.getProperty(obj, "lineNumber"); - let columnNumber = DevToolsUtils.getProperty(obj, "columnNumber"); - grip.preview = { - kind: "Error", - name: hooks.createValueGrip(name), - message: hooks.createValueGrip(msg), - stack: hooks.createValueGrip(stack), - fileName: hooks.createValueGrip(fileName), - lineNumber: hooks.createValueGrip(lineNumber), - columnNumber: hooks.createValueGrip(columnNumber), - }; - return true; - default: - return false; - } - }, - - function CSSMediaRule({obj, hooks}, grip, rawObj) { - if (isWorker || !rawObj || !(rawObj instanceof Ci.nsIDOMCSSMediaRule)) { - return false; - } - grip.preview = { - kind: "ObjectWithText", - text: hooks.createValueGrip(rawObj.conditionText), - }; - return true; - }, - - function CSSStyleRule({obj, hooks}, grip, rawObj) { - if (isWorker || !rawObj || !(rawObj instanceof Ci.nsIDOMCSSStyleRule)) { - return false; - } - grip.preview = { - kind: "ObjectWithText", - text: hooks.createValueGrip(rawObj.selectorText), - }; - return true; - }, - - function ObjectWithURL({obj, hooks}, grip, rawObj) { - if (isWorker || !rawObj || !(rawObj instanceof Ci.nsIDOMCSSImportRule || - rawObj instanceof Ci.nsIDOMCSSStyleSheet || - rawObj instanceof Ci.nsIDOMLocation || - rawObj instanceof Ci.nsIDOMWindow)) { - return false; - } - - let url; - if (rawObj instanceof Ci.nsIDOMWindow && rawObj.location) { - url = rawObj.location.href; - } else if (rawObj.href) { - url = rawObj.href; - } else { - return false; - } - - grip.preview = { - kind: "ObjectWithURL", - url: hooks.createValueGrip(url), - }; - - return true; - }, - - function ArrayLike({obj, hooks}, grip, rawObj) { - if (isWorker || !rawObj || - obj.class != "DOMStringList" && - obj.class != "DOMTokenList" && - !(rawObj instanceof Ci.nsIDOMMozNamedAttrMap || - rawObj instanceof Ci.nsIDOMCSSRuleList || - rawObj instanceof Ci.nsIDOMCSSValueList || - rawObj instanceof Ci.nsIDOMFileList || - rawObj instanceof Ci.nsIDOMFontFaceList || - rawObj instanceof Ci.nsIDOMMediaList || - rawObj instanceof Ci.nsIDOMNodeList || - rawObj instanceof Ci.nsIDOMStyleSheetList)) { - return false; - } - - if (typeof rawObj.length != "number") { - return false; - } - - grip.preview = { - kind: "ArrayLike", - length: rawObj.length, - }; - - if (hooks.getGripDepth() > 1) { - return true; - } - - let items = grip.preview.items = []; - - for (let i = 0; i < rawObj.length && - items.length < OBJECT_PREVIEW_MAX_ITEMS; i++) { - let value = makeDebuggeeValueIfNeeded(obj, rawObj[i]); - items.push(hooks.createValueGrip(value)); - } - - return true; - }, - - function CSSStyleDeclaration({obj, hooks}, grip, rawObj) { - if (isWorker || !rawObj || - !(rawObj instanceof Ci.nsIDOMCSSStyleDeclaration)) { - return false; - } - - grip.preview = { - kind: "MapLike", - size: rawObj.length, - }; - - let entries = grip.preview.entries = []; - - for (let i = 0; i < OBJECT_PREVIEW_MAX_ITEMS && - i < rawObj.length; i++) { - let prop = rawObj[i]; - let value = rawObj.getPropertyValue(prop); - entries.push([prop, hooks.createValueGrip(value)]); - } - - return true; - }, - - function DOMNode({obj, hooks}, grip, rawObj) { - if (isWorker || obj.class == "Object" || !rawObj || - !(rawObj instanceof Ci.nsIDOMNode)) { - return false; - } - - let preview = grip.preview = { - kind: "DOMNode", - nodeType: rawObj.nodeType, - nodeName: rawObj.nodeName, - }; - - if (rawObj instanceof Ci.nsIDOMDocument && rawObj.location) { - preview.location = hooks.createValueGrip(rawObj.location.href); - } else if (rawObj instanceof Ci.nsIDOMDocumentFragment) { - preview.childNodesLength = rawObj.childNodes.length; - - if (hooks.getGripDepth() < 2) { - preview.childNodes = []; - for (let node of rawObj.childNodes) { - let actor = hooks.createValueGrip(obj.makeDebuggeeValue(node)); - preview.childNodes.push(actor); - if (preview.childNodes.length == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - } - } else if (rawObj instanceof Ci.nsIDOMElement) { - // Add preview for DOM element attributes. - if (rawObj instanceof Ci.nsIDOMHTMLElement) { - preview.nodeName = preview.nodeName.toLowerCase(); - } - - let i = 0; - preview.attributes = {}; - preview.attributesLength = rawObj.attributes.length; - for (let attr of rawObj.attributes) { - preview.attributes[attr.nodeName] = hooks.createValueGrip(attr.value); - } - } else if (rawObj instanceof Ci.nsIDOMAttr) { - preview.value = hooks.createValueGrip(rawObj.value); - } else if (rawObj instanceof Ci.nsIDOMText || - rawObj instanceof Ci.nsIDOMComment) { - preview.textContent = hooks.createValueGrip(rawObj.textContent); - } - - return true; - }, - - function DOMEvent({obj, hooks}, grip, rawObj) { - if (isWorker || !rawObj || !(rawObj instanceof Ci.nsIDOMEvent)) { - return false; - } - - let preview = grip.preview = { - kind: "DOMEvent", - type: rawObj.type, - properties: Object.create(null), - }; - - if (hooks.getGripDepth() < 2) { - let target = obj.makeDebuggeeValue(rawObj.target); - preview.target = hooks.createValueGrip(target); - } - - let props = []; - if (rawObj instanceof Ci.nsIDOMMouseEvent) { - props.push("buttons", "clientX", "clientY", "layerX", "layerY"); - } else if (rawObj instanceof Ci.nsIDOMKeyEvent) { - let modifiers = []; - if (rawObj.altKey) { - modifiers.push("Alt"); - } - if (rawObj.ctrlKey) { - modifiers.push("Control"); - } - if (rawObj.metaKey) { - modifiers.push("Meta"); - } - if (rawObj.shiftKey) { - modifiers.push("Shift"); - } - preview.eventKind = "key"; - preview.modifiers = modifiers; - - props.push("key", "charCode", "keyCode"); - } else if (rawObj instanceof Ci.nsIDOMTransitionEvent) { - props.push("propertyName", "pseudoElement"); - } else if (rawObj instanceof Ci.nsIDOMAnimationEvent) { - props.push("animationName", "pseudoElement"); - } else if (rawObj instanceof Ci.nsIDOMClipboardEvent) { - props.push("clipboardData"); - } - - // Add event-specific properties. - for (let prop of props) { - let value = rawObj[prop]; - if (value && (typeof value == "object" || typeof value == "function")) { - // Skip properties pointing to objects. - if (hooks.getGripDepth() > 1) { - continue; - } - value = obj.makeDebuggeeValue(value); - } - preview.properties[prop] = hooks.createValueGrip(value); - } - - // Add any properties we find on the event object. - if (!props.length) { - let i = 0; - for (let prop in rawObj) { - let value = rawObj[prop]; - if (prop == "target" || prop == "type" || value === null || - typeof value == "function") { - continue; - } - if (value && typeof value == "object") { - if (hooks.getGripDepth() > 1) { - continue; - } - value = obj.makeDebuggeeValue(value); - } - preview.properties[prop] = hooks.createValueGrip(value); - if (++i == OBJECT_PREVIEW_MAX_ITEMS) { - break; - } - } - } - - return true; - }, - - function DOMException({obj, hooks}, grip, rawObj) { - if (isWorker || !rawObj || !(rawObj instanceof Ci.nsIDOMDOMException)) { - return false; - } - - grip.preview = { - kind: "DOMException", - name: hooks.createValueGrip(rawObj.name), - message: hooks.createValueGrip(rawObj.message), - code: hooks.createValueGrip(rawObj.code), - result: hooks.createValueGrip(rawObj.result), - filename: hooks.createValueGrip(rawObj.filename), - lineNumber: hooks.createValueGrip(rawObj.lineNumber), - columnNumber: hooks.createValueGrip(rawObj.columnNumber), - }; - - return true; - }, - - function PseudoArray({obj, hooks}, grip, rawObj) { - let length; - - let keys = obj.getOwnPropertyNames(); - if (keys.length == 0) { - return false; - } - - // If no item is going to be displayed in preview, better display as sparse object. - // The first key should contain the smallest integer index (if any). - if(keys[0] >= OBJECT_PREVIEW_MAX_ITEMS) { - return false; - } - - // Pseudo-arrays should only have array indices and, optionally, a "length" property. - // Since integer indices are sorted first, check if the last property is "length". - if(keys[keys.length-1] === "length") { - keys.pop(); - length = DevToolsUtils.getProperty(obj, "length"); - } else { - // Otherwise, let length be the (presumably) greatest array index plus 1. - length = +keys[keys.length-1] + 1; - } - // Check if length is a valid array length, i.e. is a Uint32 number. - if(typeof length !== "number" || length >>> 0 !== length) { - return false; - } - - // Ensure all keys are increasing array indices smaller than length. The order is not - // guaranteed for exotic objects but, in most cases, big array indices and properties - // which are not integer indices should be at the end. Then, iterating backwards - // allows us to return earlier when the object is not completely a pseudo-array. - let prev = length; - for(let i = keys.length - 1; i >= 0; --i) { - let key = keys[i]; - let numKey = key >>> 0; // ToUint32(key) - if (numKey + '' !== key || numKey >= prev) { - return false; - } - prev = numKey; - } - - grip.preview = { - kind: "ArrayLike", - length: length, - }; - - // Avoid recursive object grips. - if (hooks.getGripDepth() > 1) { - return true; - } - - let items = grip.preview.items = []; - let numItems = Math.min(OBJECT_PREVIEW_MAX_ITEMS, length); - - for (let i = 0; i < numItems; ++i) { - let desc = obj.getOwnPropertyDescriptor(i); - if (desc && 'value' in desc) { - items.push(hooks.createValueGrip(desc.value)); - } else { - items.push(null); - } - } - - return true; - }, - - function Object(objectActor, grip, rawObj) { - return GenericObject(objectActor, grip, rawObj, /* specialStringBehavior = */ false); - }, -]; - -/** - * Get thisDebugger.Object referent's `promiseState`. - * - * @returns Object - * An object of one of the following forms: - * - { state: "pending" } - * - { state: "fulfilled", value } - * - { state: "rejected", reason } - */ -function getPromiseState(obj) { - if (obj.class != "Promise") { - throw new Error( - "Can't call `getPromiseState` on `Debugger.Object`s that don't " + - "refer to Promise objects."); - } - - let state = { state: obj.promiseState }; - if (state.state === "fulfilled") { - state.value = obj.promiseValue; - } else if (state.state === "rejected") { - state.reason = obj.promiseReason; - } - return state; -} - -/** - * Determine if a given value is non-primitive. - * - * @param Any value - * The value to test. - * @return Boolean - * Whether the value is non-primitive. - */ -function isObject(value) { - const type = typeof value; - return type == "object" ? value !== null : type == "function"; -} - -/** - * Create a function that can safely stringify Debugger.Objects of a given - * builtin type. - * - * @param Function ctor - * The builtin class constructor. - * @return Function - * The stringifier for the class. - */ -function createBuiltinStringifier(ctor) { - return obj => ctor.prototype.toString.call(obj.unsafeDereference()); -} - -/** - * Stringify a Debugger.Object-wrapped Error instance. - * - * @param Debugger.Object obj - * The object to stringify. - * @return String - * The stringification of the object. - */ -function errorStringify(obj) { - let name = DevToolsUtils.getProperty(obj, "name"); - if (name === "" || name === undefined) { - name = obj.class; - } else if (isObject(name)) { - name = stringify(name); - } - - let message = DevToolsUtils.getProperty(obj, "message"); - if (isObject(message)) { - message = stringify(message); - } - - if (message === "" || message === undefined) { - return name; - } - return name + ": " + message; -} - -/** - * Stringify a Debugger.Object based on its class. - * - * @param Debugger.Object obj - * The object to stringify. - * @return String - * The stringification for the object. - */ -function stringify(obj) { - if (obj.class == "DeadObject") { - const error = new Error("Dead object encountered."); - DevToolsUtils.reportException("stringify", error); - return ""; - } - - const stringifier = stringifiers[obj.class] || stringifiers.Object; - - try { - return stringifier(obj); - } catch (e) { - DevToolsUtils.reportException("stringify", e); - return ""; - } -} - -// Used to prevent infinite recursion when an array is found inside itself. -var seen = null; - -var stringifiers = { - Error: errorStringify, - EvalError: errorStringify, - RangeError: errorStringify, - ReferenceError: errorStringify, - SyntaxError: errorStringify, - TypeError: errorStringify, - URIError: errorStringify, - Boolean: createBuiltinStringifier(Boolean), - Function: createBuiltinStringifier(Function), - Number: createBuiltinStringifier(Number), - RegExp: createBuiltinStringifier(RegExp), - String: createBuiltinStringifier(String), - Object: obj => "[object " + obj.class + "]", - Array: obj => { - // If we're at the top level then we need to create the Set for tracking - // previously stringified arrays. - const topLevel = !seen; - if (topLevel) { - seen = new Set(); - } else if (seen.has(obj)) { - return ""; - } - - seen.add(obj); - - const len = DevToolsUtils.getProperty(obj, "length"); - let string = ""; - - // The following check is only required because the debuggee could possibly - // be a Proxy and return any value. For normal objects, array.length is - // always a non-negative integer. - if (typeof len == "number" && len > 0) { - for (let i = 0; i < len; i++) { - const desc = obj.getOwnPropertyDescriptor(i); - if (desc) { - const { value } = desc; - if (value != null) { - string += isObject(value) ? stringify(value) : value; - } - } - - if (i < len - 1) { - string += ","; - } - } - } - - if (topLevel) { - seen = null; - } - - return string; - }, - DOMException: obj => { - const message = DevToolsUtils.getProperty(obj, "message") || ""; - const result = (+DevToolsUtils.getProperty(obj, "result")).toString(16); - const code = DevToolsUtils.getProperty(obj, "code"); - const name = DevToolsUtils.getProperty(obj, "name") || ""; - - return '[Exception... "' + message + '" ' + - 'code: "' + code + '" ' + - 'nsresult: "0x' + result + " (" + name + ')"]'; - }, - Promise: obj => { - const { state, value, reason } = getPromiseState(obj); - let statePreview = state; - if (state != "pending") { - const settledValue = state === "fulfilled" ? value : reason; - statePreview += ": " + (typeof settledValue === "object" && settledValue !== null - ? stringify(settledValue) - : settledValue); - } - return "Promise (" + statePreview + ")"; - }, -}; - -/** - * Make a debuggee value for the given object, if needed. Primitive values - * are left the same. - * - * Use case: you have a raw JS object (after unsafe dereference) and you want to - * send it to the client. In that case you need to use an ObjectActor which - * requires a debuggee value. The Debugger.Object.prototype.makeDebuggeeValue() - * method works only for JS objects and functions. - * - * @param Debugger.Object obj - * @param any value - * @return object - */ -function makeDebuggeeValueIfNeeded(obj, value) { - if (value && (typeof value == "object" || typeof value == "function")) { - return obj.makeDebuggeeValue(value); - } - return value; -} - -/** - * Creates an actor for the specied "very long" string. "Very long" is specified - * at the server's discretion. - * - * @param string String - * The string. - */ -function LongStringActor(string) { - this.string = string; - this.stringLength = string.length; -} - -LongStringActor.prototype = { - actorPrefix: "longString", - - disconnect: function () { - // Because longStringActors is not a weak map, we won't automatically leave - // it so we need to manually leave on disconnect so that we don't leak - // memory. - this._releaseActor(); - }, - - /** - * Returns a grip for this actor for returning in a protocol message. - */ - grip: function () { - return { - "type": "longString", - "initial": this.string.substring( - 0, DebuggerServer.LONG_STRING_INITIAL_LENGTH), - "length": this.stringLength, - "actor": this.actorID - }; - }, - - /** - * Handle a request to extract part of this actor's string. - * - * @param request object - * The protocol request object. - */ - onSubstring: function (request) { - return { - "from": this.actorID, - "substring": this.string.substring(request.start, request.end) - }; - }, - - /** - * Handle a request to release this LongStringActor instance. - */ - onRelease: function () { - // TODO: also check if registeredPool === threadActor.threadLifetimePool - // when the web console moves aray from manually releasing pause-scoped - // actors. - this._releaseActor(); - this.registeredPool.removeActor(this); - return {}; - }, - - _releaseActor: function () { - if (this.registeredPool && this.registeredPool.longStringActors) { - delete this.registeredPool.longStringActors[this.string]; - } - } -}; - -LongStringActor.prototype.requestTypes = { - "substring": LongStringActor.prototype.onSubstring, - "release": LongStringActor.prototype.onRelease -}; - -/** - * Create a grip for the given debuggee value. If the value is an - * object, will create an actor with the given lifetime. - */ -function createValueGrip(value, pool, makeObjectGrip) { - switch (typeof value) { - case "boolean": - return value; - - case "string": - if (stringIsLong(value)) { - return longStringGrip(value, pool); - } - return value; - - case "number": - if (value === Infinity) { - return { type: "Infinity" }; - } else if (value === -Infinity) { - return { type: "-Infinity" }; - } else if (Number.isNaN(value)) { - return { type: "NaN" }; - } else if (!value && 1 / value === -Infinity) { - return { type: "-0" }; - } - return value; - - case "undefined": - return { type: "undefined" }; - - case "object": - if (value === null) { - return { type: "null" }; - } - else if (value.optimizedOut || - value.uninitialized || - value.missingArguments) { - // The slot is optimized out, an uninitialized binding, or - // arguments on a dead scope - return { - type: "null", - optimizedOut: value.optimizedOut, - uninitialized: value.uninitialized, - missingArguments: value.missingArguments - }; - } - return makeObjectGrip(value, pool); - - case "symbol": - let form = { - type: "symbol" - }; - let name = getSymbolName(value); - if (name !== undefined) { - form.name = createValueGrip(name, pool, makeObjectGrip); - } - return form; - - default: - assert(false, "Failed to provide a grip for: " + value); - return null; - } -} - -// const symbolProtoToString = Symbol.prototype.toString; - -// function getSymbolName(symbol) { -// const name = symbolProtoToString.call(symbol).slice("Symbol(".length, -1); -// return name || undefined; -// } - -/** - * Returns true if the string is long enough to use a LongStringActor instead - * of passing the value directly over the protocol. - * - * @param str String - * The string we are checking the length of. - */ -function stringIsLong(str) { - return str.length >= DebuggerServer.LONG_STRING_LENGTH; -} - -/** - * Create a grip for the given string. - * - * @param str String - * The string we are creating a grip for. - * @param pool ActorPool - * The actor pool where the new actor will be added. - */ -function longStringGrip(str, pool) { - if (!pool.longStringActors) { - pool.longStringActors = {}; - } - - if (pool.longStringActors.hasOwnProperty(str)) { - return pool.longStringActors[str].grip(); - } - - let actor = new LongStringActor(str); - pool.addActor(actor); - pool.longStringActors[str] = actor; - return actor.grip(); -} - -// exports.ObjectActor = ObjectActor; -// exports.PropertyIteratorActor = PropertyIteratorActor; -// exports.LongStringActor = LongStringActor; -// exports.createValueGrip = createValueGrip; -// exports.stringIsLong = stringIsLong; -// exports.longStringGrip = longStringGrip; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/root.js b/native/cocos/scripting/js-bindings/script/debugger/actors/root.js deleted file mode 100755 index e5f5b85326..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/root.js +++ /dev/null @@ -1,536 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// const { Cc, Ci, Cu } = require("chrome"); -// const Services = require("Services"); -// const { ActorPool, appendExtraActors, createExtraActors } = require("devtools/server/actors/common"); -// const { DebuggerServer } = require("devtools/server/main"); - -// loader.lazyGetter(this, "ppmm", () => { -// return Cc["@mozilla.org/parentprocessmessagemanager;1"].getService(Ci.nsIMessageBroadcaster); -// }); - -/* Root actor for the remote debugging protocol. */ - -/** - * Create a remote debugging protocol root actor. - * - * @param aConnection - * The DebuggerServerConnection whose root actor we are constructing. - * - * @param aParameters - * The properties of |aParameters| provide backing objects for the root - * actor's requests; if a given property is omitted from |aParameters|, the - * root actor won't implement the corresponding requests or notifications. - * Supported properties: - * - * - tabList: a live list (see below) of tab actors. If present, the - * new root actor supports the 'listTabs' request, providing the live - * list's elements as its tab actors, and sending 'tabListChanged' - * notifications when the live list's contents change. One actor in - * this list must have a true '.selected' property. - * - * - addonList: a live list (see below) of addon actors. If present, the - * new root actor supports the 'listAddons' request, providing the live - * list's elements as its addon actors, and sending 'addonListchanged' - * notifications when the live list's contents change. - * - * - globalActorFactories: an object |A| describing further actors to - * attach to the 'listTabs' reply. This is the type accumulated by - * DebuggerServer.addGlobalActor. For each own property |P| of |A|, - * the root actor adds a property named |P| to the 'listTabs' - * reply whose value is the name of an actor constructed by - * |A[P]|. - * - * - onShutdown: a function to call when the root actor is disconnected. - * - * Instance properties: - * - * - applicationType: the string the root actor will include as the - * "applicationType" property in the greeting packet. By default, this - * is "browser". - * - * Live lists: - * - * A "live list", as used for the |tabList|, is an object that presents a - * list of actors, and also notifies its clients of changes to the list. A - * live list's interface is two properties: - * - * - getList: a method that returns a promise to the contents of the list. - * - * - onListChanged: a handler called, with no arguments, when the set of - * values the iterator would produce has changed since the last - * time 'iterator' was called. This may only be set to null or a - * callable value (one for which the typeof operator returns - * 'function'). (Note that the live list will not call the - * onListChanged handler until the list has been iterated over - * once; if nobody's seen the list in the first place, nobody - * should care if its contents have changed!) - * - * When the list changes, the list implementation should ensure that any - * actors yielded in previous iterations whose referents (tabs) still exist - * get yielded again in subsequent iterations. If the underlying referent - * is the same, the same actor should be presented for it. - * - * The root actor registers an 'onListChanged' handler on the appropriate - * list when it may need to send the client 'tabListChanged' notifications, - * and is careful to remove the handler whenever it does not need to send - * such notifications (including when it is disconnected). This means that - * live list implementations can use the state of the handler property (set - * or null) to install and remove observers and event listeners. - * - * Note that, as the only way for the root actor to see the members of the - * live list is to begin an iteration over the list, the live list need not - * actually produce any actors until they are reached in the course of - * iteration: alliterative lazy live lists. - */ - -function RootActor(aConnection, aParameters) { - this.conn = aConnection; - this._parameters = aParameters; - this._onTabListChanged = this.onTabListChanged.bind(this); - this._onAddonListChanged = this.onAddonListChanged.bind(this); - this._onWorkerListChanged = this.onWorkerListChanged.bind(this); - this._onServiceWorkerRegistrationListChanged = this.onServiceWorkerRegistrationListChanged.bind(this); - this._onProcessListChanged = this.onProcessListChanged.bind(this); - this._extraActors = {}; - - this._globalActorPool = new ActorPool(this.conn); - this.conn.addActorPool(this._globalActorPool); - - this._chromeActor = null; -} - -RootActor.prototype = { - constructor: RootActor, - applicationType: "browser", - - traits: { - sources: true, - // Whether the inspector actor allows modifying outer HTML. - editOuterHTML: true, - // Whether the inspector actor allows modifying innerHTML and inserting - // adjacent HTML. - pasteHTML: true, - // Whether the server-side highlighter actor exists and can be used to - // remotely highlight nodes (see server/actors/highlighters.js) - highlightable: true, - // Which custom highlighter does the server-side highlighter actor supports? - // (see server/actors/highlighters.js) - customHighlighters: true, - // Whether the inspector actor implements the getImageDataFromURL - // method that returns data-uris for image URLs. This is used for image - // tooltips for instance - urlToImageDataResolver: true, - networkMonitor: true, - // Whether the storage inspector actor to inspect cookies, etc. - storageInspector: true, - // Whether storage inspector is read only - storageInspectorReadOnly: true, - // Whether conditional breakpoints are supported - conditionalBreakpoints: true, - // Whether the server supports full source actors (breakpoints on - // eval scripts, etc) - debuggerSourceActors: true, - bulk: true, - // Whether the style rule actor implements the modifySelector method - // that modifies the rule's selector - selectorEditable: true, - // Whether the page style actor implements the addNewRule method that - // adds new rules to the page - addNewRule: true, - // Whether the dom node actor implements the getUniqueSelector method - getUniqueSelector: true, - // Whether the director scripts are supported - directorScripts: true, - // Whether the debugger server supports - // blackboxing/pretty-printing (not supported in Fever Dream yet) - noBlackBoxing: false, - noPrettyPrinting: false, - // Whether the page style actor implements the getUsedFontFaces method - // that returns the font faces used on a node - getUsedFontFaces: true, - // Trait added in Gecko 38, indicating that all features necessary for - // grabbing allocations from the MemoryActor are available for the performance tool - memoryActorAllocations: true, - // Added in Gecko 40, indicating that the backend isn't stupid about - // sending resumption packets on tab navigation. - noNeedToFakeResumptionOnNavigation: true, - // Added in Firefox 40. Indicates that the backend supports registering custom - // commands through the WebConsoleCommands API. - webConsoleCommands: true, - // Whether root actor exposes tab actors - // if allowChromeProcess is true, you can fetch a ChromeActor instance - // to debug chrome and any non-content ressource via getProcess request - // if allocChromeProcess is defined, but not true, it means that root actor - // no longer expose tab actors, but also that getProcess forbids - // exposing actors for security reasons - get allowChromeProcess() { - return DebuggerServer.allowChromeProcess; - }, - // Whether or not `getProfile()` supports specifying a `startTime` - // and `endTime` to filter out samples. Fx40+ - profilerDataFilterable: true, - // Whether or not the MemoryActor's heap snapshot abilities are - // fully equipped to handle heap snapshots for the memory tool. Fx44+ - heapSnapshots: true, - // Whether or not the timeline actor can emit DOMContentLoaded and Load - // markers, currently in use by the network monitor. Fx45+ - documentLoadingMarkers: true - }, - - /** - * Return a 'hello' packet as specified by the Remote Debugging Protocol. - */ - sayHello: function () { - return { - from: this.actorID, - applicationType: this.applicationType, - /* This is not in the spec, but it's used by tests. */ - testConnectionPrefix: this.conn.prefix, - traits: this.traits - }; - }, - - forwardingCancelled: function (prefix) { - return { - from: this.actorID, - type: "forwardingCancelled", - prefix, - }; - }, - - /** - * Disconnects the actor from the browser window. - */ - disconnect: function () { - /* Tell the live lists we aren't watching any more. */ - if (this._parameters.tabList) { - this._parameters.tabList.onListChanged = null; - } - if (this._parameters.addonList) { - this._parameters.addonList.onListChanged = null; - } - if (this._parameters.workerList) { - this._parameters.workerList.onListChanged = null; - } - if (this._parameters.serviceWorkerRegistrationList) { - this._parameters.serviceWorkerRegistrationList.onListChanged = null; - } - if (typeof this._parameters.onShutdown === "function") { - this._parameters.onShutdown(); - } - this._extraActors = null; - this.conn = null; - this._tabActorPool = null; - this._globalActorPool = null; - this._parameters = null; - this._chromeActor = null; - }, - - /* The 'listTabs' request and the 'tabListChanged' notification. */ - - /** - * Handles the listTabs request. The actors will survive until at least - * the next listTabs request. - */ - onListTabs: function () { - let tabList = this._parameters.tabList; - if (!tabList) { - return { from: this.actorID, error: "noTabs", - message: "This root actor has no browser tabs." }; - } - - /* - * Walk the tab list, accumulating the array of tab actors for the - * reply, and moving all the actors to a new ActorPool. We'll - * replace the old tab actor pool with the one we build here, thus - * retiring any actors that didn't get listed again, and preparing any - * new actors to receive packets. - */ - let newActorPool = new ActorPool(this.conn); - let tabActorList = []; - let selected; - return tabList.getList().then((tabActors) => { - for (let tabActor of tabActors) { - if (tabActor.selected) { - selected = tabActorList.length; - } - tabActor.parentID = this.actorID; - newActorPool.addActor(tabActor); - tabActorList.push(tabActor); - } - /* DebuggerServer.addGlobalActor support: create actors. */ - if (!this._globalActorPool) { - this._globalActorPool = new ActorPool(this.conn); - this.conn.addActorPool(this._globalActorPool); - } - // this._createExtraActors(this._parameters.globalActorFactories, this._globalActorPool); - /* - * Drop the old actorID -> actor map. Actors that still mattered were - * added to the new map; others will go away. - */ - if (this._tabActorPool) { - this.conn.removeActorPool(this._tabActorPool); - } - this._tabActorPool = newActorPool; - this.conn.addActorPool(this._tabActorPool); - - let reply = { - "from": this.actorID, - "selected": selected || 0, - "tabs": tabActorList.map(actor => actor.form()) - }; - - /* If a root window is accessible, include its URL. */ - if (this.url) { - reply.url = this.url; - } - - /* DebuggerServer.addGlobalActor support: name actors in 'listTabs' reply. */ - // this._appendExtraActors(reply); - - /* - * Now that we're actually going to report the contents of tabList to - * the client, we're responsible for letting the client know if it - * changes. - */ - tabList.onListChanged = this._onTabListChanged; - - return reply; - }); - }, - - onGetTab: function (options) { - let tabList = this._parameters.tabList; - if (!tabList) { - return { error: "noTabs", - message: "This root actor has no browser tabs." }; - } - if (!this._tabActorPool) { - this._tabActorPool = new ActorPool(this.conn); - this.conn.addActorPool(this._tabActorPool); - } - return tabList.getTab(options) - .then(tabActor => { - tabActor.parentID = this.actorID; - this._tabActorPool.addActor(tabActor); - - return { tab: tabActor.form() }; - }, error => { - if (error.error) { - // Pipe expected errors as-is to the client - return error; - } else { - return { error: "noTab", - message: "Unexpected error while calling getTab(): " + error }; - } - }); - }, - - onTabListChanged: function () { - this.conn.send({ from: this.actorID, type:"tabListChanged" }); - /* It's a one-shot notification; no need to watch any more. */ - this._parameters.tabList.onListChanged = null; - }, - - onListAddons: function () { - let addonList = this._parameters.addonList; - if (!addonList) { - return { from: this.actorID, error: "noAddons", - message: "This root actor has no browser addons." }; - } - - return addonList.getList().then((addonActors) => { - let addonActorPool = new ActorPool(this.conn); - for (let addonActor of addonActors) { - addonActorPool.addActor(addonActor); - } - - if (this._addonActorPool) { - this.conn.removeActorPool(this._addonActorPool); - } - this._addonActorPool = addonActorPool; - this.conn.addActorPool(this._addonActorPool); - - addonList.onListChanged = this._onAddonListChanged; - - return { - "from": this.actorID, - "addons": addonActors.map(addonActor => addonActor.form()) - }; - }); - }, - - onAddonListChanged: function () { - this.conn.send({ from: this.actorID, type: "addonListChanged" }); - this._parameters.addonList.onListChanged = null; - }, - - onListWorkers: function () { - let workerList = this._parameters.workerList; - if (!workerList) { - return { from: this.actorID, error: "noWorkers", - message: "This root actor has no workers." }; - } - - return workerList.getList().then(actors => { - let pool = new ActorPool(this.conn); - for (let actor of actors) { - pool.addActor(actor); - } - - this.conn.removeActorPool(this._workerActorPool); - this._workerActorPool = pool; - this.conn.addActorPool(this._workerActorPool); - - workerList.onListChanged = this._onWorkerListChanged; - - return { - "from": this.actorID, - "workers": actors.map(actor => actor.form()) - }; - }); - }, - - onWorkerListChanged: function () { - this.conn.send({ from: this.actorID, type: "workerListChanged" }); - this._parameters.workerList.onListChanged = null; - }, - - onListServiceWorkerRegistrations: function () { - let registrationList = this._parameters.serviceWorkerRegistrationList; - if (!registrationList) { - return { from: this.actorID, error: "noServiceWorkerRegistrations", - message: "This root actor has no service worker registrations." }; - } - - return registrationList.getList().then(actors => { - let pool = new ActorPool(this.conn); - for (let actor of actors) { - pool.addActor(actor); - } - - this.conn.removeActorPool(this._serviceWorkerRegistrationActorPool); - this._serviceWorkerRegistrationActorPool = pool; - this.conn.addActorPool(this._serviceWorkerRegistrationActorPool); - - registrationList.onListChanged = this._onServiceWorkerRegistrationListChanged; - - return { - "from": this.actorID, - "registrations": actors.map(actor => actor.form()) - }; - }); - }, - - onServiceWorkerRegistrationListChanged: function () { - this.conn.send({ from: this.actorID, type: "serviceWorkerRegistrationListChanged" }); - this._parameters.serviceWorkerRegistrationList.onListChanged = null; - }, - - onListProcesses: function () { - let { processList } = this._parameters; - if (!processList) { - return { from: this.actorID, error: "noProcesses", - message: "This root actor has no processes." }; - } - processList.onListChanged = this._onProcessListChanged; - return { - processes: processList.getList() - }; - }, - - onProcessListChanged: function () { - this.conn.send({ from: this.actorID, type: "processListChanged" }); - this._parameters.processList.onListChanged = null; - }, - - onGetProcess: function (aRequest) { - if (!DebuggerServer.allowChromeProcess) { - return { error: "forbidden", - message: "You are not allowed to debug chrome." }; - } - if (("id" in aRequest) && typeof (aRequest.id) != "number") { - return { error: "wrongParameter", - message: "getProcess requires a valid `id` attribute." }; - } - // If the request doesn't contains id parameter or id is 0 - // (id == 0, based on onListProcesses implementation) - if ((!("id" in aRequest)) || aRequest.id === 0) { - if (!this._chromeActor) { - // Create a ChromeActor for the parent process - let { ChromeActor } = require("devtools/server/actors/chrome"); - this._chromeActor = new ChromeActor(this.conn); - this._globalActorPool.addActor(this._chromeActor); - } - - return { form: this._chromeActor.form() }; - } else { - let mm = ppmm.getChildAt(aRequest.id); - if (!mm) { - return { error: "noProcess", - message: "There is no process with id '" + aRequest.id + "'." }; - } - return DebuggerServer.connectToContent(this.conn, mm) - .then(form => ({ form })); - } - }, - - /* This is not in the spec, but it's used by tests. */ - onEcho: function (aRequest) { - /* - * Request packets are frozen. Copy aRequest, so that - * DebuggerServerConnection.onPacket can attach a 'from' property. - */ - return Cu.cloneInto(aRequest, {}); - }, - - onProtocolDescription: function () { - return require("devtools/shared/protocol").dumpProtocolSpec(); - }, - - /* Support for DebuggerServer.addGlobalActor. */ - // _createExtraActors: createExtraActors, - // _appendExtraActors: appendExtraActors, - - /** - * Remove the extra actor (added by DebuggerServer.addGlobalActor or - * DebuggerServer.addTabActor) name |aName|. - */ - removeActorByName: function (aName) { - if (aName in this._extraActors) { - const actor = this._extraActors[aName]; - if (this._globalActorPool.has(actor)) { - this._globalActorPool.removeActor(actor); - } - if (this._tabActorPool) { - // Iterate over TabActor instances to also remove tab actors - // created during listTabs for each document. - this._tabActorPool.forEach(tab => { - tab.removeActorByName(aName); - }); - } - delete this._extraActors[aName]; - } - } -}; - -RootActor.prototype.requestTypes = { - "listTabs": RootActor.prototype.onListTabs, - "getTab": RootActor.prototype.onGetTab, - "listAddons": RootActor.prototype.onListAddons, - "listWorkers": RootActor.prototype.onListWorkers, - "listServiceWorkerRegistrations": RootActor.prototype.onListServiceWorkerRegistrations, - "listProcesses": RootActor.prototype.onListProcesses, - "getProcess": RootActor.prototype.onGetProcess, - "echo": RootActor.prototype.onEcho, - "protocolDescription": RootActor.prototype.onProtocolDescription -}; - -// exports.RootActor = RootActor; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/script.js b/native/cocos/scripting/js-bindings/script/debugger/actors/script.js deleted file mode 100755 index c9fa8b6fff..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/script.js +++ /dev/null @@ -1,2372 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// const Services = require("Services"); -// const { Cc, Ci, Cu, Cr, components, ChromeWorker } = require("chrome"); -// const { ActorPool, OriginalLocation, GeneratedLocation } = require("devtools/server/actors/common"); -// const { BreakpointActor, setBreakpointAtEntryPoints } = require("devtools/server/actors/breakpoint"); -// const { EnvironmentActor } = require("devtools/server/actors/environment"); -// const { FrameActor } = require("devtools/server/actors/frame"); -// const { ObjectActor, createValueGrip, longStringGrip } = require("devtools/server/actors/object"); -// const { SourceActor, getSourceURL } = require("devtools/server/actors/source"); -// const { DebuggerServer } = require("devtools/server/main"); -// const { ActorClassWithSpec } = require("devtools/shared/protocol"); -// const DevToolsUtils = require("devtools/shared/DevToolsUtils"); -// const flags = require("devtools/shared/flags"); -const { assert, dumpn, update, fetch } = DevToolsUtils; -// const promise = require("promise"); -// const xpcInspector = require("xpcInspector"); -// const { DevToolsWorker } = require("devtools/shared/worker/worker"); -// const object = require("sdk/util/object"); -// const { threadSpec } = require("devtools/shared/specs/script"); - -// const { defer, resolve, reject, all } = promise; - -// loader.lazyGetter(this, "Debugger", () => { -// let Debugger = require("Debugger"); -// hackDebugger(Debugger); -// return Debugger; -// }); -// loader.lazyRequireGetter(this, "CssLogic", "devtools/server/css-logic", true); -// loader.lazyRequireGetter(this, "events", "sdk/event/core"); -// loader.lazyRequireGetter(this, "mapURIToAddonID", "devtools/server/actors/utils/map-uri-to-addon-id"); - -/** - * A BreakpointActorMap is a map from locations to instances of BreakpointActor. - */ -function BreakpointActorMap() { - this._size = 0; - this._actors = {}; -} - -BreakpointActorMap.prototype = { - /** - * Return the number of BreakpointActors in this BreakpointActorMap. - * - * @returns Number - * The number of BreakpointActor in this BreakpointActorMap. - */ - get size() { - return this._size; - }, - - /** - * Generate all BreakpointActors that match the given location in - * this BreakpointActorMap. - * - * @param OriginalLocation location - * The location for which matching BreakpointActors should be generated. - */ - findActors: function* (location = new OriginalLocation()) { - // Fast shortcut for when we know we won't find any actors. Surprisingly - // enough, this speeds up refreshing when there are no breakpoints set by - // about 2x! - if (this.size === 0) { - return; - } - - function* findKeys(object, key) { - if (key !== undefined) { - if (key in object) { - yield key; - } - } - else { - for (let key of Object.keys(object)) { - yield key; - } - } - } - - let query = { - sourceActorID: location.originalSourceActor ? location.originalSourceActor.actorID : undefined, - line: location.originalLine, - }; - - // If location contains a line, assume we are searching for a whole line - // breakpoint, and set begin/endColumn accordingly. Otherwise, we are - // searching for all breakpoints, so begin/endColumn should be left unset. - if (location.originalLine) { - query.beginColumn = location.originalColumn ? location.originalColumn : 0; - query.endColumn = location.originalColumn ? location.originalColumn + 1 : Infinity; - } else { - query.beginColumn = location.originalColumn ? query.originalColumn : undefined; - query.endColumn = location.originalColumn ? query.originalColumn + 1 : undefined; - } - - for (let sourceActorID of findKeys(this._actors, query.sourceActorID)) - for (let line of findKeys(this._actors[sourceActorID], query.line)) - for (let beginColumn of findKeys(this._actors[sourceActorID][line], query.beginColumn)) - for (let endColumn of findKeys(this._actors[sourceActorID][line][beginColumn], query.endColumn)) { - yield this._actors[sourceActorID][line][beginColumn][endColumn]; - } - }, - - /** - * Return the BreakpointActor at the given location in this - * BreakpointActorMap. - * - * @param OriginalLocation location - * The location for which the BreakpointActor should be returned. - * - * @returns BreakpointActor actor - * The BreakpointActor at the given location. - */ - getActor: function (originalLocation) { - for (let actor of this.findActors(originalLocation)) { - return actor; - } - - return null; - }, - - /** - * Set the given BreakpointActor to the given location in this - * BreakpointActorMap. - * - * @param OriginalLocation location - * The location to which the given BreakpointActor should be set. - * - * @param BreakpointActor actor - * The BreakpointActor to be set to the given location. - */ - setActor: function (location, actor) { - let { originalSourceActor, originalLine, originalColumn } = location; - - let sourceActorID = originalSourceActor.actorID; - let line = originalLine; - let beginColumn = originalColumn ? originalColumn : 0; - let endColumn = originalColumn ? originalColumn + 1 : Infinity; - - if (!this._actors[sourceActorID]) { - this._actors[sourceActorID] = []; - } - if (!this._actors[sourceActorID][line]) { - this._actors[sourceActorID][line] = []; - } - if (!this._actors[sourceActorID][line][beginColumn]) { - this._actors[sourceActorID][line][beginColumn] = []; - } - if (!this._actors[sourceActorID][line][beginColumn][endColumn]) { - ++this._size; - } - this._actors[sourceActorID][line][beginColumn][endColumn] = actor; - }, - - /** - * Delete the BreakpointActor from the given location in this - * BreakpointActorMap. - * - * @param OriginalLocation location - * The location from which the BreakpointActor should be deleted. - */ - deleteActor: function (location) { - let { originalSourceActor, originalLine, originalColumn } = location; - - let sourceActorID = originalSourceActor.actorID; - let line = originalLine; - let beginColumn = originalColumn ? originalColumn : 0; - let endColumn = originalColumn ? originalColumn + 1 : Infinity; - - if (this._actors[sourceActorID]) { - if (this._actors[sourceActorID][line]) { - if (this._actors[sourceActorID][line][beginColumn]) { - if (this._actors[sourceActorID][line][beginColumn][endColumn]) { - --this._size; - } - delete this._actors[sourceActorID][line][beginColumn][endColumn]; - if (Object.keys(this._actors[sourceActorID][line][beginColumn]).length === 0) { - delete this._actors[sourceActorID][line][beginColumn]; - } - } - if (Object.keys(this._actors[sourceActorID][line]).length === 0) { - delete this._actors[sourceActorID][line]; - } - } - } - } -}; - -// exports.BreakpointActorMap = BreakpointActorMap; - -/** - * Keeps track of persistent sources across reloads and ties different - * source instances to the same actor id so that things like - * breakpoints survive reloads. ThreadSources uses this to force the - * same actorID on a SourceActor. - */ -function SourceActorStore() { - // source identifier --> actor id - this._sourceActorIds = Object.create(null); -} - -SourceActorStore.prototype = { - /** - * Lookup an existing actor id that represents this source, if available. - */ - getReusableActorId: function (aSource, aOriginalUrl) { - let url = this.getUniqueKey(aSource, aOriginalUrl); - if (url && url in this._sourceActorIds) { - return this._sourceActorIds[url]; - } - return null; - }, - - /** - * Update a source with an actorID. - */ - setReusableActorId: function (aSource, aOriginalUrl, actorID) { - let url = this.getUniqueKey(aSource, aOriginalUrl); - if (url) { - this._sourceActorIds[url] = actorID; - } - }, - - /** - * Make a unique URL from a source that identifies it across reloads. - */ - getUniqueKey: function (aSource, aOriginalUrl) { - if (aOriginalUrl) { - // Original source from a sourcemap. - return aOriginalUrl; - } - else { - return getSourceURL(aSource); - } - } -}; - -// exports.SourceActorStore = SourceActorStore; - -/** - * Manages pushing event loops and automatically pops and exits them in the - * correct order as they are resolved. - * - * @param ThreadActor thread - * The thread actor instance that owns this EventLoopStack. - * @param DebuggerServerConnection connection - * The remote protocol connection associated with this event loop stack. - * @param Object hooks - * An object with the following properties: - * - url: The URL string of the debuggee we are spinning an event loop - * for. - * - preNest: function called before entering a nested event loop - * - postNest: function called after exiting a nested event loop - */ -function EventLoopStack({ thread, connection, hooks }) { - this._hooks = hooks; - this._thread = thread; - this._connection = connection; -} - -EventLoopStack.prototype = { - /** - * The number of nested event loops on the stack. - */ - get size() { - // return xpcInspector.eventLoopNestLevel; - return _getEventLoopNestLevel(); - }, - - /** - * The URL of the debuggee who pushed the event loop on top of the stack. - */ - get lastPausedUrl() { - let url = null; - if (this.size > 0) { - try { - url = xpcInspector.lastNestRequestor.url; - } catch (e) { - // The tab's URL getter may throw if the tab is destroyed by the time - // this code runs, but we don't really care at this point. - dumpn(e); - } - } - return url; - }, - - /** - * The DebuggerServerConnection of the debugger who pushed the event loop on - * top of the stack - */ - get lastConnection() { - return xpcInspector.lastNestRequestor._connection; - }, - - /** - * Push a new nested event loop onto the stack. - * - * @returns EventLoop - */ - push: function () { - return new EventLoop({ - thread: this._thread, - connection: this._connection, - hooks: this._hooks - }); - } -}; - -/** - * An object that represents a nested event loop. It is used as the nest - * requestor with nsIJSInspector instances. - * - * @param ThreadActor thread - * The thread actor that is creating this nested event loop. - * @param DebuggerServerConnection connection - * The remote protocol connection associated with this event loop. - * @param Object hooks - * The same hooks object passed into EventLoopStack during its - * initialization. - */ -function EventLoop({ thread, connection, hooks }) { - this._thread = thread; - this._hooks = hooks; - this._connection = connection; - - this.enter = this.enter.bind(this); - this.resolve = this.resolve.bind(this); -} - -EventLoop.prototype = { - entered: false, - resolved: false, - get url() { return this._hooks.url; }, - - /** - * Enter this nested event loop. - */ - enter: function () { - let nestData = this._hooks.preNest - ? this._hooks.preNest() - : null; - - this.entered = true; - // xpcInspector.enterNestedEventLoop(this); - _enterNestedEventLoop(); - - // Keep exiting nested event loops while the last requestor is resolved. - // if (xpcInspector.eventLoopNestLevel > 0) { - // const { resolved } = xpcInspector.lastNestRequestor; - // if (resolved) { - // xpcInspector.exitNestedEventLoop(); - // } - // } - - if (this._hooks.postNest) { - this._hooks.postNest(nestData); - } - }, - - /** - * Resolve this nested event loop. - * - * @returns boolean - * True if we exited this nested event loop because it was on top of - * the stack, false if there is another nested event loop above this - * one that hasn't resolved yet. - */ - resolve: function () { - if (!this.entered) { - throw new Error("Can't resolve an event loop before it has been entered!"); - } - if (this.resolved) { - throw new Error("Already resolved this nested event loop!"); - } - this.resolved = true; - // if (this === xpcInspector.lastNestRequestor) - { - // xpcInspector.exitNestedEventLoop(); - _exitNestedEventLoop(); - return true; - } - return false; - }, -}; - -/** - * JSD2 actors. - */ - -/** - * Creates a ThreadActor. - * - * ThreadActors manage a JSInspector object and manage execution/inspection - * of debuggees. - * - * @param aParent object - * This |ThreadActor|'s parent actor. It must implement the following - * properties: - * - url: The URL string of the debuggee. - * - window: The global window object. - * - preNest: Function called before entering a nested event loop. - * - postNest: Function called after exiting a nested event loop. - * - makeDebugger: A function that takes no arguments and instantiates - * a Debugger that manages its globals on its own. - * @param aGlobal object [optional] - * An optional (for content debugging only) reference to the content - * window. - */ -function ThreadActor (aParent, aGlobal) { - this._state = "detached"; - this._frameActors = []; - this._parent = aParent; - this._dbg = null; - this._gripDepth = 0; - this._threadLifetimePool = null; - this._tabClosed = false; - this._scripts = null; - this._pauseOnDOMEvents = null; - - this._options = { - useSourceMaps: false, - autoBlackBox: false - }; - - this.breakpointActorMap = new BreakpointActorMap(); - this.sourceActorStore = new SourceActorStore(); - - this._debuggerSourcesSeen = null; - - // A map of actorID -> actor for breakpoints created and managed by the - // server. - this._hiddenBreakpoints = new Map(); - - this.global = aGlobal; - - this._allEventsListener = this._allEventsListener.bind(this); - this.onNewGlobal = this.onNewGlobal.bind(this); - this.onSourceEvent = this.onSourceEvent.bind(this); - this.uncaughtExceptionHook = this.uncaughtExceptionHook.bind(this); - this.onDebuggerStatement = this.onDebuggerStatement.bind(this); - this.onNewScript = this.onNewScript.bind(this); - this.objectGrip = this.objectGrip.bind(this); - this.pauseObjectGrip = this.pauseObjectGrip.bind(this); - this._onWindowReady = this._onWindowReady.bind(this); - // events.on(this._parent, "window-ready", this._onWindowReady); - // Set a wrappedJSObject property so |this| can be sent via the observer svc - // for the xpcshell harness. - this.wrappedJSObject = this; -}; - -ThreadActor.prototype = { - constructor: ThreadActor, - // Used by the ObjectActor to keep track of the depth of grip() calls. - _gripDepth: null, - - get dbg() { - if (!this._dbg) { - this._dbg = this._parent.makeDebugger(); - this._dbg.uncaughtExceptionHook = this.uncaughtExceptionHook; - this._dbg.onDebuggerStatement = this.onDebuggerStatement; - this._dbg.onNewScript = this.onNewScript; - // this._dbg.on("newGlobal", this.onNewGlobal); - // Keep the debugger disabled until a client attaches. - this._dbg.enabled = this._state != "detached"; - } - return this._dbg; - }, - - get globalDebugObject() { - if (!this._parent.window) { - return null; - } - return this.dbg.makeGlobalObjectReference(this._parent.window); - }, - - get state() { - return this._state; - }, - - get attached() { - return this.state == "attached" || - this.state == "running" || - this.state == "paused"; - }, - - get threadLifetimePool() { - if (!this._threadLifetimePool) { - this._threadLifetimePool = new ActorPool(this.conn); - this.conn.addActorPool(this._threadLifetimePool); - this._threadLifetimePool.objectActors = new WeakMap(); - } - return this._threadLifetimePool; - }, - - get scripts() { - if (!this._scripts) { - this._scripts = new ScriptStore(); - this._scripts.addScripts(this.dbg.findScripts()); - } - return this._scripts; - }, - - get sources() { - return this._parent.sources; - }, - - get youngestFrame() { - if (this.state != "paused") { - return null; - } - return this.dbg.getNewestFrame(); - }, - - _prettyPrintWorker: null, - get prettyPrintWorker() { - if (!this._prettyPrintWorker) { - this._prettyPrintWorker = new DevToolsWorker( - "resource://devtools/server/actors/pretty-print-worker.js", - { name: "pretty-print", - verbose: dumpn.wantLogging } - ); - } - return this._prettyPrintWorker; - }, - - /** - * Keep track of all of the nested event loops we use to pause the debuggee - * when we hit a breakpoint/debugger statement/etc in one place so we can - * resolve them when we get resume packets. We have more than one (and keep - * them in a stack) because we can pause within client evals. - */ - _threadPauseEventLoops: null, - _pushThreadPause: function () { - if (!this._threadPauseEventLoops) { - this._threadPauseEventLoops = []; - } - const eventLoop = this._nestedEventLoops.push(); - this._threadPauseEventLoops.push(eventLoop); - eventLoop.enter(); - }, - _popThreadPause: function () { - const eventLoop = this._threadPauseEventLoops.pop(); - assert(eventLoop, "Should have an event loop."); - eventLoop.resolve(); - }, - - /** - * Remove all debuggees and clear out the thread's sources. - */ - clearDebuggees: function () { - if (this._dbg) { - this.dbg.removeAllDebuggees(); - } - this._sources = null; - this._scripts = null; - }, - - /** - * Listener for our |Debugger|'s "newGlobal" event. - */ - onNewGlobal: function (aGlobal) { - // Notify the client. - this.conn.send({ - from: this.actorID, - type: "newGlobal", - // TODO: after bug 801084 lands see if we need to JSONify this. - hostAnnotations: aGlobal.hostAnnotations - }); - }, - - disconnect: function () { - dumpn("in ThreadActor.prototype.disconnect"); - if (this._state == "paused") { - this.onResume(); - } - - // Blow away our source actor ID store because those IDs are only - // valid for this connection. This is ok because we never keep - // things like breakpoints across connections. - this._sourceActorStore = null; - - // events.off(this._parent, "window-ready", this._onWindowReady); - this.sources.off("newSource", this.onSourceEvent); - this.sources.off("updatedSource", this.onSourceEvent); - this.clearDebuggees(); - this.conn.removeActorPool(this._threadLifetimePool); - this._threadLifetimePool = null; - - if (this._prettyPrintWorker) { - this._prettyPrintWorker.destroy(); - this._prettyPrintWorker = null; - } - - if (!this._dbg) { - return; - } - this._dbg.enabled = false; - this._dbg = null; - }, - - /** - * Disconnect the debugger and put the actor in the exited state. - */ - exit: function () { - this.disconnect(); - this._state = "exited"; - }, - - // Request handlers - onAttach: function (aRequest) { - if (this.state === "exited") { - return { type: "exited" }; - } - - if (this.state !== "detached") { - return { error: "wrongState", - message: "Current state is " + this.state }; - } - - this._state = "attached"; - this._debuggerSourcesSeen = new WeakSet(); - - Object.assign(this._options, aRequest.options || {}); - this.sources.setOptions(this._options); - this.sources.on("newSource", this.onSourceEvent); - this.sources.on("updatedSource", this.onSourceEvent); - - // Initialize an event loop stack. This can't be done in the constructor, - // because this.conn is not yet initialized by the actor pool at that time. - this._nestedEventLoops = new EventLoopStack({ - hooks: this._parent, - connection: this.conn, - thread: this - }); - - // this.dbg.addDebuggees(); - this.dbg.enabled = true; - try { - // Put ourselves in the paused state. - let packet = this._paused(); - if (!packet) { - return { error: "notAttached" }; - } - packet.why = { type: "attached" }; - - // Send the response to the attach request now (rather than - // returning it), because we're going to start a nested event loop - // here. - this.conn.send(packet); - - // Start a nested event loop. - this._pushThreadPause(); - - // We already sent a response to this request, don't send one - // now. - return null; - } catch (e) { - reportError(e); - return { error: "notAttached", message: e.toString() }; - } - }, - - onDetach: function (aRequest) { - this.disconnect(); - this._state = "detached"; - this._debuggerSourcesSeen = null; - - dumpn("ThreadActor.prototype.onDetach: returning 'detached' packet"); - return { - type: "detached" - }; - }, - - onReconfigure: function (aRequest) { - if (this.state == "exited") { - return { error: "wrongState" }; - } - const options = aRequest.options || {}; - - if ("observeAsmJS" in options) { - this.dbg.allowUnobservedAsmJS = !options.observeAsmJS; - } - - Object.assign(this._options, options); - - // Update the global source store -// this.sources.setOptions(options); - - return {}; - }, - - /** - * Pause the debuggee, by entering a nested event loop, and return a 'paused' - * packet to the client. - * - * @param Debugger.Frame aFrame - * The newest debuggee frame in the stack. - * @param object aReason - * An object with a 'type' property containing the reason for the pause. - * @param function onPacket - * Hook to modify the packet before it is sent. Feel free to return a - * promise. - */ - _pauseAndRespond: function (aFrame, aReason, onPacket = function (k) { return k; }) { - try { - let packet = this._paused(aFrame); - if (!packet) { - return undefined; - } - packet.why = aReason; - - let generatedLocation = this.sources.getFrameLocation(aFrame); - this.sources.getOriginalLocation(generatedLocation) - .then((originalLocation) => { - if (!originalLocation.originalSourceActor) { - // The only time the source actor will be null is if there - // was a sourcemap and it tried to look up the original - // location but there was no original URL. This is a strange - // scenario so we simply don't pause. - DevToolsUtils.reportException( - "ThreadActor", - new Error("Attempted to pause in a script with a sourcemap but " + - "could not find original location.") - ); - - return undefined; - } - - packet.frame.where = { - source: originalLocation.originalSourceActor.form(), - line: originalLocation.originalLine, - column: originalLocation.originalColumn - }; - Promise.resolve(onPacket(packet)) - .then(null, error => { - reportError(error); - return { - error: "unknownError", - message: error.message + "\n" + error.stack - }; - }) - .then(packet => { - this.conn.send(packet); - }); - }); - - this._pushThreadPause(); - } catch (e) { - reportError(e, "Got an exception during TA__pauseAndRespond: "); - } - - // If the browser tab has been closed, terminate the debuggee script - // instead of continuing. Executing JS after the content window is gone is - // a bad idea. - return this._tabClosed ? null : undefined; - }, - - _makeOnEnterFrame: function ({ pauseAndRespond }) { - return aFrame => { - const generatedLocation = this.sources.getFrameLocation(aFrame); - let { originalSourceActor } = this.unsafeSynchronize(this.sources.getOriginalLocation( - generatedLocation)); - let url = originalSourceActor.url; - - return this.sources.isBlackBoxed(url) - ? undefined - : pauseAndRespond(aFrame); - }; - }, - - _makeOnPop: function ({ thread, pauseAndRespond, createValueGrip }) { - return function (aCompletion) { - // onPop is called with 'this' set to the current frame. - - const generatedLocation = thread.sources.getFrameLocation(this); - const { originalSourceActor } = thread.unsafeSynchronize(thread.sources.getOriginalLocation( - generatedLocation)); - const url = originalSourceActor.url; - - if (thread.sources.isBlackBoxed(url)) { - return undefined; - } - - // Note that we're popping this frame; we need to watch for - // subsequent step events on its caller. - this.reportedPop = true; - - return pauseAndRespond(this, aPacket => { - aPacket.why.frameFinished = {}; - if (!aCompletion) { - aPacket.why.frameFinished.terminated = true; - } else if (aCompletion.hasOwnProperty("return")) { - aPacket.why.frameFinished.return = createValueGrip(aCompletion.return); - } else if (aCompletion.hasOwnProperty("yield")) { - aPacket.why.frameFinished.return = createValueGrip(aCompletion.yield); - } else { - aPacket.why.frameFinished.throw = createValueGrip(aCompletion.throw); - } - return aPacket; - }); - }; - }, - - _makeOnStep: function ({ thread, pauseAndRespond, startFrame, - startLocation, steppingType }) { - // Breaking in place: we should always pause. - if (steppingType === "break") { - return function () { - return pauseAndRespond(this); - }; - } - - // Otherwise take what a "step" means into consideration. - return function () { - // onStep is called with 'this' set to the current frame. - - // Only allow stepping stops at entry points for the line, when - // the stepping occurs in a single frame. The "same frame" - // check makes it so a sequence of steps can step out of a frame - // and into subsequent calls in the outer frame. E.g., if there - // is a call "a(b())" and the user steps into b, then this - // condition makes it possible to step out of b and into a. - if (this === startFrame && - !this.script.getOffsetLocation(this.offset).isEntryPoint) { - return undefined; - } - - const generatedLocation = thread.sources.getFrameLocation(this); - const newLocation = thread.unsafeSynchronize(thread.sources.getOriginalLocation( - generatedLocation)); - - // Cases when we should pause because we have executed enough to consider - // a "step" to have occured: - // - // 1.1. We change frames. - // 1.2. We change URLs (can happen without changing frames thanks to - // source mapping). - // 1.3. We change lines. - // - // Cases when we should always continue execution, even if one of the - // above cases is true: - // - // 2.1. We are in a source mapped region, but inside a null mapping - // (doesn't correlate to any region of original source) - // 2.2. The source we are in is black boxed. - - // Cases 2.1 and 2.2 - if (newLocation.originalUrl == null - || thread.sources.isBlackBoxed(newLocation.originalUrl)) { - return undefined; - } - - // Cases 1.1, 1.2 and 1.3 - if (this !== startFrame - || startLocation.originalUrl !== newLocation.originalUrl - || startLocation.originalLine !== newLocation.originalLine) { - return pauseAndRespond(this); - } - - // Otherwise, let execution continue (we haven't executed enough code to - // consider this a "step" yet). - return undefined; - }; - }, - - /** - * Define the JS hook functions for stepping. - */ - _makeSteppingHooks: function (aStartLocation, steppingType) { - // Bind these methods and state because some of the hooks are called - // with 'this' set to the current frame. Rather than repeating the - // binding in each _makeOnX method, just do it once here and pass it - // in to each function. - const steppingHookState = { - pauseAndRespond: (aFrame, onPacket = k=>k) => { - return this._pauseAndRespond(aFrame, { type: "resumeLimit" }, onPacket); - }, - createValueGrip: v => createValueGrip(v, this._pausePool, - this.objectGrip), - thread: this, - startFrame: this.youngestFrame, - startLocation: aStartLocation, - steppingType: steppingType - }; - - return { - onEnterFrame: this._makeOnEnterFrame(steppingHookState), - onPop: this._makeOnPop(steppingHookState), - onStep: this._makeOnStep(steppingHookState) - }; - }, - - /** - * Handle attaching the various stepping hooks we need to attach when we - * receive a resume request with a resumeLimit property. - * - * @param Object aRequest - * The request packet received over the RDP. - * @returns A promise that resolves to true once the hooks are attached, or is - * rejected with an error packet. - */ - _handleResumeLimit: function (aRequest) { - let steppingType = aRequest.resumeLimit.type; - if (["break", "step", "next", "finish"].indexOf(steppingType) == -1) { - return reject({ error: "badParameterType", - message: "Unknown resumeLimit type" }); - } - - const generatedLocation = this.sources.getFrameLocation(this.youngestFrame); - return this.sources.getOriginalLocation(generatedLocation) - .then(originalLocation => { - const { onEnterFrame, onPop, onStep } = this._makeSteppingHooks(originalLocation, - steppingType); - - // Make sure there is still a frame on the stack if we are to continue - // stepping. - let stepFrame = this._getNextStepFrame(this.youngestFrame); - if (stepFrame) { - switch (steppingType) { - case "step": - this.dbg.onEnterFrame = onEnterFrame; - // Fall through. - case "break": - case "next": - if (stepFrame.script) { - stepFrame.onStep = onStep; - } - stepFrame.onPop = onPop; - break; - case "finish": - stepFrame.onPop = onPop; - } - } - - return true; - }); - }, - - /** - * Clear the onStep and onPop hooks from the given frame and all of the frames - * below it. - * - * @param Debugger.Frame aFrame - * The frame we want to clear the stepping hooks from. - */ - _clearSteppingHooks: function (aFrame) { - if (aFrame && aFrame.live) { - while (aFrame) { - aFrame.onStep = undefined; - aFrame.onPop = undefined; - aFrame = aFrame.older; - } - } - }, - - /** - * Listen to the debuggee's DOM events if we received a request to do so. - * - * @param Object aRequest - * The resume request packet received over the RDP. - */ - _maybeListenToEvents: function (aRequest) { - // Break-on-DOMEvents is only supported in content debugging. - let events = aRequest.pauseOnDOMEvents; - if (this.global && events && - (events == "*" || - (Array.isArray(events) && events.length))) { - this._pauseOnDOMEvents = events; - let els = Cc["@mozilla.org/eventlistenerservice;1"] - .getService(Ci.nsIEventListenerService); - els.addListenerForAllEvents(this.global, this._allEventsListener, true); - } - }, - - /** - * If we are tasked with breaking on the load event, we have to add the - * listener early enough. - */ - _onWindowReady: function () { - this._maybeListenToEvents({ - pauseOnDOMEvents: this._pauseOnDOMEvents - }); - }, - - /** - * Handle a protocol request to resume execution of the debuggee. - */ - onResume: function (aRequest) { - if (this._state !== "paused") { - return { - error: "wrongState", - message: "Can't resume when debuggee isn't paused. Current state is '" - + this._state + "'", - state: this._state - }; - } - - // In case of multiple nested event loops (due to multiple debuggers open in - // different tabs or multiple debugger clients connected to the same tab) - // only allow resumption in a LIFO order. - if (this._nestedEventLoops.size && this._nestedEventLoops.lastPausedUrl - && (this._nestedEventLoops.lastPausedUrl !== this._parent.url - || this._nestedEventLoops.lastConnection !== this.conn)) { - return { - error: "wrongOrder", - message: "trying to resume in the wrong order.", - lastPausedUrl: this._nestedEventLoops.lastPausedUrl - }; - } - let resumeLimitHandled; - if (aRequest && aRequest.resumeLimit) { - resumeLimitHandled = this._handleResumeLimit(aRequest); - } else { - this._clearSteppingHooks(this.youngestFrame); - resumeLimitHandled = Promise.resolve(true); - } - - return resumeLimitHandled.then(() => { - if (aRequest) { - this._options.pauseOnExceptions = aRequest.pauseOnExceptions; - this._options.ignoreCaughtExceptions = aRequest.ignoreCaughtExceptions; - this.maybePauseOnExceptions(); - this._maybeListenToEvents(aRequest); - } - - let packet = this._resumed(); - this._popThreadPause(); - // Tell anyone who cares of the resume (as of now, that's the xpcshell - // harness) - // if (Services.obs) { - // Services.obs.notifyObservers(this, "devtools-thread-resumed", null); - // } - return packet; - }, error => { - return error instanceof Error - ? { error: "unknownError", - message: DevToolsUtils.safeErrorString(error) } - // It is a known error, and the promise was rejected with an error - // packet. - : error; - }); - }, - - /** - * Spin up a nested event loop so we can synchronously resolve a promise. - * - * DON'T USE THIS UNLESS YOU ABSOLUTELY MUST! Nested event loops suck: the - * world's state can change out from underneath your feet because JS is no - * longer run-to-completion. - * - * @param aPromise - * The promise we want to resolve. - * @returns The promise's resolution. - */ - unsafeSynchronize: function (aPromise) { - let needNest = true; - let eventLoop; - let returnVal; - - aPromise - .then((aResolvedVal) => { - needNest = false; - returnVal = aResolvedVal; - }) - .then(null, (aError) => { - reportError(aError, "Error inside unsafeSynchronize:"); - }) - .then(() => { - if (eventLoop) { - eventLoop.resolve(); - } - }); - - if (needNest) { - eventLoop = this._nestedEventLoops.push(); - eventLoop.enter(); - } - - return returnVal; - }, - - /** - * Set the debugging hook to pause on exceptions if configured to do so. - */ - maybePauseOnExceptions: function () { - if (this._options.pauseOnExceptions) { - this.dbg.onExceptionUnwind = this.onExceptionUnwind.bind(this); - } - }, - - /** - * A listener that gets called for every event fired on the page, when a list - * of interesting events was provided with the pauseOnDOMEvents property. It - * is used to set server-managed breakpoints on any existing event listeners - * for those events. - * - * @param Event event - * The event that was fired. - */ - _allEventsListener: function (event) { - if (this._pauseOnDOMEvents == "*" || - this._pauseOnDOMEvents.indexOf(event.type) != -1) { - for (let listener of this._getAllEventListeners(event.target)) { - if (event.type == listener.type || this._pauseOnDOMEvents == "*") { - this._breakOnEnter(listener.script); - } - } - } - }, - - /** - * Return an array containing all the event listeners attached to the - * specified event target and its ancestors in the event target chain. - * - * @param EventTarget eventTarget - * The target the event was dispatched on. - * @returns Array - */ - _getAllEventListeners: function (eventTarget) { - let els = Cc["@mozilla.org/eventlistenerservice;1"] - .getService(Ci.nsIEventListenerService); - - let targets = els.getEventTargetChainFor(eventTarget, true); - let listeners = []; - - for (let target of targets) { - let handlers = els.getListenerInfoFor(target); - for (let handler of handlers) { - // Null is returned for all-events handlers, and native event listeners - // don't provide any listenerObject, which makes them not that useful to - // a JS debugger. - if (!handler || !handler.listenerObject || !handler.type) - continue; - // Create a listener-like object suitable for our purposes. - let l = Object.create(null); - l.type = handler.type; - let listener = handler.listenerObject; - let listenerDO = this.globalDebugObject.makeDebuggeeValue(listener); - // If the listener is not callable, assume it is an event handler object. - if (!listenerDO.callable) { - // For some events we don't have permission to access the - // 'handleEvent' property when running in content scope. - if (!listenerDO.unwrap()) { - continue; - } - let heDesc; - while (!heDesc && listenerDO) { - heDesc = listenerDO.getOwnPropertyDescriptor("handleEvent"); - listenerDO = listenerDO.proto; - } - if (heDesc && heDesc.value) { - listenerDO = heDesc.value; - } - } - // When the listener is a bound function, we are actually interested in - // the target function. - while (listenerDO.isBoundFunction) { - listenerDO = listenerDO.boundTargetFunction; - } - l.script = listenerDO.script; - // Chrome listeners won't be converted to debuggee values, since their - // compartment is not added as a debuggee. - if (!l.script) - continue; - listeners.push(l); - } - } - return listeners; - }, - - /** - * Set a breakpoint on the first line of the given script that has an entry - * point. - */ - _breakOnEnter: function (script) { - let offsets = script.getAllOffsets(); - for (let line = 0, n = offsets.length; line < n; line++) { - if (offsets[line]) { - // N.B. Hidden breakpoints do not have an original location, and are not - // stored in the breakpoint actor map. - let actor = new BreakpointActor(this); - this.threadLifetimePool.addActor(actor); - - let scripts = this.dbg.findScripts({ source: script.source, line: line }); - let entryPoints = findEntryPointsForLine(scripts, line); - setBreakpointAtEntryPoints(actor, entryPoints); - this._hiddenBreakpoints.set(actor.actorID, actor); - break; - } - } - }, - - /** - * Helper method that returns the next frame when stepping. - */ - _getNextStepFrame: function (aFrame) { - let stepFrame = aFrame.reportedPop ? aFrame.older : aFrame; - if (!stepFrame || !stepFrame.script) { - stepFrame = null; - } - return stepFrame; - }, - - onClientEvaluate: function (aRequest) { - if (this.state !== "paused") { - return { error: "wrongState", - message: "Debuggee must be paused to evaluate code." }; - } - - let frame = this._requestFrame(aRequest.frame); - if (!frame) { - return { error: "unknownFrame", - message: "Evaluation frame not found" }; - } - - if (!frame.environment) { - return { error: "notDebuggee", - message: "cannot access the environment of this frame." }; - } - - let youngest = this.youngestFrame; - - // Put ourselves back in the running state and inform the client. - let resumedPacket = this._resumed(); - this.conn.send(resumedPacket); - - // Run the expression. - // XXX: test syntax errors - let completion = frame.eval(aRequest.expression); - - // Put ourselves back in the pause state. - let packet = this._paused(youngest); - packet.why = { type: "clientEvaluated", - frameFinished: this.createProtocolCompletionValue(completion) }; - - // Return back to our previous pause's event loop. - return packet; - }, - - onFrames: function (aRequest) { - if (this.state !== "paused") { - return { error: "wrongState", - message: "Stack frames are only available while the debuggee is paused."}; - } - - let start = aRequest.start ? aRequest.start : 0; - let count = aRequest.count; - - // Find the starting frame... - let frame = this.youngestFrame; - let i = 0; - while (frame && (i < start)) { - frame = frame.older; - i++; - } - - // Return request.count frames, or all remaining - // frames if count is not defined. - let promises = []; - for (; frame && (!count || i < (start + count)); i++, frame = frame.older) { - let form = this._createFrameActor(frame).form(); - form.depth = i; - - let promise = this.sources.getOriginalLocation(new GeneratedLocation( - this.sources.createNonSourceMappedActor(frame.script.source), - form.where.line, - form.where.column - )).then((originalLocation) => { - if (!originalLocation.originalSourceActor) { - return null; - } - - let sourceForm = originalLocation.originalSourceActor.form(); - form.where = { - source: sourceForm, - line: originalLocation.originalLine, - column: originalLocation.originalColumn - }; - form.source = sourceForm; - return form; - }); - promises.push(promise); - } - - return Promise.all(promises).then(function (frames) { - // Filter null values because sourcemapping may have failed. - return { frames: frames.filter(x => !!x) }; - }); - }, - - onReleaseMany: function (aRequest) { - if (!aRequest.actors) { - return { error: "missingParameter", - message: "no actors were specified" }; - } - - let res; - for (let actorID of aRequest.actors) { - let actor = this.threadLifetimePool.get(actorID); - if (!actor) { - if (!res) { - res = { error: "notReleasable", - message: "Only thread-lifetime actors can be released." }; - } - continue; - } - actor.onRelease(); - } - return res ? res : {}; - }, - - /** - * Get the script and source lists from the debugger. - */ - _discoverSources: function () { - // Only get one script per Debugger.Source. - const sourcesToScripts = new Map(); - const scripts = this.dbg.findScripts(); - - for (let i = 0, len = scripts.length; i < len; i++) { - let s = scripts[i]; - if (s.source) { - sourcesToScripts.set(s.source, s); - } - } - - return Promise.all([...sourcesToScripts.values()].map(script => { - return this.sources.createSourceActors(script.source); - })); - }, - - onSources: function (aRequest) { - return this._discoverSources().then(() => { - // No need to flush the new source packets here, as we are sending the - // list of sources out immediately and we don't need to invoke the - // overhead of an RDP packet for every source right now. Let the default - // timeout flush the buffered packets. - - return { - sources: this.sources.iter().map(s => s.form()) - }; - }); - }, - - /** - * Disassociate all breakpoint actors from their scripts and clear the - * breakpoint handlers. This method can be used when the thread actor intends - * to keep the breakpoint store, but needs to clear any actual breakpoints, - * e.g. due to a page navigation. This way the breakpoint actors' script - * caches won't hold on to the Debugger.Script objects leaking memory. - */ - disableAllBreakpoints: function () { - for (let bpActor of this.breakpointActorMap.findActors()) { - bpActor.removeScripts(); - } - }, - - - /** - * Handle a protocol request to pause the debuggee. - */ - onInterrupt: function (aRequest) { - if (this.state == "exited") { - return { type: "exited" }; - } else if (this.state == "paused") { - // TODO: return the actual reason for the existing pause. - return { type: "paused", why: { type: "alreadyPaused" } }; - } else if (this.state != "running") { - return { error: "wrongState", - message: "Received interrupt request in " + this.state + - " state." }; - } - - try { - // If execution should pause just before the next JavaScript bytecode is - // executed, just set an onEnterFrame handler. - if (aRequest.when == "onNext") { - let onEnterFrame = (aFrame) => { - return this._pauseAndRespond(aFrame, { type: "interrupted", onNext: true }); - }; - this.dbg.onEnterFrame = onEnterFrame; - - return { type: "willInterrupt" }; - } - - // If execution should pause immediately, just put ourselves in the paused - // state. - let packet = this._paused(); - if (!packet) { - return { error: "notInterrupted" }; - } - packet.why = { type: "interrupted" }; - - // Send the response to the interrupt request now (rather than - // returning it), because we're going to start a nested event loop - // here. - this.conn.send(packet); - - // Start a nested event loop. - this._pushThreadPause(); - - // We already sent a response to this request, don't send one - // now. - return null; - } catch (e) { - reportError(e); - return { error: "notInterrupted", message: e.toString() }; - } - }, - - /** - * Handle a protocol request to retrieve all the event listeners on the page. - */ - onEventListeners: function (aRequest) { - // This request is only supported in content debugging. - if (!this.global) { - return { - error: "notImplemented", - message: "eventListeners request is only supported in content debugging" - }; - } - - let els = Cc["@mozilla.org/eventlistenerservice;1"] - .getService(Ci.nsIEventListenerService); - - let nodes = this.global.document.getElementsByTagName("*"); - nodes = [this.global].concat([].slice.call(nodes)); - let listeners = []; - - for (let node of nodes) { - let handlers = els.getListenerInfoFor(node); - - for (let handler of handlers) { - // Create a form object for serializing the listener via the protocol. - let listenerForm = Object.create(null); - let listener = handler.listenerObject; - // Native event listeners don't provide any listenerObject or type and - // are not that useful to a JS debugger. - if (!listener || !handler.type) { - continue; - } - - // There will be no tagName if the event listener is set on the window. - let selector = node.tagName ? CssLogic.findCssSelector(node) : "window"; - let nodeDO = this.globalDebugObject.makeDebuggeeValue(node); - listenerForm.node = { - selector: selector, - object: createValueGrip(nodeDO, this._pausePool, this.objectGrip) - }; - listenerForm.type = handler.type; - listenerForm.capturing = handler.capturing; - listenerForm.allowsUntrusted = handler.allowsUntrusted; - listenerForm.inSystemEventGroup = handler.inSystemEventGroup; - let handlerName = "on" + listenerForm.type; - listenerForm.isEventHandler = false; - if (typeof node.hasAttribute !== "undefined") { - listenerForm.isEventHandler = !!node.hasAttribute(handlerName); - } - if (!!node[handlerName]) { - listenerForm.isEventHandler = !!node[handlerName]; - } - // Get the Debugger.Object for the listener object. - let listenerDO = this.globalDebugObject.makeDebuggeeValue(listener); - // If the listener is an object with a 'handleEvent' method, use that. - if (listenerDO.class == "Object" || listenerDO.class == "XULElement") { - // For some events we don't have permission to access the - // 'handleEvent' property when running in content scope. - if (!listenerDO.unwrap()) { - continue; - } - let heDesc; - while (!heDesc && listenerDO) { - heDesc = listenerDO.getOwnPropertyDescriptor("handleEvent"); - listenerDO = listenerDO.proto; - } - if (heDesc && heDesc.value) { - listenerDO = heDesc.value; - } - } - // When the listener is a bound function, we are actually interested in - // the target function. - while (listenerDO.isBoundFunction) { - listenerDO = listenerDO.boundTargetFunction; - } - listenerForm.function = createValueGrip(listenerDO, this._pausePool, - this.objectGrip); - listeners.push(listenerForm); - } - } - return { listeners: listeners }; - }, - - /** - * Return the Debug.Frame for a frame mentioned by the protocol. - */ - _requestFrame: function (aFrameID) { - if (!aFrameID) { - return this.youngestFrame; - } - - if (this._framePool.has(aFrameID)) { - return this._framePool.get(aFrameID).frame; - } - - return undefined; - }, - - _paused: function (aFrame) { - // We don't handle nested pauses correctly. Don't try - if we're - // paused, just continue running whatever code triggered the pause. - // We don't want to actually have nested pauses (although we - // have nested event loops). If code runs in the debuggee during - // a pause, it should cause the actor to resume (dropping - // pause-lifetime actors etc) and then repause when complete. - - if (this.state === "paused") { - return undefined; - } - - // Clear stepping hooks. - this.dbg.onEnterFrame = undefined; - this.dbg.onExceptionUnwind = undefined; - if (aFrame) { - aFrame.onStep = undefined; - aFrame.onPop = undefined; - } - - // Clear DOM event breakpoints. - // XPCShell tests don't use actual DOM windows for globals and cause - // removeListenerForAllEvents to throw. - // if (!isWorker && this.global && !this.global.toString().includes("Sandbox")) { - // let els = Cc["@mozilla.org/eventlistenerservice;1"] - // .getService(Ci.nsIEventListenerService); - // els.removeListenerForAllEvents(this.global, this._allEventsListener, true); - // for (let [, bp] of this._hiddenBreakpoints) { - // bp.delete(); - // } - // this._hiddenBreakpoints.clear(); - // } - - this._state = "paused"; - - // Create the actor pool that will hold the pause actor and its - // children. - assert(!this._pausePool, "No pause pool should exist yet"); - this._pausePool = new ActorPool(this.conn); - this.conn.addActorPool(this._pausePool); - - // Give children of the pause pool a quick link back to the - // thread... - this._pausePool.threadActor = this; - - // Create the pause actor itself... - assert(!this._pauseActor, "No pause actor should exist yet"); - this._pauseActor = new PauseActor(this._pausePool); - this._pausePool.addActor(this._pauseActor); - - // Update the list of frames. - let poppedFrames = this._updateFrames(); - - // Send off the paused packet and spin an event loop. - let packet = { from: this.actorID, - type: "paused", - actor: this._pauseActor.actorID }; - if (aFrame) { - packet.frame = this._createFrameActor(aFrame).form(); - } - - if (poppedFrames) { - packet.poppedFrames = poppedFrames; - } - - return packet; - }, - - _resumed: function () { - this._state = "running"; - - // Drop the actors in the pause actor pool. - this.conn.removeActorPool(this._pausePool); - - this._pausePool = null; - this._pauseActor = null; - - return { from: this.actorID, type: "resumed" }; - }, - - /** - * Expire frame actors for frames that have been popped. - * - * @returns A list of actor IDs whose frames have been popped. - */ - _updateFrames: function () { - let popped = []; - - // Create the actor pool that will hold the still-living frames. - let framePool = new ActorPool(this.conn); - let frameList = []; - - for (let frameActor of this._frameActors) { - if (frameActor.frame.live) { - framePool.addActor(frameActor); - frameList.push(frameActor); - } else { - popped.push(frameActor.actorID); - } - } - - // Remove the old frame actor pool, this will expire - // any actors that weren't added to the new pool. - if (this._framePool) { - this.conn.removeActorPool(this._framePool); - } - - this._frameActors = frameList; - this._framePool = framePool; - this.conn.addActorPool(framePool); - - return popped; - }, - - _createFrameActor: function (aFrame) { - if (aFrame.actor) { - return aFrame.actor; - } - - let actor = new FrameActor(aFrame, this); - this._frameActors.push(actor); - this._framePool.addActor(actor); - aFrame.actor = actor; - - return actor; - }, - - /** - * Create and return an environment actor that corresponds to the provided - * Debugger.Environment. - * @param Debugger.Environment aEnvironment - * The lexical environment we want to extract. - * @param object aPool - * The pool where the newly-created actor will be placed. - * @return The EnvironmentActor for aEnvironment or undefined for host - * functions or functions scoped to a non-debuggee global. - */ - createEnvironmentActor: function (aEnvironment, aPool) { - if (!aEnvironment) { - return undefined; - } - - if (aEnvironment.actor) { - return aEnvironment.actor; - } - - let actor = new EnvironmentActor(aEnvironment, this); - aPool.addActor(actor); - aEnvironment.actor = actor; - - return actor; - }, - - /** - * Return a protocol completion value representing the given - * Debugger-provided completion value. - */ - createProtocolCompletionValue: function (aCompletion) { - let protoValue = {}; - if (aCompletion == null) { - protoValue.terminated = true; - } else if ("return" in aCompletion) { - protoValue.return = createValueGrip(aCompletion.return, - this._pausePool, this.objectGrip); - } else if ("throw" in aCompletion) { - protoValue.throw = createValueGrip(aCompletion.throw, - this._pausePool, this.objectGrip); - } else { - protoValue.return = createValueGrip(aCompletion.yield, - this._pausePool, this.objectGrip); - } - return protoValue; - }, - - /** - * Create a grip for the given debuggee object. - * - * @param aValue Debugger.Object - * The debuggee object value. - * @param aPool ActorPool - * The actor pool where the new object actor will be added. - */ - objectGrip: function (aValue, aPool) { - if (!aPool.objectActors) { - aPool.objectActors = new WeakMap(); - } - - if (aPool.objectActors.has(aValue)) { - return aPool.objectActors.get(aValue).grip(); - } else if (this.threadLifetimePool.objectActors.has(aValue)) { - return this.threadLifetimePool.objectActors.get(aValue).grip(); - } - - let actor = new PauseScopedObjectActor(aValue, { - getGripDepth: () => this._gripDepth, - incrementGripDepth: () => this._gripDepth++, - decrementGripDepth: () => this._gripDepth--, - createValueGrip: v => createValueGrip(v, this._pausePool, - this.pauseObjectGrip), - sources: () => this.sources, - createEnvironmentActor: (env, pool) => - this.createEnvironmentActor(env, pool), - promote: () => this.threadObjectGrip(actor), - isThreadLifetimePool: () => - actor.registeredPool !== this.threadLifetimePool, - getGlobalDebugObject: () => this.globalDebugObject - }); - aPool.addActor(actor); - aPool.objectActors.set(aValue, actor); - return actor.grip(); - }, - - /** - * Create a grip for the given debuggee object with a pause lifetime. - * - * @param aValue Debugger.Object - * The debuggee object value. - */ - pauseObjectGrip: function (aValue) { - if (!this._pausePool) { - throw "Object grip requested while not paused."; - } - - return this.objectGrip(aValue, this._pausePool); - }, - - /** - * Extend the lifetime of the provided object actor to thread lifetime. - * - * @param aActor object - * The object actor. - */ - threadObjectGrip: function (aActor) { - // We want to reuse the existing actor ID, so we just remove it from the - // current pool's weak map and then let pool.addActor do the rest. - aActor.registeredPool.objectActors.delete(aActor.obj); - this.threadLifetimePool.addActor(aActor); - this.threadLifetimePool.objectActors.set(aActor.obj, aActor); - }, - - /** - * Handle a protocol request to promote multiple pause-lifetime grips to - * thread-lifetime grips. - * - * @param aRequest object - * The protocol request object. - */ - onThreadGrips: function (aRequest) { - if (this.state != "paused") { - return { error: "wrongState" }; - } - - if (!aRequest.actors) { - return { error: "missingParameter", - message: "no actors were specified" }; - } - - for (let actorID of aRequest.actors) { - let actor = this._pausePool.get(actorID); - if (actor) { - this.threadObjectGrip(actor); - } - } - return {}; - }, - - /** - * Create a long string grip that is scoped to a pause. - * - * @param aString String - * The string we are creating a grip for. - */ - pauseLongStringGrip: function (aString) { - return longStringGrip(aString, this._pausePool); - }, - - /** - * Create a long string grip that is scoped to a thread. - * - * @param aString String - * The string we are creating a grip for. - */ - threadLongStringGrip: function (aString) { - return longStringGrip(aString, this._threadLifetimePool); - }, - - // JS Debugger API hooks. - - /** - * A function that the engine calls when a call to a debug event hook, - * breakpoint handler, watchpoint handler, or similar function throws some - * exception. - * - * @param aException exception - * The exception that was thrown in the debugger code. - */ - uncaughtExceptionHook: function (aException) { - dumpn("Got an exception: " + aException.message + "\n" + aException.stack); - }, - - /** - * A function that the engine calls when a debugger statement has been - * executed in the specified frame. - * - * @param aFrame Debugger.Frame - * The stack frame that contained the debugger statement. - */ - onDebuggerStatement: function (aFrame) { - // Don't pause if we are currently stepping (in or over) or the frame is - // black-boxed. - const generatedLocation = this.sources.getFrameLocation(aFrame); - const { originalSourceActor } = this.unsafeSynchronize(this.sources.getOriginalLocation( - generatedLocation)); - const url = originalSourceActor ? originalSourceActor.url : null; - - return this.sources.isBlackBoxed(url) || aFrame.onStep - ? undefined - : this._pauseAndRespond(aFrame, { type: "debuggerStatement" }); - }, - - /** - * A function that the engine calls when an exception has been thrown and has - * propagated to the specified frame. - * - * @param aFrame Debugger.Frame - * The youngest remaining stack frame. - * @param aValue object - * The exception that was thrown. - */ - onExceptionUnwind: function (aFrame, aValue) { - let willBeCaught = false; - for (let frame = aFrame; frame != null; frame = frame.older) { - if (frame.script.isInCatchScope(frame.offset)) { - willBeCaught = true; - break; - } - } - - if (willBeCaught && this._options.ignoreCaughtExceptions) { - return undefined; - } - - // NS_ERROR_NO_INTERFACE exceptions are a special case in browser code, - // since they're almost always thrown by QueryInterface functions, and - // handled cleanly by native code. -// if (aValue == Cr.NS_ERROR_NO_INTERFACE) { -// return undefined; -// } - - const generatedLocation = this.sources.getFrameLocation(aFrame); - const { originalSourceActor } = this.unsafeSynchronize(this.sources.getOriginalLocation( - generatedLocation)); - const url = originalSourceActor ? originalSourceActor.url : null; - - if (this.sources.isBlackBoxed(url)) { - return undefined; - } - - try { - let packet = this._paused(aFrame); - if (!packet) { - return undefined; - } - - packet.why = { type: "exception", - exception: createValueGrip(aValue, this._pausePool, - this.objectGrip) - }; - this.conn.send(packet); - - this._pushThreadPause(); - } catch (e) { - reportError(e, "Got an exception during TA_onExceptionUnwind: "); - } - - return undefined; - }, - - /** - * A function that the engine calls when a new script has been loaded into the - * scope of the specified debuggee global. - * - * @param aScript Debugger.Script - * The source script that has been loaded into a debuggee compartment. - * @param aGlobal Debugger.Object - * A Debugger.Object instance whose referent is the global object. - */ - onNewScript: function (aScript, aGlobal) { - this._addSource(aScript.source); - }, - - /** - * A function called when there's a new or updated source from a thread actor's - * sources. Emits `newSource` and `updatedSource` on the tab actor. - * - * @param {String} name - * @param {SourceActor} source - */ - onSourceEvent: function (name, source) { - this.conn.send({ - from: this._parent.actorID, - type: name, - source: source.form() - }); - - // For compatibility and debugger still using `newSource` on the thread client, - // still emit this event here. Clean up in bug 1247084 - if (name === "newSource") { - this.conn.send({ - from: this.actorID, - type: name, - source: source.form() - }); - } - }, - - /** - * Add the provided source to the server cache. - * - * @param aSource Debugger.Source - * The source that will be stored. - * @returns true, if the source was added; false otherwise. - */ - _addSource: function (aSource) { - if (!this.sources.allowSource(aSource) || this._debuggerSourcesSeen.has(aSource)) { - return false; - } - - let sourceActor = this.sources.createNonSourceMappedActor(aSource); - let bpActors = [...this.breakpointActorMap.findActors()]; - - if (this._options.useSourceMaps) { - let promises = []; - - // Go ahead and establish the source actors for this script, which - // fetches sourcemaps if available and sends onNewSource - // notifications. - let sourceActorsCreated = this.sources._createSourceMappedActors(aSource); - - if (bpActors.length) { - // We need to use unsafeSynchronize here because if the page is being reloaded, - // this call will replace the previous set of source actors for this source - // with a new one. If the source actors have not been replaced by the time - // we try to reset the breakpoints below, their location objects will still - // point to the old set of source actors, which point to different - // scripts. - this.unsafeSynchronize(sourceActorsCreated); - } - - for (let _actor of bpActors) { - // XXX bug 1142115: We do async work in here, so we need to create a fresh - // binding because for/of does not yet do that in SpiderMonkey. - let actor = _actor; - - if (actor.isPending) { - promises.push(actor.originalLocation.originalSourceActor._setBreakpoint(actor)); - } else { - promises.push(this.sources.getAllGeneratedLocations(actor.originalLocation) - .then((generatedLocations) => { - if (generatedLocations.length > 0 && - generatedLocations[0].generatedSourceActor.actorID === sourceActor.actorID) { - sourceActor._setBreakpointAtAllGeneratedLocations(actor, generatedLocations); - } - })); - } - } - - if (promises.length > 0) { - this.unsafeSynchronize(Promise.all(promises)); - } - } else { - // Bug 1225160: If addSource is called in response to a new script - // notification, and this notification was triggered by loading a JSM from - // chrome code, calling unsafeSynchronize could cause a debuggee timer to - // fire. If this causes the JSM to be loaded a second time, the browser - // will crash, because loading JSMS is not reentrant, and the first load - // has not completed yet. - // - // The root of the problem is that unsafeSynchronize can cause debuggee - // code to run. Unfortunately, fixing that is prohibitively difficult. The - // best we can do at the moment is disable source maps for the browser - // debugger, and carefully avoid the use of unsafeSynchronize in this - // function when source maps are disabled. - for (let actor of bpActors) { - if (actor.isPending) { - actor.originalLocation.originalSourceActor._setBreakpoint(actor); - } else { - actor.originalLocation.originalSourceActor._setBreakpointAtGeneratedLocation( - actor, GeneratedLocation.fromOriginalLocation(actor.originalLocation) - ); - } - } - } - - this._debuggerSourcesSeen.add(aSource); - return true; - }, - - - /** - * Get prototypes and properties of multiple objects. - */ - onPrototypesAndProperties: function (aRequest) { - let result = {}; - for (let actorID of aRequest.actors) { - // This code assumes that there are no lazily loaded actors returned - // by this call. - let actor = this.conn.getActor(actorID); - if (!actor) { - return { from: this.actorID, - error: "noSuchActor" }; - } - let handler = actor.onPrototypeAndProperties; - if (!handler) { - return { from: this.actorID, - error: "unrecognizedPacketType", - message: ('Actor "' + actorID + - '" does not recognize the packet type ' + - '"prototypeAndProperties"') }; - } - result[actorID] = handler.call(actor, {}); - } - return { from: this.actorID, - actors: result }; - } -}; - -ThreadActor.prototype.requestTypes = { - "attach": ThreadActor.prototype.onAttach, - "detach": ThreadActor.prototype.onDetach, - "reconfigure": ThreadActor.prototype.onReconfigure, - "resume": ThreadActor.prototype.onResume, - "clientEvaluate": ThreadActor.prototype.onClientEvaluate, - "frames": ThreadActor.prototype.onFrames, - "interrupt": ThreadActor.prototype.onInterrupt, - "eventListeners": ThreadActor.prototype.onEventListeners, - "releaseMany": ThreadActor.prototype.onReleaseMany, - "sources": ThreadActor.prototype.onSources, - "threadGrips": ThreadActor.prototype.onThreadGrips, - "prototypesAndProperties": ThreadActor.prototype.onPrototypesAndProperties -}; - -// exports.ThreadActor = ThreadActor; - -/** - * Creates a PauseActor. - * - * PauseActors exist for the lifetime of a given debuggee pause. Used to - * scope pause-lifetime grips. - * - * @param ActorPool aPool - * The actor pool created for this pause. - */ -function PauseActor(aPool) -{ - this.pool = aPool; -} - -PauseActor.prototype = { - actorPrefix: "pause" -}; - - -/** - * A base actor for any actors that should only respond receive messages in the - * paused state. Subclasses may expose a `threadActor` which is used to help - * determine when we are in a paused state. Subclasses should set their own - * "constructor" property if they want better error messages. You should never - * instantiate a PauseScopedActor directly, only through subclasses. - */ -function PauseScopedActor() -{ -} - -/** - * A function decorator for creating methods to handle protocol messages that - * should only be received while in the paused state. - * - * @param aMethod Function - * The function we are decorating. - */ -PauseScopedActor.withPaused = function (aMethod) { - return function () { - if (this.isPaused()) { - return aMethod.apply(this, arguments); - } else { - return this._wrongState(); - } - }; -}; - -PauseScopedActor.prototype = { - - /** - * Returns true if we are in the paused state. - */ - isPaused: function () { - // When there is not a ThreadActor available (like in the webconsole) we - // have to be optimistic and assume that we are paused so that we can - // respond to requests. - return this.threadActor ? this.threadActor.state === "paused" : true; - }, - - /** - * Returns the wrongState response packet for this actor. - */ - _wrongState: function () { - return { - error: "wrongState", - message: this.constructor.name + - " actors can only be accessed while the thread is paused." - }; - } -}; - -/** - * Creates a pause-scoped actor for the specified object. - * @see ObjectActor - */ -function PauseScopedObjectActor(obj, hooks) { - ObjectActor.call(this, obj, hooks); - this.hooks.promote = hooks.promote; - this.hooks.isThreadLifetimePool = hooks.isThreadLifetimePool; -} - -PauseScopedObjectActor.prototype = Object.create(PauseScopedActor.prototype); - -Object.assign(PauseScopedObjectActor.prototype, ObjectActor.prototype); - -Object.assign(PauseScopedObjectActor.prototype, { - constructor: PauseScopedObjectActor, - actorPrefix: "pausedobj", - - onOwnPropertyNames: - PauseScopedActor.withPaused(ObjectActor.prototype.onOwnPropertyNames), - - onPrototypeAndProperties: - PauseScopedActor.withPaused(ObjectActor.prototype.onPrototypeAndProperties), - - onPrototype: PauseScopedActor.withPaused(ObjectActor.prototype.onPrototype), - onProperty: PauseScopedActor.withPaused(ObjectActor.prototype.onProperty), - onDecompile: PauseScopedActor.withPaused(ObjectActor.prototype.onDecompile), - - onDisplayString: - PauseScopedActor.withPaused(ObjectActor.prototype.onDisplayString), - - onParameterNames: - PauseScopedActor.withPaused(ObjectActor.prototype.onParameterNames), - - /** - * Handle a protocol request to promote a pause-lifetime grip to a - * thread-lifetime grip. - * - * @param aRequest object - * The protocol request object. - */ - onThreadGrip: PauseScopedActor.withPaused(function (aRequest) { - this.hooks.promote(); - return {}; - }), - - /** - * Handle a protocol request to release a thread-lifetime grip. - * - * @param aRequest object - * The protocol request object. - */ - onRelease: PauseScopedActor.withPaused(function (aRequest) { - if (this.hooks.isThreadLifetimePool()) { - return { error: "notReleasable", - message: "Only thread-lifetime actors can be released." }; - } - - this.release(); - return {}; - }), -}); - -Object.assign(PauseScopedObjectActor.prototype.requestTypes, { - "threadGrip": PauseScopedObjectActor.prototype.onThreadGrip, -}); - -function hackDebugger(Debugger) { - // TODO: Improve native code instead of hacking on top of it - - /** - * Override the toString method in order to get more meaningful script output - * for debugging the debugger. - */ - Debugger.Script.prototype.toString = function () { - let output = ""; - if (this.url) { - output += this.url; - } - if (typeof this.staticLevel != "undefined") { - output += ":L" + this.staticLevel; - } - if (typeof this.startLine != "undefined") { - output += ":" + this.startLine; - if (this.lineCount && this.lineCount > 1) { - output += "-" + (this.startLine + this.lineCount - 1); - } - } - if (typeof this.startLine != "undefined") { - output += ":" + this.startLine; - if (this.lineCount && this.lineCount > 1) { - output += "-" + (this.startLine + this.lineCount - 1); - } - } - if (this.strictMode) { - output += ":strict"; - } - return output; - }; - - /** - * Helper property for quickly getting to the line number a stack frame is - * currently paused at. - */ - Object.defineProperty(Debugger.Frame.prototype, "line", { - configurable: true, - get: function () { - if (this.script) { - return this.script.getOffsetLocation(this.offset).lineNumber; - } else { - return null; - } - } - }); -} - - -/** - * Creates an actor for handling chrome debugging. ChromeDebuggerActor is a - * thin wrapper over ThreadActor, slightly changing some of its behavior. - * - * @param aConnection object - * The DebuggerServerConnection with which this ChromeDebuggerActor - * is associated. (Currently unused, but required to make this - * constructor usable with addGlobalActor.) - * - * @param aParent object - * This actor's parent actor. See ThreadActor for a list of expected - * properties. - */ -function ChromeDebuggerActor(aConnection, aParent) -{ - ThreadActor.prototype.initialize.call(this, aParent); -} - -ChromeDebuggerActor.prototype = Object.create(ThreadActor.prototype); - -Object.assign(ChromeDebuggerActor.prototype, { - constructor: ChromeDebuggerActor, - - // A constant prefix that will be used to form the actor ID by the server. - actorPrefix: "chromeDebugger" -}); - -// exports.ChromeDebuggerActor = ChromeDebuggerActor; - -/** - * Creates an actor for handling add-on debugging. AddonThreadActor is - * a thin wrapper over ThreadActor. - * - * @param aConnection object - * The DebuggerServerConnection with which this AddonThreadActor - * is associated. (Currently unused, but required to make this - * constructor usable with addGlobalActor.) - * - * @param aParent object - * This actor's parent actor. See ThreadActor for a list of expected - * properties. - */ -function AddonThreadActor(aConnect, aParent) { - ThreadActor.prototype.initialize.call(this, aParent); -} - -AddonThreadActor.prototype = Object.create(ThreadActor.prototype); - -Object.assign(AddonThreadActor.prototype, { - constructor: AddonThreadActor, - - // A constant prefix that will be used to form the actor ID by the server. - actorPrefix: "addonThread" -}); - -// exports.AddonThreadActor = AddonThreadActor; - -// Utility functions. - -/** - * Report the given error in the error console and to stdout. - * - * @param Error aError - * The error object you wish to report. - * @param String aPrefix - * An optional prefix for the reported error message. - */ -// var oldReportError = reportError; -function reportError(aError, aPrefix="") { - // assert(aError instanceof Error, "Must pass Error objects to reportError"); - let msg = "" + aPrefix + aError.message + ":\n" + aError.stack; - // oldReportError(msg); - log(msg); -} - -/** - * Find the scripts which contain offsets that are an entry point to the given - * line. - * - * @param Array scripts - * The set of Debugger.Scripts to consider. - * @param Number line - * The line we are searching for entry points into. - * @returns Array of objects of the form { script, offsets } where: - * - script is a Debugger.Script - * - offsets is an array of offsets that are entry points into the - * given line. - */ -function findEntryPointsForLine(scripts, line) { - const entryPoints = []; - for (let script of scripts) { - const offsets = script.getLineOffsets(line); - if (offsets.length) { - entryPoints.push({ script, offsets }); - } - } - return entryPoints; -} - -/** - * Unwrap a global that is wrapped in a |Debugger.Object|, or if the global has - * become a dead object, return |undefined|. - * - * @param Debugger.Object wrappedGlobal - * The |Debugger.Object| which wraps a global. - * - * @returns {Object|undefined} - * Returns the unwrapped global object or |undefined| if unwrapping - * failed. - */ -var unwrapDebuggerObjectGlobal = wrappedGlobal => { - try { - // Because of bug 991399 we sometimes get nuked window references here. We - // just bail out in that case. - // - // Note that addon sandboxes have a DOMWindow as their prototype. So make - // sure that we can touch the prototype too (whatever it is), in case _it_ - // is it a nuked window reference. We force stringification to make sure - // that any dead object proxies make themselves known. - let global = wrappedGlobal.unsafeDereference(); - Object.getPrototypeOf(global) + ""; - return global; - } - catch (e) { - return undefined; - } -}; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/source.js b/native/cocos/scripting/js-bindings/script/debugger/actors/source.js deleted file mode 100644 index f2d2db1fed..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/source.js +++ /dev/null @@ -1,937 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public -* License, v. 2.0. If a copy of the MPL was not distributed with this -* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// const { Cc, Ci } = require("chrome"); -// const Services = require("Services"); -// const { BreakpointActor, setBreakpointAtEntryPoints } = require("devtools/server/actors/breakpoint"); -// const { OriginalLocation, GeneratedLocation } = require("devtools/server/actors/common"); -// const { createValueGrip } = require("devtools/server/actors/object"); -// const { ActorClassWithSpec, Arg, RetVal, method } = require("devtools/shared/protocol"); -// const DevToolsUtils = require("devtools/shared/DevToolsUtils"); -// const { assert, fetch } = DevToolsUtils; -// const { joinURI } = require("devtools/shared/path"); -// const promise = require("promise"); -// const { defer, resolve, reject, all } = promise; -// const { sourceSpec } = require("devtools/shared/specs/source"); - -// loader.lazyRequireGetter(this, "SourceMapConsumer", "source-map", true); -// loader.lazyRequireGetter(this, "SourceMapGenerator", "source-map", true); -// loader.lazyRequireGetter(this, "mapURIToAddonID", "devtools/server/actors/utils/map-uri-to-addon-id"); - -// from "devtools/shared/specs/source" -const sourceSpec = generateActorSpec({ - typeName: "source", - - methods: { - getExecutableLines: { response: { lines: RetVal("json") } }, - onSource: { - request: { type: "source" }, - response: RetVal("json") - }, - prettyPrint: { - request: { indent: Arg(0, "number") }, - response: RetVal("json") - }, - disablePrettyPrint: { - response: RetVal("json") - }, - blackbox: { response: { pausedInSource: RetVal("boolean") } }, - unblackbox: {}, - setBreakpoint: { - request: { - location: { - line: Arg(0, "number"), - column: Arg(1, "nullable:number") - }, - condition: Arg(2, "nullable:string"), - noSliding: Arg(3, "nullable:boolean") - }, - response: RetVal("json") - }, - }, -}); - -// --------------- - -function isEvalSource(source) { - let introType = source.introductionType; - // These are all the sources that are essentially eval-ed (either - // by calling eval or passing a string to one of these functions). - return (introType === "eval" || - introType === "Function" || - introType === "eventHandler" || - introType === "setTimeout" || - introType === "setInterval"); -} - -// exports.isEvalSource = isEvalSource; - -function getSourceURL(source, window) { - if (isEvalSource(source)) { - // Eval sources have no urls, but they might have a `displayURL` - // created with the sourceURL pragma. If the introduction script - // is a non-eval script, generate an full absolute URL relative to it. - - if (source.displayURL && source.introductionScript && - !isEvalSource(source.introductionScript.source)) { - - if (source.introductionScript.source.url === "debugger eval code") { - if (window) { - // If this is a named eval script created from the console, make it - // relative to the current page. window is only available - // when we care about this. - return joinURI(window.location.href, source.displayURL); - } - } - else { - return joinURI(source.introductionScript.source.url, source.displayURL); - } - } - - return source.displayURL; - } - else if (source.url === "debugger eval code") { - // Treat code evaluated by the console as unnamed eval scripts - return null; - } - return source.url; -} - -// exports.getSourceURL = getSourceURL; - -/** - * Resolve a URI back to physical file. - * - * Of course, this works only for URIs pointing to local resources. - * - * @param aURI - * URI to resolve - * @return - * resolved nsIURI - */ -function resolveURIToLocalPath(aURI) { - let resolved; - switch (aURI.scheme) { - case "jar": - case "file": - return aURI; - - case "chrome": - resolved = Cc["@mozilla.org/chrome/chrome-registry;1"]. - getService(Ci.nsIChromeRegistry).convertChromeURL(aURI); - return resolveURIToLocalPath(resolved); - - case "resource": - resolved = Cc["@mozilla.org/network/protocol;1?name=resource"]. - getService(Ci.nsIResProtocolHandler).resolveURI(aURI); - aURI = Services.io.newURI(resolved, null, null); - return resolveURIToLocalPath(aURI); - - default: - return null; - } -} - -/** - * A SourceActor provides information about the source of a script. There - * are two kinds of source actors: ones that represent real source objects, - * and ones that represent non-existant "original" sources when the real - * sources are sourcemapped. When a source is sourcemapped, actors are - * created for both the "generated" and "original" sources, and the client will - * only see the original sources. We separate these because there isn't - * a 1:1 mapping of generated to original sources; one generated source - * may represent N original sources, so we need to create N + 1 separate - * actors. - * - * There are 4 different scenarios for sources that you should - * understand: - * - * - A single non-sourcemapped source that is not inlined in HTML - * (separate JS file, eval'ed code, etc) - * - A single sourcemapped source which creates N original sources - * - An HTML page with multiple inline scripts, which are distinct - * sources, but should be represented as a single source - * - A pretty-printed source (which may or may not be an original - * sourcemapped source), which generates a sourcemap for itself - * - * The complexity of `SourceActor` and `ThreadSources` are to handle - * all of thise cases and hopefully internalize the complexities. - * - * @param Debugger.Source source - * The source object we are representing. - * @param ThreadActor thread - * The current thread actor. - * @param String originalUrl - * Optional. For sourcemapped urls, the original url this is representing. - * @param Debugger.Source generatedSource - * Optional, passed in when aSourceMap is also passed in. The generated - * source object that introduced this source. - * @param Boolean isInlineSource - * Optional. True if this is an inline source from a HTML or XUL page. - * @param String contentType - * Optional. The content type of this source, if immediately available. - */ -let SourceActor = ActorClassWithSpec(sourceSpec, { - typeName: "source", - - initialize: function ({ source, thread, originalUrl, generatedSource, - isInlineSource, contentType }) { - this._threadActor = thread; - this._originalUrl = originalUrl; - this._source = source; - this._generatedSource = generatedSource; - this._contentType = contentType; - this._isInlineSource = isInlineSource; - - this.onSource = this.onSource.bind(this); - this._invertSourceMap = this._invertSourceMap.bind(this); - this._encodeAndSetSourceMapURL = this._encodeAndSetSourceMapURL.bind(this); - this._getSourceText = this._getSourceText.bind(this); - - this._mapSourceToAddon(); - - if (this.threadActor.sources.isPrettyPrinted(this.url)) { - this._init = this.prettyPrint( - this.threadActor.sources.prettyPrintIndent(this.url) - ).then(null, error => { - DevToolsUtils.reportException("SourceActor", error); - }); - } else { - this._init = null; - } - }, - - get isSourceMapped() { - return !!(!this.isInlineSource && ( - this._originalURL || this._generatedSource || - this.threadActor.sources.isPrettyPrinted(this.url) - )); - }, - - get isInlineSource() { - return this._isInlineSource; - }, - - get threadActor() { return this._threadActor; }, - get sources() { return this._threadActor.sources; }, - get dbg() { return this.threadActor.dbg; }, - get source() { return this._source; }, - get generatedSource() { return this._generatedSource; }, - get breakpointActorMap() { return this.threadActor.breakpointActorMap; }, - get url() { - if (this.source) { - return getSourceURL(this.source, this.threadActor._parent.window); - } - return this._originalUrl; - }, - get addonID() { return this._addonID; }, - get addonPath() { return this._addonPath; }, - - get prettyPrintWorker() { - return this.threadActor.prettyPrintWorker; - }, - - form: function () { - let source = this.source || this.generatedSource; - // This might not have a source or a generatedSource because we - // treat HTML pages with inline scripts as a special SourceActor - // that doesn't have either - let introductionUrl = null; - if (source && source.introductionScript) { - introductionUrl = source.introductionScript.source.url; - } - - return { - actor: this.actorID, - generatedUrl: this.generatedSource ? this.generatedSource.url : null, - url: this.url ? this.url.split(" -> ").pop() : null, - addonID: this._addonID, - addonPath: this._addonPath, - isBlackBoxed: this.threadActor.sources.isBlackBoxed(this.url), - isPrettyPrinted: this.threadActor.sources.isPrettyPrinted(this.url), - isSourceMapped: this.isSourceMapped, - sourceMapURL: source ? source.sourceMapURL : null, - introductionUrl: introductionUrl ? introductionUrl.split(" -> ").pop() : null, - introductionType: source ? source.introductionType : null - }; - }, - - disconnect: function () { - if (this.registeredPool && this.registeredPool.sourceActors) { - delete this.registeredPool.sourceActors[this.actorID]; - } - }, - - _mapSourceToAddon: function () { - try { - var nsuri = Services.io.newURI(this.url.split(" -> ").pop(), null, null); - } - catch (e) { - // We can't do anything with an invalid URI - return; - } - - let localURI = resolveURIToLocalPath(nsuri); - if (!localURI) { - return; - } - - let id = mapURIToAddonID(localURI); - if (!id) { - return; - } - this._addonID = id; - - if (localURI instanceof Ci.nsIJARURI) { - // The path in the add-on is easy for jar: uris - this._addonPath = localURI.JAREntry; - } - else if (localURI instanceof Ci.nsIFileURL) { - // For file: uris walk up to find the last directory that is part of the - // add-on - let target = localURI.file; - let path = target.leafName; - - // We can assume that the directory containing the source file is part - // of the add-on - let root = target.parent; - let file = root.parent; - while (file && mapURIToAddonID(Services.io.newFileURI(file))) { - path = root.leafName + "/" + path; - root = file; - file = file.parent; - } - - if (!file) { - const error = new Error("Could not find the root of the add-on for " + this.url); - DevToolsUtils.reportException("SourceActor.prototype._mapSourceToAddon", error); - return; - } - - this._addonPath = path; - } - }, - - _reportLoadSourceError: function (error, map = null) { - try { - DevToolsUtils.reportException("SourceActor", error); - - JSON.stringify(this.form(), null, 4).split(/\n/g) - .forEach(line => console.error("\t", line)); - - if (!map) { - return; - } - - console.error("\t", "source map's sourceRoot =", map.sourceRoot); - - console.error("\t", "source map's sources ="); - map.sources.forEach(s => { - let hasSourceContent = map.sourceContentFor(s, true); - console.error("\t\t", s, "\t", - hasSourceContent ? "has source content" : "no source content"); - }); - - console.error("\t", "source map's sourcesContent ="); - map.sourcesContent.forEach(c => { - if (c.length > 80) { - c = c.slice(0, 77) + "..."; - } - c = c.replace(/\n/g, "\\n"); - console.error("\t\t", c); - }); - } catch (e) { } - }, - - _getSourceText: function () { - let toResolvedContent = t => ({ - content: t, - contentType: this._contentType - }); - - let genSource = this.generatedSource || this.source; - return this.threadActor.sources.fetchSourceMap(genSource).then(map => { - if (map) { - try { - let sourceContent = map.sourceContentFor(this.url); - if (sourceContent) { - return toResolvedContent(sourceContent); - } - } catch (error) { - this._reportLoadSourceError(error, map); - throw error; - } - } - - // Use `source.text` if it exists, is not the "no source" string, and - // the content type of the source is JavaScript or it is synthesized - // wasm. It will be "no source" if the Debugger API wasn't able to load - // the source because sources were discarded - // (javascript.options.discardSystemSource == true). Re-fetch non-JS - // sources to get the contentType from the headers. - if (this.source && - this.source.text !== "[no source]" && - this._contentType && - (this._contentType.indexOf("javascript") !== -1 || - this._contentType === "text/wasm")) { - return toResolvedContent(this.source.text); - } - else { - // Only load the HTML page source from cache (which exists when - // there are inline sources). Otherwise, we can't trust the - // cache because we are most likely here because we are - // fetching the original text for sourcemapped code, and the - // page hasn't requested it before (if it has, it was a - // previous debugging session). - let loadFromCache = this.isInlineSource; - - // Fetch the sources with the same principal as the original document - let win = this.threadActor._parent.window; - let principal, cacheKey; - // On xpcshell, we don't have a window but a Sandbox - if (!isWorker && win instanceof Ci.nsIDOMWindow) { - let webNav = win.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIWebNavigation); - let channel = webNav.currentDocumentChannel; - principal = channel.loadInfo.loadingPrincipal; - - // Retrieve the cacheKey in order to load POST requests from cache - // Note that chrome:// URLs don't support this interface. - if (loadFromCache && - webNav.currentDocumentChannel instanceof Ci.nsICacheInfoChannel) { - cacheKey = webNav.currentDocumentChannel.cacheKey; - assert( - cacheKey, - "Could not fetch the cacheKey from the related document." - ); - } - } - - let sourceFetched = fetch(this.url, { - principal, - cacheKey, - loadFromCache - }); - - // Record the contentType we just learned during fetching - return sourceFetched - .then(result => { - this._contentType = result.contentType; - return result; - }, error => { - this._reportLoadSourceError(error, map); - throw error; - }); - } - }); - }, - - /** - * Get all executable lines from the current source - * @return Array - Executable lines of the current script - **/ - getExecutableLines: function () { - function sortLines(lines) { - // Converting the Set into an array - lines = [...lines]; - lines.sort((a, b) => { - return a - b; - }); - return lines; - } - - if (this.generatedSource) { - return this.threadActor.sources.getSourceMap(this.generatedSource).then(sm => { - let lines = new Set(); - - // Position of executable lines in the generated source - let offsets = this.getExecutableOffsets(this.generatedSource, false); - for (let offset of offsets) { - let {line, source: sourceUrl} = sm.originalPositionFor({ - line: offset.lineNumber, - column: offset.columnNumber - }); - - if (sourceUrl === this.url) { - lines.add(line); - } - } - - return sortLines(lines); - }); - } - - let lines = this.getExecutableOffsets(this.source, true); - return sortLines(lines); - }, - - /** - * Extract all executable offsets from the given script - * @param String url - extract offsets of the script with this url - * @param Boolean onlyLine - will return only the line number - * @return Set - Executable offsets/lines of the script - **/ - getExecutableOffsets: function (source, onlyLine) { - let offsets = new Set(); - for (let s of this.dbg.findScripts({ source })) { - for (let offset of s.getAllColumnOffsets()) { - offsets.add(onlyLine ? offset.lineNumber : offset); - } - } - - return offsets; - }, - - /** - * Handler for the "source" packet. - */ - onSource: function () { - return Promise.resolve(this._init) - .then(this._getSourceText) - .then(({ content, contentType }) => { - return { - source: createValueGrip(content, this.threadActor.threadLifetimePool, - this.threadActor.objectGrip), - contentType: contentType - }; - }) - .then(null, aError => { - reportError(aError, "Got an exception during SA_onSource: "); - throw new Error("Could not load the source for " + this.url + ".\n" + - DevToolsUtils.safeErrorString(aError)); - }); - }, - - /** - * Handler for the "prettyPrint" packet. - */ - prettyPrint: function (indent) { - this.threadActor.sources.prettyPrint(this.url, indent); - return this._getSourceText() - .then(this._sendToPrettyPrintWorker(indent)) - .then(this._invertSourceMap) - .then(this._encodeAndSetSourceMapURL) - .then(() => { - // We need to reset `_init` now because we have already done the work of - // pretty printing, and don't want onSource to wait forever for - // initialization to complete. - this._init = null; - }) - .then(this.onSource) - .then(null, error => { - this.disablePrettyPrint(); - throw new Error(DevToolsUtils.safeErrorString(error)); - }); - }, - - /** - * Return a function that sends a request to the pretty print worker, waits on - * the worker's response, and then returns the pretty printed code. - * - * @param Number aIndent - * The number of spaces to indent by the code by, when we send the - * request to the pretty print worker. - * @returns Function - * Returns a function which takes an AST, and returns a promise that - * is resolved with `{ code, mappings }` where `code` is the pretty - * printed code, and `mappings` is an array of source mappings. - */ - _sendToPrettyPrintWorker: function (aIndent) { - return ({ content }) => { - return this.prettyPrintWorker.performTask("pretty-print", { - url: this.url, - indent: aIndent, - source: content - }); - }; - }, - - /** - * Invert a source map. So if a source map maps from a to b, return a new - * source map from b to a. We need to do this because the source map we get - * from _generatePrettyCodeAndMap goes the opposite way we want it to for - * debugging. - * - * Note that the source map is modified in place. - */ - _invertSourceMap: function ({ code, mappings }) { - const generator = new SourceMapGenerator({ file: this.url }); - return DevToolsUtils.yieldingEach(mappings._array, m => { - let mapping = { - generated: { - line: m.originalLine, - column: m.originalColumn - } - }; - if (m.source) { - mapping.source = m.source; - mapping.original = { - line: m.generatedLine, - column: m.generatedColumn - }; - mapping.name = m.name; - } - generator.addMapping(mapping); - }).then(() => { - generator.setSourceContent(this.url, code); - let consumer = SourceMapConsumer.fromSourceMap(generator); - - return { - code: code, - map: consumer - }; - }); - }, - - /** - * Save the source map back to our thread's ThreadSources object so that - * stepping, breakpoints, debugger statements, etc can use it. If we are - * pretty printing a source mapped source, we need to compose the existing - * source map with our new one. - */ - _encodeAndSetSourceMapURL: function ({ map: sm }) { - let source = this.generatedSource || this.source; - let sources = this.threadActor.sources; - - return sources.getSourceMap(source).then(prevMap => { - if (prevMap) { - // Compose the source maps - this._oldSourceMapping = { - url: source.sourceMapURL, - map: prevMap - }; - - prevMap = SourceMapGenerator.fromSourceMap(prevMap); - prevMap.applySourceMap(sm, this.url); - sm = SourceMapConsumer.fromSourceMap(prevMap); - } - - let sources = this.threadActor.sources; - sources.clearSourceMapCache(source.sourceMapURL); - sources.setSourceMapHard(source, null, sm); - }); - }, - - /** - * Handler for the "disablePrettyPrint" packet. - */ - disablePrettyPrint: function () { - let source = this.generatedSource || this.source; - let sources = this.threadActor.sources; - let sm = sources.getSourceMap(source); - - sources.clearSourceMapCache(source.sourceMapURL, { hard: true }); - - if (this._oldSourceMapping) { - sources.setSourceMapHard(source, - this._oldSourceMapping.url, - this._oldSourceMapping.map); - this._oldSourceMapping = null; - } - - this.threadActor.sources.disablePrettyPrint(this.url); - return this.onSource(); - }, - - /** - * Handler for the "blackbox" packet. - */ - blackbox: function () { - this.threadActor.sources.blackBox(this.url); - if (this.threadActor.state == "paused" - && this.threadActor.youngestFrame - && this.threadActor.youngestFrame.script.url == this.url) { - return true; - } - return false; - }, - - /** - * Handler for the "unblackbox" packet. - */ - unblackbox: function () { - this.threadActor.sources.unblackBox(this.url); - }, - - /** - * Handle a request to set a breakpoint. - * - * @param Number line - * Line to break on. - * @param Number column - * Column to break on. - * @param String condition - * A condition which must be true for breakpoint to be hit. - * @param Boolean noSliding - * If true, disables breakpoint sliding. - * - * @returns Promise - * A promise that resolves to a JSON object representing the - * response. - */ - setBreakpoint: function (line, column, condition, noSliding) { - if (this.threadActor.state !== "paused") { - throw { - error: "wrongState", - message: "Cannot set breakpoint while debuggee is running." - }; - } - - let location = new OriginalLocation(this, line, column); - return this._getOrCreateBreakpointActor( - location, - condition, - noSliding - ).then((actor) => { - let response = { - actor: actor.actorID, - isPending: actor.isPending - }; - - let actualLocation = actor.originalLocation; - if (!actualLocation.equals(location)) { - response.actualLocation = actualLocation.toJSON(); - } - - return response; - }); - }, - - /** - * Get or create a BreakpointActor for the given location in the original - * source, and ensure it is set as a breakpoint handler on all scripts that - * match the given location. - * - * @param OriginalLocation originalLocation - * An OriginalLocation representing the location of the breakpoint in - * the original source. - * @param String condition - * A string that is evaluated whenever the breakpoint is hit. If the - * string evaluates to false, the breakpoint is ignored. - * @param Boolean noSliding - * If true, disables breakpoint sliding. - * - * @returns BreakpointActor - * A BreakpointActor representing the breakpoint. - */ - _getOrCreateBreakpointActor: function (originalLocation, condition, noSliding) { - let actor = this.breakpointActorMap.getActor(originalLocation); - if (!actor) { - actor = new BreakpointActor(this.threadActor, originalLocation); - this.threadActor.threadLifetimePool.addActor(actor); - this.breakpointActorMap.setActor(originalLocation, actor); - } - - actor.condition = condition; - - return this._setBreakpoint(actor, noSliding); - }, - - /* - * Ensure the given BreakpointActor is set as a breakpoint handler on all - * scripts that match its location in the original source. - * - * If there are no scripts that match the location of the BreakpointActor, - * we slide its location to the next closest line (for line breakpoints) or - * column (for column breakpoint) that does. - * - * If breakpoint sliding fails, then either there are no scripts that contain - * any code for the given location, or they were all garbage collected before - * the debugger started running. We cannot distinguish between these two - * cases, so we insert the BreakpointActor in the BreakpointActorMap as - * a pending breakpoint. Whenever a new script is introduced, this method is - * called again for each pending breakpoint. - * - * @param BreakpointActor actor - * The BreakpointActor to be set as a breakpoint handler. - * @param Boolean noSliding - * If true, disables breakpoint sliding. - * - * @returns A Promise that resolves to the given BreakpointActor. - */ - _setBreakpoint: function (actor, noSliding) { - const { originalLocation } = actor; - const { originalLine, originalSourceActor } = originalLocation; - - if (!this.isSourceMapped) { - const generatedLocation = GeneratedLocation.fromOriginalLocation(originalLocation); - if (!this._setBreakpointAtGeneratedLocation(actor, generatedLocation) && - !noSliding) { - const query = { line: originalLine }; - // For most cases, we have a real source to query for. The - // only time we don't is for HTML pages. In that case we want - // to query for scripts in an HTML page based on its URL, as - // there could be several sources within an HTML page. - if (this.source) { - query.source = this.source; - } else { - query.url = this.url; - } - const scripts = this.dbg.findScripts(query); - - // Never do breakpoint sliding for column breakpoints. - // Additionally, never do breakpoint sliding if no scripts - // exist on this line. - // - // Sliding can go horribly wrong if we always try to find the - // next line with valid entry points in the entire file. - // Scripts may be completely GCed and we never knew they - // existed, so we end up sliding through whole functions to - // the user's bewilderment. - // - // We can slide reliably if any scripts exist, however, due - // to how scripts are kept alive. A parent Debugger.Script - // keeps all of its children alive, so as long as we have a - // valid script, we can slide through it and know we won't - // slide through any of its child scripts. Additionally, if a - // script gets GCed, that means that all parents scripts are - // GCed as well, and no scripts will exist on those lines - // anymore. We will never slide through a GCed script. - if (originalLocation.originalColumn || scripts.length === 0) { - return Promise.resolve(actor); - } - - // Find the script that spans the largest amount of code to - // determine the bounds for sliding. - const largestScript = scripts.reduce((largestScript, script) => { - if (script.lineCount > largestScript.lineCount) { - return script; - } - return largestScript; - }); - const maxLine = largestScript.startLine + largestScript.lineCount - 1; - - let actualLine = originalLine; - for (; actualLine <= maxLine; actualLine++) { - const loc = new GeneratedLocation(this, actualLine); - if (this._setBreakpointAtGeneratedLocation(actor, loc)) { - break; - } - } - - // The above loop should never complete. We only did breakpoint sliding - // because we found scripts on the line we started from, - // which means there must be valid entry points somewhere - // within those scripts. - assert( - actualLine <= maxLine, - "Could not find any entry points to set a breakpoint on, " + - "even though I was told a script existed on the line I started " + - "the search with." - ); - - // Update the actor to use the new location (reusing a - // previous breakpoint if it already exists on that line). - const actualLocation = new OriginalLocation(originalSourceActor, actualLine); - const existingActor = this.breakpointActorMap.getActor(actualLocation); - this.breakpointActorMap.deleteActor(originalLocation); - if (existingActor) { - actor.delete(); - actor = existingActor; - } else { - actor.originalLocation = actualLocation; - this.breakpointActorMap.setActor(actualLocation, actor); - } - } - - return Promise.resolve(actor); - } else { - return this.sources.getAllGeneratedLocations(originalLocation).then((generatedLocations) => { - this._setBreakpointAtAllGeneratedLocations( - actor, - generatedLocations - ); - - return actor; - }); - } - }, - - _setBreakpointAtAllGeneratedLocations: function (actor, generatedLocations) { - let success = false; - for (let generatedLocation of generatedLocations) { - if (this._setBreakpointAtGeneratedLocation( - actor, - generatedLocation - )) { - success = true; - } - } - return success; - }, - - /* - * Ensure the given BreakpointActor is set as breakpoint handler on all - * scripts that match the given location in the generated source. - * - * @param BreakpointActor actor - * The BreakpointActor to be set as a breakpoint handler. - * @param GeneratedLocation generatedLocation - * A GeneratedLocation representing the location in the generated - * source for which the given BreakpointActor is to be set as a - * breakpoint handler. - * - * @returns A Boolean that is true if the BreakpointActor was set as a - * breakpoint handler on at least one script, and false otherwise. - */ - _setBreakpointAtGeneratedLocation: function (actor, generatedLocation) { - let { - generatedSourceActor, - generatedLine, - generatedColumn, - generatedLastColumn - } = generatedLocation; - - // Find all scripts that match the given source actor and line - // number. - const query = { line: generatedLine }; - if (generatedSourceActor.source) { - query.source = generatedSourceActor.source; - } else { - query.url = generatedSourceActor.url; - } - let scripts = this.dbg.findScripts(query); - - scripts = scripts.filter((script) => !actor.hasScript(script)); - - // Find all entry points that correspond to the given location. - let entryPoints = []; - if (generatedColumn === undefined) { - // This is a line breakpoint, so we are interested in all offsets - // that correspond to the given line number. - for (let script of scripts) { - let offsets = script.getLineOffsets(generatedLine); - if (offsets.length > 0) { - entryPoints.push({ script, offsets }); - } - } - } else { - // This is a column breakpoint, so we are interested in all column - // offsets that correspond to the given line *and* column number. - for (let script of scripts) { - let columnToOffsetMap = script.getAllColumnOffsets() - .filter(({ lineNumber }) => { - return lineNumber === generatedLine; - }); - for (let { columnNumber: column, offset } of columnToOffsetMap) { - if (column >= generatedColumn && column <= generatedLastColumn) { - entryPoints.push({ script, offsets: [offset] }); - } - } - } - } - - if (entryPoints.length === 0) { - return false; - } - setBreakpointAtEntryPoints(actor, entryPoints); - return true; - } -}); - -// exports.SourceActor = SourceActor; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/ScriptStore.js b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/ScriptStore.js deleted file mode 100755 index cbd9830ec1..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/ScriptStore.js +++ /dev/null @@ -1,219 +0,0 @@ -/* -*- indent-tabs-mode: nil; js-indent-level: 2; js-indent-level: 2 -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -const { noop } = DevToolsUtils; - -/** - * A `ScriptStore` is a cache of `Debugger.Script` instances. It holds strong - * references to the cached scripts to alleviate the GC-sensitivity issues that - * plague `Debugger.prototype.findScripts`, but this means that its lifetime - * must be managed carefully. It is the `ScriptStore` user's responsibility to - * ensure that the `ScriptStore` stays up to date. - * - * Implementation Notes: - * - * The ScriptStore's prototype methods are very hot, in general. To help the - * JIT, they avoid ES6-isms and higher-order iteration functions, for the most - * part. You might be wondering why we don't maintain indices on, say, - * Debugger.Source for faster querying, if these methods are so hot. First, the - * hottest method is actually just getting all scripts; second, populating the - * store becomes prohibitively expensive. So we fall back to linear queries - * (which isn't so bad, because Debugger.prototype.findScripts is also linear). - */ -function ScriptStore() { - // Set of every Debugger.Script in the cache. - this._scripts = new NoDeleteSet; -} - -// module.exports = ScriptStore; - -ScriptStore.prototype = { - // Populating a ScriptStore. - - /** - * Add one script to the cache. - * - * @param Debugger.Script script - */ - addScript: function(script) { - this._scripts.add(script); - }, - - /** - * Add many scripts to the cache at once. - * - * @param Array scripts - * The set of Debugger.Scripts to add to the cache. - */ - addScripts: function(scripts) { - for (var i = 0, len = scripts.length; i < len; i++) { - this.addScript(scripts[i]); - } - }, - - // Querying a ScriptStore. - - /** - * Get all the sources for which we have scripts cached. - * - * @returns Array of Debugger.Source - */ - getSources: function() { - return [...new Set(this._scripts.items.map(s => s.source))]; - }, - - /** - * Get all the scripts in the cache. - * - * @returns read-only Array of Debugger.Script. - * - * NB: The ScriptStore retains ownership of the returned array, and the - * ScriptStore's consumers MUST NOT MODIFY its contents! - */ - getAllScripts: function() { - return this._scripts.items; - }, - - getScriptsBySourceActor: function(sourceActor) { - return sourceActor.source ? - this.getScriptsBySource(sourceActor.source) : - this.getScriptsByURL(sourceActor._originalUrl); - }, - - getScriptsBySourceActorAndLine: function(sourceActor, line) { - return sourceActor.source ? - this.getScriptsBySourceAndLine(sourceActor.source, line) : - this.getScriptsByURLAndLine(sourceActor._originalUrl, line); - }, - - /** - * Get all scripts produced from the given source. - * - * @param Debugger.Source source - * @returns Array of Debugger.Script - */ - getScriptsBySource: function(source) { - var results = []; - var scripts = this._scripts.items; - var length = scripts.length; - for (var i = 0; i < length; i++) { - if (scripts[i].source === source) { - results.push(scripts[i]); - } - } - return results; - }, - - /** - * Get all scripts produced from the given source whose source code definition - * spans the given line. - * - * @param Debugger.Source source - * @param Number line - * @returns Array of Debugger.Script - */ - getScriptsBySourceAndLine: function(source, line) { - var results = []; - var scripts = this._scripts.items; - var length = scripts.length; - for (var i = 0; i < length; i++) { - var script = scripts[i]; - if (script.source === source && - script.startLine <= line && - (script.startLine + script.lineCount) > line) { - results.push(script); - } - } - return results; - }, - - /** - * Get all scripts defined by a source at the given URL. - * - * @param String url - * @returns Array of Debugger.Script - */ - getScriptsByURL: function(url) { - var results = []; - var scripts = this._scripts.items; - var length = scripts.length; - for (var i = 0; i < length; i++) { - if (scripts[i].url === url) { - results.push(scripts[i]); - } - } - return results; - }, - - /** - * Get all scripts defined by a source a the given URL and whose source code - * definition spans the given line. - * - * @param String url - * @param Number line - * @returns Array of Debugger.Script - */ - getScriptsByURLAndLine: function(url, line) { - var results = []; - var scripts = this._scripts.items; - var length = scripts.length; - for (var i = 0; i < length; i++) { - var script = scripts[i]; - if (script.url === url && - script.startLine <= line && - (script.startLine + script.lineCount) > line) { - results.push(script); - } - } - return results; - }, -}; - - -/** - * A set which can only grow, and does not support the delete operation. - * Provides faster iteration than the native Set by maintaining an array of all - * items, in addition to the internal set of all items, which allows direct - * iteration (without the iteration protocol and calling into C++, which are - * both expensive). - */ -function NoDeleteSet() { - this._set = new Set(); - this.items = []; -} - -NoDeleteSet.prototype = { - /** - * An array containing every item in the set for convenience and faster - * iteration. This is public for reading only, and consumers MUST NOT modify - * this array! - */ - items: null, - - /** - * Add an item to the set. - * - * @param any item - */ - add: function(item) { - if (!this._set.has(item)) { - this._set.add(item); - this.items.push(item); - } - }, - - /** - * Return true if the item is in the set, false otherwise. - * - * @param any item - * @returns Boolean - */ - has: function(item) { - return this._set.has(item); - } -}; diff --git a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js b/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js deleted file mode 100755 index ced3724138..0000000000 --- a/native/cocos/scripting/js-bindings/script/debugger/actors/utils/TabSources.js +++ /dev/null @@ -1,847 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict"; - -// const { Ci, Cu } = require("chrome"); -// const DevToolsUtils = require("devtools/shared/DevToolsUtils"); -// const { assert, fetch } = DevToolsUtils.; -// const EventEmitter = require("devtools/shared/event-emitter"); -// const { OriginalLocation, GeneratedLocation } = require("devtools/server/actors/common"); -// const { resolve } = require("promise"); -// const { joinURI } = require("devtools/shared/path"); - -// loader.lazyRequireGetter(this, "SourceActor", "devtools/server/actors/source", true); -// loader.lazyRequireGetter(this, "isEvalSource", "devtools/server/actors/source", true); -// loader.lazyRequireGetter(this, "SourceMapConsumer", "source-map", true); -// loader.lazyRequireGetter(this, "SourceMapGenerator", "source-map", true); - -/** - * Manages the sources for a thread. Handles source maps, locations in the - * sources, etc for ThreadActors. - */ -function TabSources(threadActor, allowSourceFn = () => true) { - EventEmitter.decorate(this); - - this._thread = threadActor; - this._useSourceMaps = true; - this._autoBlackBox = true; - this._anonSourceMapId = 1; - this.allowSource = source => { - return !isHiddenSource(source) && allowSourceFn(source); - }; - - this.blackBoxedSources = new Set(); - this.prettyPrintedSources = new Map(); - this.neverAutoBlackBoxSources = new Set(); - - // generated Debugger.Source -> promise of SourceMapConsumer - this._sourceMaps = new Map(); - // sourceMapURL -> promise of SourceMapConsumer - this._sourceMapCache = Object.create(null); - // Debugger.Source -> SourceActor - this._sourceActors = new Map(); - // url -> SourceActor - this._sourceMappedSourceActors = Object.create(null); -} - -/** - * Matches strings of the form "foo.min.js" or "foo-min.js", etc. If the regular - * expression matches, we can be fairly sure that the source is minified, and - * treat it as such. - */ -const MINIFIED_SOURCE_REGEXP = /\bmin\.js$/; - -TabSources.prototype = { - /** - * Update preferences and clear out existing sources - */ - reconfigure: function(options) { - if ('useSourceMaps' in options) { - this._useSourceMaps = options.useSourceMaps; - } - - if ('autoBlackBox' in options) { - this._autoBlackBox = options.autoBlackBox; - } - - this.reset(); - }, - - /** - * Update preferences and clear out existing sources - */ - setOptions: function (options) { - let shouldReset = false; - - if ("useSourceMaps" in options) { - shouldReset = true; - this._useSourceMaps = options.useSourceMaps; - } - - if ("autoBlackBox" in options) { - shouldReset = true; - this._autoBlackBox = options.autoBlackBox; - } - - if (shouldReset) { - this.reset(); - } - }, - - /** - * Clear existing sources so they are recreated on the next access. - * - * @param Object opts - * Specify { sourceMaps: true } if you also want to clear - * the source map cache (usually done on reload). - */ - reset: function (opts = {}) { - this._sourceActors = new Map(); - this._sourceMaps = new Map(); - this._sourceMappedSourceActors = Object.create(null); - - if (opts.sourceMaps) { - this._sourceMapCache = Object.create(null); - } - }, - - /** - * Return the source actor representing the `source` (or - * `originalUrl`), creating one if none exists already. May return - * null if the source is disallowed. - * - * @param Debugger.Source source - * The source to make an actor for - * @param String originalUrl - * The original source URL of a sourcemapped source - * @param optional Debguger.Source generatedSource - * The generated source that introduced this source via source map, - * if any. - * @param optional String contentType - * The content type of the source, if immediately available. - * @returns a SourceActor representing the source or null. - */ - source: function ({ source, originalUrl, generatedSource, - isInlineSource, contentType }) { - DevToolsUtils.assert(source || (originalUrl && generatedSource), - "TabSources.prototype.source needs an originalUrl or a source"); - - if (source) { - // If a source is passed, we are creating an actor for a real - // source, which may or may not be sourcemapped. - - if (!this.allowSource(source)) { - return null; - } - - // It's a hack, but inline HTML scripts each have real sources, - // but we want to represent all of them as one source as the - // HTML page. The actor representing this fake HTML source is - // stored in this array, which always has a URL, so check it - // first. - if (source.url in this._sourceMappedSourceActors) { - return this._sourceMappedSourceActors[source.url]; - } - - if (isInlineSource) { - // If it's an inline source, the fake HTML source hasn't been - // created yet (would have returned above), so flip this source - // into a sourcemapped state by giving it an `originalUrl` which - // is the HTML url. - originalUrl = source.url; - source = null; - } - else if (this._sourceActors.has(source)) { - return this._sourceActors.get(source); - } - } - else if (originalUrl) { - // Not all "original" scripts are distinctly separate from the - // generated script. Pretty-printed sources have a sourcemap for - // themselves, so we need to make sure there a real source - // doesn't already exist with this URL. - for (let [source, actor] of this._sourceActors) { - if (source.url === originalUrl) { - return actor; - } - } - - if (originalUrl in this._sourceMappedSourceActors) { - return this._sourceMappedSourceActors[originalUrl]; - } - } - - let actor = new SourceActor({ - thread: this._thread, - source: source, - originalUrl: originalUrl, - generatedSource: generatedSource, - isInlineSource: isInlineSource, - contentType: contentType - }); - - let sourceActorStore = this._thread.sourceActorStore; - var id = sourceActorStore.getReusableActorId(source, originalUrl); - if (id) { - actor.actorID = id; - } - - this._thread.threadLifetimePool.addActor(actor); - sourceActorStore.setReusableActorId(source, originalUrl, actor.actorID); - - if (this._autoBlackBox && - !this.neverAutoBlackBoxSources.has(actor.url) && - this._isMinifiedURL(actor.url)) { - - this.blackBox(actor.url); - this.neverAutoBlackBoxSources.add(actor.url); - } - - if (source) { - this._sourceActors.set(source, actor); - } - else { - this._sourceMappedSourceActors[originalUrl] = actor; - } - - this._emitNewSource(actor); - return actor; - }, - - _emitNewSource: function (actor) { - if (!actor.source) { - // Always notify if we don't have a source because that means - // it's something that has been sourcemapped, or it represents - // the HTML file that contains inline sources. - this.emit("newSource", actor); - } - else { - // If sourcemapping is enabled and a source has sourcemaps, we - // create `SourceActor` instances for both the original and - // generated sources. The source actors for the generated - // sources are only for internal use, however; breakpoints are - // managed by these internal actors. We only want to notify the - // user of the original sources though, so if the actor has a - // `Debugger.Source` instance and a valid source map (meaning - // it's a generated source), don't send the notification. - this.fetchSourceMap(actor.source).then(map => { - if (!map) { - this.emit("newSource", actor); - } - }); - } - }, - - getSourceActor: function (source) { - if (source.url in this._sourceMappedSourceActors) { - return this._sourceMappedSourceActors[source.url]; - } - - if (this._sourceActors.has(source)) { - return this._sourceActors.get(source); - } - - throw new Error("getSource: could not find source actor for " + - (source.url || "source")); - }, - - getSourceActorByURL: function (url) { - if (url) { - for (let [source, actor] of this._sourceActors) { - if (source.url === url) { - return actor; - } - } - - if (url in this._sourceMappedSourceActors) { - return this._sourceMappedSourceActors[url]; - } - } - - throw new Error("getSourceActorByURL: could not find source for " + url); - return null; - }, - - /** - * Returns true if the URL likely points to a minified resource, false - * otherwise. - * - * @param String aURL - * The URL to test. - * @returns Boolean - */ - _isMinifiedURL: function (aURL) { - if (!aURL) { - return false; - } - - try { - let url = new URL(aURL); - let pathname = url.pathname; - return MINIFIED_SOURCE_REGEXP.test(pathname.slice(pathname.lastIndexOf("/") + 1)); - } catch (e) { - // Not a valid URL so don't try to parse out the filename, just test the - // whole thing with the minified source regexp. - return MINIFIED_SOURCE_REGEXP.test(aURL); - } - }, - - /** - * Create a source actor representing this source. This ignores - * source mapping and always returns an actor representing this real - * source. Use `createSourceActors` if you want to respect source maps. - * - * @param Debugger.Source aSource - * The source instance to create an actor for. - * @returns SourceActor - */ - createNonSourceMappedActor: function (aSource) { - // Don't use getSourceURL because we don't want to consider the - // displayURL property if it's an eval source. We only want to - // consider real URLs, otherwise if there is a URL but it's - // invalid the code below will not set the content type, and we - // will later try to fetch the contents of the URL to figure out - // the content type, but it's a made up URL for eval sources. - let url = isEvalSource(aSource) ? null : aSource.url; - let spec = { source: aSource }; - - // XXX bug 915433: We can't rely on Debugger.Source.prototype.text - // if the source is an HTML-embedded