issue #2823: load js file in firefox.

This commit is contained in:
James Chen 2013-10-07 10:50:12 +08:00
parent d033411bbe
commit b5679cbc3a
3 changed files with 466 additions and 36 deletions

View File

@ -392,7 +392,6 @@ JSBool ScriptingCore::evalString(const char *string, jsval *outVal, const char *
global = global_;
JSScript* script = JS_CompileScript(cx, global, string, strlen(string), filename, 1);
if (script) {
// JSAutoCompartment ac(cx, global);
JSAutoCompartment ac(cx, global);
JSBool evaluatedOK = JS_ExecuteScript(cx, global, script, outVal);
if (JS_FALSE == evaluatedOK) {
@ -463,19 +462,23 @@ void ScriptingCore::createGlobalContext() {
this->cx_ = JS_NewContext(rt_, 8192);
JS_SetOptions(this->cx_, JSOPTION_TYPE_INFERENCE);
JS_SetVersion(this->cx_, JSVERSION_LATEST);
// JS_SetVersion(this->cx_, JSVERSION_LATEST);
// Only disable METHODJIT on iOS.
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
JS_SetOptions(this->cx_, JS_GetOptions(this->cx_) & ~JSOPTION_METHODJIT);
JS_SetOptions(this->cx_, JS_GetOptions(this->cx_) & ~JSOPTION_METHODJIT_ALWAYS);
#endif
//#if (CC_TARGET_PLATFORM == CC_PLATFORM_
// JS_SetOptions(this->cx_, JS_GetOptions(this->cx_) & ~JSOPTION_METHODJIT);
// JS_SetOptions(this->cx_, JS_GetOptions(this->cx_) & ~JSOPTION_METHODJIT_ALWAYS);
//#endif
JS_SetErrorReporter(this->cx_, ScriptingCore::reportError);
#if defined(JS_GC_ZEAL) && defined(DEBUG)
//JS_SetGCZeal(this->cx_, 2, JS_DEFAULT_ZEAL_FREQ);
#endif
this->global_ = NewGlobalObject(cx_);
JSAutoCompartment ac(cx_, global_);
#if JSB_ENABLE_DEBUGGER
JS_SetDebugMode(cx_, JS_TRUE);
#endif
@ -500,6 +503,8 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c
if (!path) {
return false;
}
cocos2d::FileUtils *futil = cocos2d::FileUtils::getInstance();
std::string fullPath = futil->fullPathForFilename(path);
if (global == NULL) {
@ -508,7 +513,12 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c
if (cx == NULL) {
cx = cx_;
}
JSScript *script = NULL;
JSAutoCompartment ac(cx, global);
uint32_t oldopts = JS_GetOptions(cx);
JS_SetOptions(cx, oldopts | JSOPTION_COMPILE_N_GO | JSOPTION_NO_SCRIPT_RVAL);
js::RootedObject obj(cx, global);
JS::CompileOptions options(cx);
options.setUTF8(true).setFileAndLine(fullPath.c_str(), 1);
@ -519,6 +529,8 @@ JSBool ScriptingCore::runScript(const char *path, JSObject* global, JSContext* c
void *data = futil->getFileData(byteCodePath.c_str(),
"rb",
&length);
js::RootedScript script(cx);
if (data) {
script = JS_DecodeScript(cx, data, length, NULL, NULL);
CC_SAFE_DELETE_ARRAY(data);
@ -930,15 +942,16 @@ JSBool ScriptingCore::executeFunctionWithOwner(jsval owner, const char *name, ui
do
{
JSAutoCompartment ac(cx, obj);
if (JS_HasProperty(cx, obj, name, &hasAction) && hasAction) {
if (!JS_GetProperty(cx, obj, name, &temp_retval)) {
break;
}
if (temp_retval == JSVAL_VOID) {
break;
}
}
JSAutoCompartment ac(cx, obj);
if (retVal) {
bRet = JS_CallFunctionName(cx, obj, name, argc, vp, retVal);
}
@ -1099,6 +1112,8 @@ int ScriptingCore::sendEvent(ScriptEvent* evt)
{
if (NULL == evt)
return 0;
JSAutoCompartment ac(cx_, global_);
switch (evt->type)
{
@ -1199,7 +1214,7 @@ JSBool jsval_to_long_long(JSContext *cx, jsval vp, long long* r) {
}
JSBool jsval_to_std_string(JSContext *cx, jsval v, std::string* ret) {
JSString *tmp = v.isString() ? JS_ValueToString(cx, v) : NULL;
JSString *tmp = JS_ValueToString(cx, v);
JSB_PRECONDITION3(tmp, cx, JS_FALSE, "Error processing arguments");
JSStringWrapper str(tmp);
@ -1736,14 +1751,24 @@ jsval long_long_to_jsval(JSContext* cx, long long v) {
return OBJECT_TO_JSVAL(tmp);
}
jsval std_string_to_jsval(JSContext* cx, const std::string& v) {
return c_string_to_jsval(cx, v.c_str());
jsval std_string_to_jsval(JSContext* cx, const std::string& v)
{
return c_string_to_jsval(cx, v.c_str(), v.size());
}
jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */) {
if (v == NULL) {
jsval c_string_to_jsval(JSContext* cx, const char* v, size_t length /* = -1 */)
{
if (v == NULL)
{
return JSVAL_NULL;
}
if (0 == length)
{
auto emptyStr = JS_NewStringCopyZ(cx, "");
return STRING_TO_JSVAL(emptyStr);
}
jsval ret = JSVAL_NULL;
int utf16_size = 0;
jschar* strUTF16 = (jschar*)cc_utf8_to_utf16(v, length, &utf16_size);
@ -1914,6 +1939,8 @@ void SimpleRunLoop::update(float dt) {
}
void ScriptingCore::debugProcessInput(string str) {
JSAutoCompartment ac(cx_, debugGlobal_);
JSString* jsstr = JS_NewStringCopyZ(cx_, str.c_str());
jsval argv[3] = {
STRING_TO_JSVAL(jsstr),
@ -1921,12 +1948,13 @@ void ScriptingCore::debugProcessInput(string str) {
script
};
jsval outval;
JSAutoCompartment ac(cx_, debugGlobal_);
JS_CallFunctionName(cx_, debugGlobal_, "processInput", 3, argv, &outval);
}
void ScriptingCore::enableDebugger() {
if (debugGlobal_ == NULL) {
JSAutoCompartment ac0(cx_, global_);
debugGlobal_ = NewGlobalObject(cx_, true);
JS_WrapObject(cx_, &debugGlobal_);
JSAutoCompartment ac(cx_, debugGlobal_);
@ -1940,6 +1968,7 @@ void ScriptingCore::enableDebugger() {
runScript("jsb_debugger.js", debugGlobal_);
// runScript("SysTest/script.js", debugGlobal_);
CCLOG("before _prepareDebugger...");
// prepare the debugger
jsval argv = OBJECT_TO_JSVAL(global_);
jsval outval;
@ -1947,6 +1976,8 @@ void ScriptingCore::enableDebugger() {
if (!ok) {
JS_ReportPendingException(cx_);
}
CCLOG("after _prepareDebugger...");
// define the start debugger function
JS_DefineFunction(cx_, global_, "startDebugger", JSBDebug_StartDebugger, 3, JSPROP_READONLY | JSPROP_PERMANENT);
// start bg thread
@ -1954,6 +1985,7 @@ void ScriptingCore::enableDebugger() {
auto t = std::thread(&serverEntryPoint);
t.detach();
CCLOG("after _prepareDebugger...02");
Scheduler* scheduler = Director::getInstance()->getScheduler();
scheduler->scheduleUpdateForTarget(this->runLoop, 0, false);
}
@ -1991,15 +2023,23 @@ JSBool jsGetScript(JSContext* cx, unsigned argc, jsval* vp)
JSObject* NewGlobalObject(JSContext* cx, bool debug)
{
JSObject* glob = JS_NewGlobalObject(cx, &global_class, NULL);
if (!glob) {
JS::CompartmentOptions options;
options.setZone(JS::FreshZone)
.setVersion(JSVERSION_LATEST);
JS::RootedObject glob(cx, JS_NewGlobalObject(cx, &global_class, NULL, options));
if (!glob)
{
return NULL;
}
JSAutoCompartment ac(cx, glob);
JSBool ok = JS_TRUE;
ok = JS_InitStandardClasses(cx, glob);
if (ok)
JS_InitReflect(cx, glob);
{
ok = JS_InitReflect(cx, glob) != NULL;
}
if (ok && debug)
ok = JS_DefineDebuggerObject(cx, glob);
if (!ok)
@ -2240,14 +2280,18 @@ static void serverEntryPoint(void)
// read/write data
TRACE_DEBUGGER_SERVER("debug server : client connected");
if (recieveIndex == 0)
{
replyToClient(clientSocket, "{\"from\":\"root\",\"applicationType\":\"browser\",\"traits\":{\"sources\": true}}");
++recieveIndex;
}
inData = "connected";
// process any input, send any output
clearBuffers();
// if (recieveIndex == 0)
// {
// replyToClient(clientSocket, "{\"from\":\"root\",\"applicationType\":\"browser\",\"traits\":{\"sources\": true}}");
// ++recieveIndex;
// }
char buf[256] = {0};
char buf[1024] = {0};
int readBytes = 0;
while ((readBytes = ::recv(clientSocket, buf, sizeof(buf), 0)) > 0)
{

View File

@ -192,7 +192,7 @@ public:
void debugProcessInput(string str);
void enableDebugger();
JSObject* getDebugGlobal() { return debugGlobal_; }
JSObject* getGlobalObject() { return global_; }
JSObject* getGlobalObject() { return global_ ? global_ : debugGlobal_; }
private:
void string_report(jsval val);

View File

@ -1,4 +1,8 @@
dbg = {};
dbg = {
LONG_STRING_LENGTH: 10000,
LONG_STRING_INITIAL_LENGTH: 1000,
LONG_STRING_READ_LENGTH: 1000
};
dbg.log = log;
var textCommandProcessor = {};
@ -299,7 +303,39 @@ jsonResponder.onBreakpoint = function (filename, linenumber) {
"data" : {"jsfilename" : filename,
"linenumber" : linenumber}};
this.write(JSON.stringify(response));
dbg.log("onBreakpoint: " + JSON.stringify(response));
var breakInfo = { "from":"tabThreadActor111", "type":"paused", "actor":"pauseActor",
"why":{ "type":"breakpoint", "actors":["breakpointActor1"] },
"frame":{ "actor":"frameActor", "depth":1,
"type":"call", "where":{ "url":"sample.js", "line":3 },
"environment":{ "type":"function", "actor":"gFrameActor",
"function":{ "type":"object", "class":"Function", "actor":"gActor" },
"functionName":"g",
"bindings":{ arguments: [ { "y": { "value":"argument to g", "configurable":"false",
"writable":true, "enumerable":true } } ] },
"parent":{ "type":"function", "actor":"fFrameActor",
"function":{ "type":"object", "class":"Function", "actor":"fActor" },
"functionName":"f",
"bindings": { arguments: [ { "x": { "value":"argument to f", "configurable":"false",
"writable":true, "enumerable":true } } ],
variables: { "z": { "value":"value of z", "configurable":"false",
"writable":true, "enumerable":true } } },
"parent":{ "type":"object", "actor":"globalCodeActor",
"object":{ "type":"object", "class":"Global",
"actor":"globalObjectActor" }
}
}
},
"callee":"gActor", "calleeName":"g",
"this":{ "type":"object", "class":"Function", "actor":"gActor" },
"arguments":["argument to g"]
}
};
_RDPWrite(breakInfo);
//this.write(JSON.stringify(response));
}
jsonResponder.onStep = function (filename, linenumber) {
@ -332,10 +368,45 @@ textResponder.write = function (str) {
_bufferWrite(String.fromCharCode(23));
}
textResponder.onBreakpoint = function (filename, linenumber) {
var shortFilename = filename.substring(filename.lastIndexOf("/") + 1);
var response = "Breakpoint hit at " + shortFilename + " line number : " + linenumber;
this.write(response);
var breakpointFrame = null;
textResponder.onBreakpoint = function (frame) {//filename, linenumber) {
// var shortFilename = filename.substring(filename.lastIndexOf("/") + 1);
// var response = "Breakpoint hit at " + shortFilename + " line number : " + linenumber;
// dbg.log("textResponder.onBreakpoint:"+response);
var breakInfo = { "from":"tabThreadActor111", "type":"paused", "actor":"pauseActor",
"why":{ "type":"breakpoint", "actors":["breakpointActor1"] },
"frame":{ "actor":"frameActor", "depth":1,
"type":"call", "where":{ "url":"sample.js", "line":3 },
"environment":{ "type":"function", "actor":"gFrameActor",
"function":{ "type":"object", "class":"Function", "actor":"gActor" },
"functionName":"g",
"bindings":{ arguments: [ { "y": { "value":"argument to g", "configurable":"false",
"writable":true, "enumerable":true } } ] },
"parent":{ "type":"function", "actor":"fFrameActor",
"function":{ "type":"object", "class":"Function", "actor":"fActor" },
"functionName":"f",
"bindings": { arguments: [ { "x": { "value":"argument to f", "configurable":"false",
"writable":true, "enumerable":true } } ],
variables: { "z": { "value":"value of z", "configurable":"false",
"writable":true, "enumerable":true } } },
"parent":{ "type":"object", "actor":"globalCodeActor",
"object":{ "type":"object", "class":"Global",
"actor":"globalObjectActor" }
}
}
},
"callee":"gActor", "calleeName":"g",
"this":{ "type":"object", "class":"Function", "actor":"gActor" },
"arguments":["argument to g"]
}
};
breakpointFrame = frame;
_RDPWrite(breakInfo);
// this.write(response);
}
textResponder.onStep = function (filename, linenumber) {
@ -420,8 +491,9 @@ textResponder.commandNotFound = function () {
var breakpointHandler = {
hit: function (frame) {
dbg.log("breakpointHandler hit");
try {
dbg.responder.onBreakpoint(frame.script.url, frame.script.getOffsetLine(frame.offset));
dbg.responder.onBreakpoint(frame);//frame.script.url, frame.script.getOffsetLine(frame.offset));
} catch (e) {
dbg.log("exception " + e);
}
@ -487,6 +559,71 @@ var debugObject = function (r, isNormal) {
dbg.breakLine = 0;
dbg.scriptSourceActorMap = {};
addFiles = function() {
for (var key in dbg.scripts)
{
dbg.log("sources:" + key);
var scripts = dbg.scripts[key];
for (var i = 0; i < scripts.length; ++i)
{
dbg.log("url:" + scripts[i].source.url);
dbg.log("-----------");
dbg.scriptSourceActorMap[key+"_SourceActor"] = scripts[i];
_RDPWrite(
{
from: "tabThreadActor111",
type: "newSource",
source: {
actor: key+"_SourceActor",
url: "file://" + scripts[i].source.url,
isBlackBoxed: false
}
});
}
}
};
addInitialSource = function(sourceActor, script)
{
_RDPWrite(
{
from: sourceActor,
source: {
type: "longString",
initial: script.source.text.substring(0, dbg.LONG_STRING_INITIAL_LENGTH),
length: script.source.text.length,
actor: sourceActor+"_LongString"
}
});
}
addSource = function(longStringActor, script)
{
_RDPWrite(
{
from: longStringActor,
substring: script.source.text
});
}
isStringStartWith = function (str, substring) {
var reg = new RegExp("^"+substring);
return reg.test(str);
};
isStringEndsWith = function (str, substring) {
var reg = new RegExp(substring + "$");
return reg.test(str);
};
var breakpointActorIndex = 0;
this.processInput = function (inputstr, frame, script) {
var command_func;
var command_return;
@ -498,6 +635,240 @@ this.processInput = function (inputstr, frame, script) {
return;
}
// var testStr = "104:{\
// \"to\": \"tabThreadActor111\",\
// \"type\": \"resume\",\
// \"resumeLimit\": null,\
// \"pauseOnExceptions\": false\
// }60:{\
// \"to\": \"ActionsTest.js_SourceActor\",\
// \"type\": \"source\"\
// }";
// for (var i = 0; i < testArr.length; ++i)
// {
// dbg.log("split: " +"{"+ testArr[i] + ",length= "+testArr.length);
// }
var inputArr = inputstr.split(/\d+:{/g);
if (inputArr.length > 1)
{
inputArr.shift();
for (var i = 0; i < inputArr.length; ++i) {
// dbg.log("---> "+inputArr[i]);
processInput("{"+inputArr[i], frame, script);
}
return;
}
// dbg.log("inputStr:"+inputstr);
if (inputstr === "connected")
{
var rootInit = {from:"root",applicationType:"browser",traits:{sources: true}};
_RDPWrite(rootInit);
return;
}
// var semi = inputstr.indexOf(":");
// if (semi === -1)
// {
// dbg.log("wrong input remote debugger protocol string.");
// return;
// }
var jsonStr = inputstr;//.substring(semi+1);
dbg.log("jsonStr:" + jsonStr);
var jsonObj = JSON.parse(jsonStr);
// for (var key in jsonObj)
// {
// dbg.log("["+key+"]="+jsonObj[key]);
// }
if (jsonObj.to === "root" && jsonObj.type === "listTabs")
{
_RDPWrite({ from:"root", tabs:[{ actor:"JSBTabActor", title:"Hello cocos2d-x JSB", url:"http://www.cocos2d-x.org" }], selected:0 });
}
else if (jsonObj.to === "JSBTabActor" && jsonObj.type === "attach")
{
_RDPWrite({ from:"JSBTabActor", type:"tabAttached", threadActor:"tabThreadActor111" });
}
else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "attach")
{
_RDPWrite(
{
from: "tabThreadActor111",
type: "paused",
actor: "JSBTabActor",
poppedFrames: [],
why: {
type: "attached"
}
});
}
else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "sources")
{
addFiles();
}
else if (jsonObj.to && isStringEndsWith(jsonObj.to, "_SourceActor") && jsonObj.type === "source")
{
dbg.log("require source ...: " + jsonObj.to);
var script = dbg.scriptSourceActorMap[jsonObj.to];
if (script)
{
addInitialSource(jsonObj.to, script);
}
}
else if (jsonObj.to && isStringEndsWith(jsonObj.to, "_LongString") && jsonObj.type === "substring")
{
var sourceActor = jsonObj.to.substring(0, jsonObj.to.length-"_LongString".length);
dbg.log("source actor: " + sourceActor);
var script = dbg.scriptSourceActorMap[sourceActor];
if (script)
{
addSource(jsonObj.to, script);
}
_RDPWrite({
from: "tabThreadActor111",
type: "resumed"
});
}
else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "resume")
{
dbg.log("resume type to server....");
_RDPWrite({
from: "tabThreadActor111",
type: "resumed"
});
}
else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "setBreakpoint")
{
++breakpointActorIndex;
var scripts = dbg.scripts[jsonObj.location.url],
tmpScript = null;
if (scripts) {
var breakLine = jsonObj.location.line,
off = -1;
for (var n=0; n < scripts.length; n++) {
offsets = scripts[n].getLineOffsets(breakLine);
if (offsets.length > 0) {
off = offsets[0];
tmpScript = scripts[n];
break;
}
}
if (off >= 0) {
tmpScript.setBreakpoint(off, breakpointHandler);
// return ({commandname : "break",
// success : true,
// jsfilename : md[2],
// breakpointlinenumber : breakLine});
} else {
// return ({commandname : "break",
// success : false,
// stringResult : "no valid offsets at that line"});
}
} else {
// return ({commandname : "break",
// success : false,
// jsfilename : md[2],
// stringResult : "Invalid script name"});
}
_RDPWrite({ from: "tabThreadActor111", "actor":"breakpointActor"+breakpointActorIndex});
// jsonObj.location.url
// jsonObj.location.line
}
else if (isStringStartWith(jsonObj.to, "breakpointActor") && jsonObj.type === "delete")
{
_RDPWrite({ from: jsonObj.to });
}
else if (jsonObj.to === "tabThreadActor111" && jsonObj.type === "frames")
{
dbg.log("sdfsld...."+breakpointFrame.arguments);
// var arr = breakpointFrame.getOwnPropertyNames();
// log("names: "+ arr);
var parentEnv = breakpointFrame.environment.parent;
log("parentEnv:" + parentEnv);
log("parentEnv.type:" + parentEnv.type);
log("parentEnv.actor:" + parentEnv.actor);
log("parentEnv.functionName:" + parentEnv.functionName);
log("parentEnv.object:" + parentEnv.object);
log("parentEnv.object.type:" + parentEnv.object.type);
log("parentEnv.object.class:" + parentEnv.object.class);
var keys = Object.keys(parentEnv.object);
log("keys: " + keys);
parentEnv = parentEnv.parent;
log("2parentEnv:" + parentEnv);
log("parentEnv.type:" + parentEnv.type);
log("parentEnv.actor:" + parentEnv.actor);
log("parentEnv.functionName:" + parentEnv.functionName);
var bindings = parentEnv.bindings;
log("bindings:" + bindings);
var args = bindings.arguments;
log("args:"+args);
var vars = bindings.variables;
log("vars:" + vars);
// if (breakpointFrame != null)
{
dbg.log("get frames.....");
var obj = {
"from": "tabThreadActor111",
"frame":{ "actor":"frameActor", "depth":1,
"type":"call", "where":{ "url":"sample.js", "line":3 },
"environment":{ "type":"function", "actor":"gFrameActor",
"function":{ "type":"object", "class":"Function", "actor":"gActor" },
"functionName":"g",
"bindings":{ arguments: [ { "y": { "value":"argument to g", "configurable":"false",
"writable":true, "enumerable":true } } ] },
"parent":{ "type":"function", "actor":"fFrameActor",
"function":{ "type":"object", "class":"Function", "actor":"fActor" },
"functionName":"f",
"bindings": { arguments: [ { "x": { "value":"argument to f", "configurable":"false",
"writable":true, "enumerable":true } } ],
variables: { "z": { "value":"value of z", "configurable":"false",
"writable":true, "enumerable":true } } },
"parent":{ "type":"object", "actor":"globalCodeActor",
"object":{ "type":"object", "class":"Global",
"actor":"globalObjectActor" }
}
}
},
"callee":"gActor", "calleeName":"g",
"this":{ "type":"object", "class":"Function", "actor":"gActor" },
"arguments":["argument to g"]
}};
_RDPWrite(obj);
breakpointFrame = null;
}
}
else if (jsonObj.type === "interrupt")
{
_RDPWrite({
from: "tabThreadActor111",
type: "resumed"
});
}
return;
// remove Carriage Return's
inputstr = inputstr.replace(/\r+/, "");
@ -570,9 +941,15 @@ _printHelp = function() {
dbg.scripts = [];
_RDPWrite = function(jsonObj){
var buf = JSON.stringify(jsonObj);
_bufferWrite("" + buf.length + ":" + buf);
};
dbg.onNewScript = function (script) {
dbg.log("onNewScript, "+script.url);
// skip if the url is this script
var last = script.url.split("/").pop();
// var last = script.url.split("/").pop();
var children = script.getChildScripts(),
arr = [script].concat(children);
@ -584,9 +961,13 @@ dbg.onNewScript = function (script) {
var offsets = arr[i].getLineOffsets(j);
dbg.log(" off: " + offsets.join(",") + "; line: " + j);
}
}
*/
dbg.scripts[last] = arr;
}*/
dbg.scripts["file://"+script.url] = arr;
// dbg.log("source: "+script.source.text);
};
dbg.onError = function (frame, report) {
@ -596,6 +977,11 @@ dbg.onError = function (frame, report) {
dbg.log("!! exception");
};
dbg.onDebuggerStatement = function(frame)
{
dbg.log("onDebuggerStatement...");
};
this._prepareDebugger = function (global) {
var tmp = new Debugger(global);
tmp.onNewScript = dbg.onNewScript;