Merge pull request #799 from dumganhar/jsb2.0

ExceptionCallback has specific parameter( location, message, stack ), script could also add listener for script exception
This commit is contained in:
James Chen
2017-09-06 05:05:07 -05:00
committed by GitHub
8 changed files with 264 additions and 108 deletions
@@ -72,6 +72,7 @@ namespace se {
, _globalObj(nullptr)
, _isValid(false)
, _isInCleanup(false)
, _isErrorHandleWorking(false)
, _isGarbageCollecting(false)
, _currentSourceContext(0)
, _exceptionCallback(nullptr)
@@ -107,6 +108,8 @@ namespace se {
_globalObj = Object::_createJSObject(nullptr, globalObj);
_globalObj->root();
_globalObj->setProperty("scriptEngineType", se::Value("ChakraCore"));
_globalObj->defineFunction("log", __log);
_globalObj->defineFunction("forceGC", __forceGC);
@@ -168,56 +171,37 @@ namespace se {
NonRefNativePtrCreatedByCtorMap::destroy();
}
std::string ScriptEngine::formatException(JsValueRef exception)
ScriptEngine::ExceptionInfo ScriptEngine::formatException(JsValueRef exception)
{
std::string ret;
JsValueRef propertyNames = JS_INVALID_REFERENCE;
JsGetOwnPropertyNames(exception, &propertyNames);
JsValueType type;
_CHECK(JsGetValueType(propertyNames, &type));
assert(type == JsArray);
ExceptionInfo ret;
if (exception == JS_INVALID_REFERENCE)
return ret;
for (int i = 0; ; ++i)
std::vector<std::string> allKeys;
Object* exceptionObj = Object::_createJSObject(nullptr, exception);
exceptionObj->getAllKeys(&allKeys);
for (const auto& key : allKeys)
{
JsValueRef index = JS_INVALID_REFERENCE;
JsValueRef result = JS_INVALID_REFERENCE;
_CHECK(JsIntToNumber(i, &index));
if (JsNoError != JsGetIndexedProperty(propertyNames, index, &result))
break;
JsGetValueType(result, &type);
if (type == JsUndefined)
break;
assert(type == JsString);
Value key;
internal::jsToSeValue(result, &key);
std::string keyStr = key.toString();
if (keyStr == "stack")
Value tmp;
if (exceptionObj->getProperty(key.c_str(), &tmp))
{
JsPropertyIdRef propertyId = JS_INVALID_REFERENCE;
if (JsCreatePropertyId(keyStr.c_str(), keyStr.length(), &propertyId) != JsNoError)
// LOGD("[%s]=%s\n", key.c_str(), tmp.toStringForce().c_str());
if (key == "message")
{
return "failed to get and clear exception";
ret.message = tmp.toString();
}
JsValueRef jsValue;
if (JsGetProperty(exception, propertyId, &jsValue) != JsNoError)
else if (key == "stack")
{
return "failed to get error message";
ret.stack = tmp.toString();
}
internal::forceConvertJsValueToStdString(jsValue, &ret);
// LOGD("[%s]=%s\n", keyStr.c_str(), tmp.c_str());
break;
}
}
exceptionObj->decRef();
ret.location = "(see stack)";
return ret;
}
@@ -300,11 +284,34 @@ namespace se {
JsValueRef exception;
_CHECK(JsGetAndClearException(&exception));
std::string exceptionMsg = formatException(exception);
LOGD("ERROR: %s\n", exceptionMsg.c_str());
ExceptionInfo exceptionInfo = formatException(exception);
LOGD("ERROR: %s, %s, \nSTACK:\n%s\n", exceptionInfo.message.c_str(), exceptionInfo.location.c_str(), exceptionInfo.stack.c_str());
if (_exceptionCallback != nullptr)
{
_exceptionCallback(exceptionMsg.c_str());
_exceptionCallback(exceptionInfo.location.c_str(), exceptionInfo.message.c_str(), exceptionInfo.stack.c_str());
}
if (!_isErrorHandleWorking)
{
_isErrorHandleWorking = true;
Value errorHandler;
if (_globalObj->getProperty("__errorHandler", &errorHandler) && errorHandler.isObject() && errorHandler.toObject()->isFunction())
{
ValueArray args;
args.push_back(Value(exceptionInfo.location));
args.push_back(Value(0));
args.push_back(Value(exceptionInfo.message));
args.push_back(Value(exceptionInfo.stack));
errorHandler.toObject()->call(args, _globalObj);
}
_isErrorHandleWorking = false;
}
else
{
LOGE("ERROR: __errorHandler has exception\n");
}
}
}
@@ -115,7 +115,7 @@ namespace se {
void clearException();
using ExceptionCallback = std::function<void(const char*)>;
using ExceptionCallback = std::function<void(const char*, const char*, const char*)>; // location, message, stack
void setExceptionCallback(const ExceptionCallback& cb);
@@ -137,8 +137,18 @@ namespace se {
bool _setNodeEventListener(NodeEventListener listener);
private:
struct ExceptionInfo
{
std::string location;
std::string message;
std::string stack;
std::string formatException(JsValueRef exception);
bool isValid() const
{
return !message.empty();
}
};
ExceptionInfo formatException(JsValueRef exception);
JsRuntimeHandle _rt;
JsContextRef _cx;
@@ -148,6 +158,7 @@ namespace se {
bool _isValid;
bool _isInCleanup;
bool _isGarbageCollecting;
bool _isErrorHandleWorking;
unsigned _currentSourceContext;
NodeEventListener _nodeEventListener;
@@ -86,6 +86,7 @@ namespace se {
, _isGarbageCollecting(false)
, _isValid(false)
, _isInCleanup(false)
, _isErrorHandleWorking(false)
, _exceptionCallback(nullptr)
{
}
@@ -126,6 +127,8 @@ namespace se {
_globalObj->root();
_globalObj->setProperty("window", se::Value(_globalObj));
_globalObj->setProperty("scriptEngineType", se::Value("JavaScriptCore"));
JSStringRef propertyName = JSStringCreateWithUTF8CString("log");
JSObjectSetProperty(_cx, globalObj, propertyName, JSObjectMakeFunctionWithCallback(_cx, propertyName, __log), kJSPropertyAttributeReadOnly, nullptr);
JSStringRelease(propertyName);
@@ -193,17 +196,16 @@ namespace se {
LOGD("ScriptEngine::cleanup end ...\n");
}
std::string ScriptEngine::_formatException(JSValueRef exception)
ScriptEngine::ExceptionInfo ScriptEngine::_formatException(JSValueRef exception)
{
std::string ret;
internal::forceConvertJsValueToStdString(_cx, exception, &ret);
ExceptionInfo ret;
internal::forceConvertJsValueToStdString(_cx, exception, &ret.message);
JSType type = JSValueGetType(_cx, exception);
if (type == kJSTypeObject)
{
JSObjectRef obj = JSValueToObject(_cx, exception, nullptr);
std::string strackInfo;
JSStringRef stackKey = JSStringCreateWithUTF8CString("stack");
JSValueRef stackVal = JSObjectGetProperty(_cx, obj, stackKey, nullptr);
if (stackKey != nullptr)
@@ -212,12 +214,15 @@ namespace se {
if (type == kJSTypeString)
{
JSStringRef stackStr = JSValueToStringCopy(_cx, stackVal, nullptr);
internal::jsStringToStdString(_cx, stackStr, &strackInfo);
internal::jsStringToStdString(_cx, stackStr, &ret.stack);
JSStringRelease(stackStr);
}
JSStringRelease(stackKey);
}
std::string line;
std::string column;
std::string filePath;
JSPropertyNameArrayRef nameArr = JSObjectCopyPropertyNames(_cx, obj);
size_t count =JSPropertyNameArrayGetCount(nameArr);
for (size_t i = 0; i < count; ++i)
@@ -235,19 +240,21 @@ namespace se {
if (name == "line")
{
ret += ", line: " + value;
line = value;
ret.lineno = (uint32_t)JSValueToNumber(_cx, jsValue, nullptr);
}
else if (name == "file")
else if (name == "column")
{
ret += ", file: " + value;
column = value;
}
else if (name == "sourceURL")
{
filePath = value;
ret.filePath = value;
}
}
if (!strackInfo.empty())
{
ret += "\nSTACK:\n" + strackInfo;
}
ret.location = filePath + ":" + line + ":" + column;
JSPropertyNameArrayRelease(nameArr);
}
@@ -258,14 +265,42 @@ namespace se {
{
if (exception != nullptr)
{
std::string exceptionStr = _formatException(exception);
if (!exceptionStr.empty())
ExceptionInfo exceptionInfo = _formatException(exception);
if (exceptionInfo.isValid())
{
std::string exceptionStr = exceptionInfo.message;
exceptionStr += ", location: " + exceptionInfo.location;
if (!exceptionInfo.stack.empty())
{
exceptionStr += "\nSTACK:\n" + exceptionInfo.stack;
}
LOGD("ERROR: %s\n", exceptionStr.c_str());
if (_exceptionCallback != nullptr)
{
_exceptionCallback(exceptionStr.c_str());
_exceptionCallback(exceptionInfo.location.c_str(), exceptionInfo.message.c_str(), exceptionInfo.stack.c_str());
}
if (!_isErrorHandleWorking)
{
_isErrorHandleWorking = true;
Value errorHandler;
if (_globalObj->getProperty("__errorHandler", &errorHandler) && errorHandler.isObject() && errorHandler.toObject()->isFunction())
{
ValueArray args;
args.push_back(Value(exceptionInfo.filePath));
args.push_back(Value(exceptionInfo.lineno));
args.push_back(Value(exceptionInfo.message));
args.push_back(Value(exceptionInfo.stack));
errorHandler.toObject()->call(args, _globalObj);
}
_isErrorHandleWorking = false;
}
else
{
LOGE("ERROR: __errorHandler has exception\n");
}
}
}
@@ -194,7 +194,7 @@ namespace se {
*/
void clearException();
using ExceptionCallback = std::function<void(const char*)>;
using ExceptionCallback = std::function<void(const char*, const char*, const char*)>; // location, message, stack
/**
* @brief Sets the callback function while an exception is fired.
@@ -233,7 +233,26 @@ namespace se {
ScriptEngine();
~ScriptEngine();
std::string _formatException(JSValueRef exception);
struct ExceptionInfo
{
std::string location;
std::string message;
std::string stack;
// For compatibility
std::string filePath;
uint32_t lineno;
ExceptionInfo()
: lineno(0)
{}
bool isValid() const
{
return !message.empty();
}
};
ExceptionInfo _formatException(JSValueRef exception);
JSGlobalContextRef _cx;
@@ -242,6 +261,7 @@ namespace se {
bool _isGarbageCollecting;
bool _isValid;
bool _isInCleanup;
bool _isErrorHandleWorking;
NodeEventListener _nodeEventListener;
FileOperationDelegate _fileOperationDelegate;
@@ -229,6 +229,7 @@ namespace se {
, _isGarbageCollecting(false)
, _isValid(false)
, _isInCleanup(false)
, _isErrorHandleWorking(false)
, _nodeEventListener(nullptr)
, _exceptionCallback(nullptr)
{
@@ -237,13 +238,13 @@ namespace se {
}
/* static */
void ScriptEngine::myWeakPointerCompartmentCallback(JSContext* cx, JSCompartment* comp, void* data)
void ScriptEngine::onWeakPointerCompartmentCallback(JSContext* cx, JSCompartment* comp, void* data)
{
myWeakPointerZoneGroupCallback(cx, data);
onWeakPointerZoneGroupCallback(cx, data);
}
/* static */
void ScriptEngine::myWeakPointerZoneGroupCallback(JSContext* cx, void* data)
void ScriptEngine::onWeakPointerZoneGroupCallback(JSContext* cx, void* data)
{
bool isInCleanup = getInstance()->isInCleanup();
bool isIterUpdated = false;
@@ -330,7 +331,7 @@ namespace se {
#ifdef DEBUG
JS::ContextOptionsRef(_cx)
// .setExtraWarnings(true)
.setExtraWarnings(true)
.setIon(false)
.setBaseline(false)
.setAsmJS(false);
@@ -350,16 +351,19 @@ namespace se {
_globalObj = Object::_createJSObject(nullptr, globalObj);
_globalObj->root();
JS::RootedObject rootedGlobalObj(_cx, _globalObj->_getJSObject());
_oldCompartment = JS_EnterCompartment(_cx, rootedGlobalObj);
JS_InitStandardClasses(_cx, rootedGlobalObj) ;
_globalObj->setProperty("scriptEngineType", se::Value("SpiderMonkey"));
JS_DefineFunction(_cx, rootedGlobalObj, "log", __log, 0, JSPROP_PERMANENT);
JS_DefineFunction(_cx, rootedGlobalObj, "forceGC", __forceGC, 0, JSPROP_READONLY | JSPROP_PERMANENT);
// JS_AddWeakPointerZoneGroupCallback(_cx, ScriptEngine::myWeakPointerZoneGroupCallback, nullptr);
JS_AddWeakPointerCompartmentCallback(_cx, ScriptEngine::myWeakPointerCompartmentCallback, nullptr);
// JS_AddWeakPointerZoneGroupCallback(_cx, ScriptEngine::onWeakPointerZoneGroupCallback, nullptr);
JS_AddWeakPointerCompartmentCallback(_cx, ScriptEngine::onWeakPointerCompartmentCallback, nullptr);
JS_FireOnNewGlobalObject(_cx, rootedGlobalObj);
JS::SetBuildIdOp(_cx, getBytecodeBuildId);
@@ -408,8 +412,8 @@ namespace se {
Class::cleanup();
Object::cleanup();
// JS_RemoveWeakPointerZoneGroupCallback(_cx, ScriptEngine::myWeakPointerZoneGroupCallback);
// JS_RemoveWeakPointerCompartmentCallback(_cx, ScriptEngine::myWeakPointerCompartmentCallback);
// JS_RemoveWeakPointerZoneGroupCallback(_cx, ScriptEngine::onWeakPointerZoneGroupCallback);
// JS_RemoveWeakPointerCompartmentCallback(_cx, ScriptEngine::onWeakPointerCompartmentCallback);
JS_LeaveCompartment(_cx, _oldCompartment);
JS::SetGetIncumbentGlobalCallback(_cx, nullptr);
@@ -719,28 +723,63 @@ namespace se {
assert(exceptionValue.isObject());
JS::RootedObject exceptionObj(_cx, exceptionValue.toObjectOrNull());
JSErrorReport* report = JS_ErrorFromException(_cx, exceptionObj);
const char* fileName = report->filename != nullptr ? report->filename : "(no filename)";
std::string exceptionStr = report->message().c_str();
exceptionStr += ", file: ";
exceptionStr += fileName;
char lineBuf[50] = {0};
snprintf(lineBuf, sizeof(lineBuf), "%u", report->lineno);
exceptionStr += lineBuf;
const char* message = report->message().c_str();
const std::string filePath = report->filename != nullptr ? report->filename : "(no filename)";
char line[50] = {0};
snprintf(line, sizeof(line), "%u", report->lineno);
char column[50] = {0};
snprintf(column, sizeof(column), "%u", report->column);
const std::string location = filePath + ":" + line + ":" + column;
JS::RootedValue stack(_cx);
if (JS_GetProperty(_cx, exceptionObj, "stack", &stack) && stack.isString())
char* stack = nullptr; // Need to be freed by JS_free
JS::RootedValue stackVal(_cx);
if (JS_GetProperty(_cx, exceptionObj, "stack", &stackVal) && stackVal.isString())
{
JS::RootedString jsstackStr(_cx, stackVal.toString());
stack = JS_EncodeStringToUTF8(_cx, jsstackStr);
}
std::string exceptionStr = message;
exceptionStr += ", location: " + location;
if (stack != nullptr)
{
JS::RootedString jsstackStr(_cx, stack.toString());
char* stackStr = JS_EncodeStringToUTF8(_cx, jsstackStr);
exceptionStr += "\nSTACK:\n";
exceptionStr += stackStr;
JS_free(_cx, stackStr);
exceptionStr += stack;
}
LOGE("ERROR: %s\n", exceptionStr.c_str());
if (_exceptionCallback != nullptr)
{
_exceptionCallback(exceptionStr.c_str());
_exceptionCallback(location.c_str(), message, stack);
}
if (!_isErrorHandleWorking)
{
_isErrorHandleWorking = true;
Value errorHandler;
if (_globalObj->getProperty("__errorHandler", &errorHandler) && errorHandler.isObject() && errorHandler.toObject()->isFunction())
{
ValueArray args;
args.push_back(Value(filePath));
args.push_back(Value(report->lineno));
args.push_back(Value(message));
args.push_back(Value(stack));
errorHandler.toObject()->call(args, _globalObj);
}
_isErrorHandleWorking = false;
}
else
{
LOGE("ERROR: __errorHandler has exception\n");
}
if (stack != nullptr)
{
JS_free(_cx, stack);
stack = nullptr;
}
}
}
@@ -101,7 +101,7 @@ namespace se {
void clearException();
using ExceptionCallback = std::function<void(const char*)>;
using ExceptionCallback = std::function<void(const char*, const char*, const char*)>; // location, message, stack
void setExceptionCallback(const ExceptionCallback& cb);
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
@@ -123,8 +123,8 @@ namespace se {
bool _setNodeEventListener(NodeEventListener listener);
private:
static void myWeakPointerCompartmentCallback(JSContext* cx, JSCompartment* comp, void* data);
static void myWeakPointerZoneGroupCallback(JSContext* cx, void* data);
static void onWeakPointerCompartmentCallback(JSContext* cx, JSCompartment* comp, void* data);
static void onWeakPointerZoneGroupCallback(JSContext* cx, void* data);
bool getScript(const std::string& path, JS::MutableHandleScript script);
bool compileScript(const std::string& path, JS::MutableHandleScript script);
@@ -137,6 +137,7 @@ namespace se {
bool _isGarbageCollecting;
bool _isValid;
bool _isInCleanup;
bool _isErrorHandleWorking;
NodeEventListener _nodeEventListener;
FileOperationDelegate _fileOperationDelegate;
@@ -46,7 +46,7 @@ namespace se {
std::string stackTraceToString(v8::Local<v8::StackTrace> stack)
{
std::string stackStr = "STACK:\n";
std::string stackStr;
char tmp[100] = {0};
for (int i = 0, e = stack->GetFrameCount(); i < e; ++i)
{
@@ -86,7 +86,7 @@ namespace se {
}
} // namespace {
void ScriptEngine::myFatalErrorCallback(const char* location, const char* message)
void ScriptEngine::onFatalErrorCallback(const char* location, const char* message)
{
std::string errorStr = "[FATAL ERROR] location: ";
errorStr += location;
@@ -96,44 +96,83 @@ namespace se {
LOGE("%s\n", errorStr.c_str());
if (getInstance()->_exceptionCallback != nullptr)
{
getInstance()->_exceptionCallback(errorStr.c_str());
getInstance()->_exceptionCallback(location, message, "(no stack information)");
}
}
void ScriptEngine::myOOMErrorCallback(const char* location, bool is_heap_oom)
void ScriptEngine::onOOMErrorCallback(const char* location, bool is_heap_oom)
{
std::string errorStr = "[OOM ERROR] location: ";
errorStr += location;
errorStr += ", is heap out of memory: ";
std::string message;
message = "is heap out of memory: ";
if (is_heap_oom)
errorStr += "true";
message += "true";
else
errorStr += "false";
message += "false";
errorStr += ", " + message;
LOGE("%s\n", errorStr.c_str());
if (getInstance()->_exceptionCallback != nullptr)
{
getInstance()->_exceptionCallback(errorStr.c_str());
getInstance()->_exceptionCallback(location, message.c_str(), "(no stack information)");
}
}
void ScriptEngine::myMessageCallback(v8::Local<v8::Message> message, v8::Local<v8::Value> data)
void ScriptEngine::onMessageCallback(v8::Local<v8::Message> message, v8::Local<v8::Value> data)
{
ScriptEngine* thiz = getInstance();
v8::Local<v8::String> msg = message->Get();
se::Value msgVal;
Value msgVal;
internal::jsToSeValue(v8::Isolate::GetCurrent(), msg, &msgVal);
assert(msgVal.isString());
std::string errorStr = msgVal.toString();
v8::ScriptOrigin origin = message->GetScriptOrigin();
Value resouceNameVal;
internal::jsToSeValue(v8::Isolate::GetCurrent(), origin.ResourceName(), &resouceNameVal);
Value line;
internal::jsToSeValue(v8::Isolate::GetCurrent(), origin.ResourceLineOffset(), &line);
Value column;
internal::jsToSeValue(v8::Isolate::GetCurrent(), origin.ResourceColumnOffset(), &column);
std::string location = resouceNameVal.toString() + ":" + line.toStringForce() + ":" + column.toStringForce();
std::string errorStr = msgVal.toString() + ", " + location;
std::string stackStr = stackTraceToString(message->GetStackTrace());
if (!stackStr.empty())
{
errorStr += "\n" + stackStr;
if (line.toInt32() == 0)
{
location = "(see stack)";
}
errorStr += "\nSTACK:\n" + stackStr;
}
LOGE("ERROR: %s\n", errorStr.c_str());
if (getInstance()->_exceptionCallback != nullptr)
if (thiz->_exceptionCallback != nullptr)
{
getInstance()->_exceptionCallback(errorStr.c_str());
thiz->_exceptionCallback(location.c_str(), msgVal.toString().c_str(), stackStr.c_str());
}
if (!thiz->_isErrorHandleWorking)
{
thiz->_isErrorHandleWorking = true;
Value errorHandler;
if (thiz->_globalObj->getProperty("__errorHandler", &errorHandler) && errorHandler.isObject() && errorHandler.toObject()->isFunction())
{
ValueArray args;
args.push_back(resouceNameVal);
args.push_back(line);
args.push_back(msgVal);
args.push_back(Value(stackStr));
errorHandler.toObject()->call(args, thiz->_globalObj);
}
thiz->_isErrorHandleWorking = false;
}
else
{
LOGE("ERROR: __errorHandler has exception\n");
}
}
@@ -175,6 +214,7 @@ namespace se {
, _isValid(false)
, _isGarbageCollecting(false)
, _isInCleanup(false)
, _isErrorHandleWorking(false)
, _nodeEventListener(nullptr)
, _exceptionCallback(nullptr)
#if SE_ENABLE_INSPECTOR
@@ -219,9 +259,9 @@ namespace se {
_isolate->SetCaptureStackTraceForUncaughtExceptions(true, 20, v8::StackTrace::kOverview);
_isolate->SetFatalErrorHandler(myFatalErrorCallback);
_isolate->SetOOMErrorHandler(myOOMErrorCallback);
_isolate->AddMessageListener(myMessageCallback);
_isolate->SetFatalErrorHandler(onFatalErrorCallback);
_isolate->SetOOMErrorHandler(onOOMErrorCallback);
_isolate->AddMessageListener(onMessageCallback);
_context.Reset(_isolate, v8::Context::New(_isolate));
_context.Get(_isolate)->Enter();
@@ -235,6 +275,8 @@ namespace se {
_globalObj = Object::_createJSObject(nullptr, _context.Get(_isolate)->Global());
_globalObj->root();
_globalObj->setProperty("scriptEngineType", se::Value("V8"));
_globalObj->defineFunction("log", __log);
_globalObj->defineFunction("forceGC", __forceGC);
@@ -135,7 +135,7 @@ namespace se {
void clearException();
using ExceptionCallback = std::function<void(const char*)>;
using ExceptionCallback = std::function<void(const char*, const char*, const char*)>; // location, message, stack
void setExceptionCallback(const ExceptionCallback& cb);
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
@@ -159,9 +159,9 @@ namespace se {
private:
static void privateDataFinalize(void* nativeObj);
static void myFatalErrorCallback(const char* location, const char* message);
static void myOOMErrorCallback(const char* location, bool is_heap_oom);
static void myMessageCallback(v8::Local<v8::Message> message, v8::Local<v8::Value> data);
static void onFatalErrorCallback(const char* location, const char* message);
static void onOOMErrorCallback(const char* location, bool is_heap_oom);
static void onMessageCallback(v8::Local<v8::Message> message, v8::Local<v8::Value> data);
v8::Platform* _platform;
v8::Isolate* _isolate;
@@ -177,6 +177,7 @@ namespace se {
bool _isValid;
bool _isGarbageCollecting;
bool _isInCleanup;
bool _isErrorHandleWorking;
NodeEventListener _nodeEventListener;
FileOperationDelegate _fileOperationDelegate;