void MD_Runner::run() { fprintf(stderr, "V8 version %s [mordor shell]\n", v8::V8::GetVersion()); v8::Platform* v8_platform = v8::platform::CreateDefaultPlatform(1); v8::V8::InitializeICU(); v8::V8::InitializePlatform(v8_platform); v8::V8::Initialize(); int argc = g_argc; v8::V8::SetFlagsFromCommandLine(&argc, g_argv, true); v8::V8::SetFlagsFromString(MD_V8_OPTIONS, sizeof(MD_V8_OPTIONS) - 1); v8::V8::SetArrayBufferAllocator(&ArrayBufferAllocator::the_singleton); v8::Isolate* isolate = v8::Isolate::New(); { v8::Isolate::Scope isolate_scope(isolate); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); Environment* env = Environment::New(context, Scheduler::getThis()); ProcessObject po(env); po.setup(); { Coroutine<const char*> coReadScript(&readScript); const char* script; bool running = true; do { script = coReadScript.call(); if (coReadScript.state() == Fiber::State::TERM) { break; } v8::HandleScope handle_scope(context->GetIsolate()); v8::Local<v8::String> script_str = Utf8String(isolate, script); ExecuteString(env, script_str, Utf8String(isolate, "md_shell")); running = env->running(); } while (running); std::cout << "bye." << std::endl; } Environment::environment.reset(); } isolate->Dispose(); LineEditor* line_editor = LineEditor::Get(); if (line_editor) line_editor->Close(); v8::V8::Dispose(); v8::V8::ShutdownPlatform(); delete v8_platform; this->over(); }
void statSync(const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handle_scope(isolate); String::Utf8Value path(args[0]->ToString()); boost::filesystem::file_status rawStats = fs::status(boost::filesystem::path(*path)); Local<Object> statObj = Object::New(isolate); // Check dir bool isDir = false; if(rawStats.type() == boost::filesystem::directory_file){ isDir = true; } statObj->Set(v8::String::NewFromUtf8(isolate, "isDirectory"), v8::Boolean::New(isolate, isDir)); // Check symbolic link bool isSymbolic = false; if(rawStats.type() == boost::filesystem::symlink_file){ isSymbolic = true; } statObj->Set(v8::String::NewFromUtf8(isolate, "isSymbolicLink"), v8::Boolean::New(isolate, isSymbolic)); args.GetReturnValue().Set(statObj); return; }
TEST_F(JSDeviceTest, createTemplate) { HandleScope handle_scope(isolate); Local<Context> context = Context::New(isolate, nullptr); Context::Scope context_scope(context); Handle<Object> global = context->Global(); jsDevice->initJsObjectsTemplate(isolate, global); }
v8::Local<v8::Map> Msg_Struct::build_object_map(const Field_Info &field_info, Block_Buffer &buffer, Isolate* isolate) { EscapableHandleScope handle_scope(isolate); uint16_t vec_size = 0; buffer.read_uint16(vec_size); Local<Map> map = Map::New(isolate); if(is_struct(field_info.field_type)) { for(uint16_t i = 0; i < vec_size; ++i) { Local<Object> object = build_object_struct(field_info, buffer, isolate); Local<Value> key = object->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, field_info.key_name.c_str(), NewStringType::kNormal).ToLocalChecked()).ToLocalChecked(); map->Set(isolate->GetCurrentContext(), key, object).ToLocalChecked(); } } else { Field_Info key_info; key_info.field_label = "args"; key_info.field_type = field_info.key_type; key_info.field_name = field_info.key_name; Local<Value> key = build_object_arg(key_info, buffer, isolate); Local<Value> value = build_object_arg(field_info, buffer, isolate); map->Set(isolate->GetCurrentContext(), key, value).ToLocalChecked(); } return handle_scope.Escape(map); }
/** * コンストラクタ */ TJSInstance::TJSInstance(Isolate *isolate, Local<Object> &obj, const tTJSVariant &variant) : isolate(isolate), TJSBase(variant) { HandleScope handle_scope(isolate); // Javascript オブジェクトに格納 wrap(isolate, obj); self.Reset(isolate, obj); self.SetWeak(this, release); iTJSDispatch2 *objthis = variant.AsObjectNoAddRef(); // TJSインスタンスにネイティブインスタンスとして登録しておく iTJSNativeInstance *ninstance = this; objthis->NativeInstanceSupport(TJS_NIS_REGISTER, classId, &ninstance); // callJS メソッド登録 tCallJSFunction *callJS = new tCallJSFunction(); if (callJS) { tTJSVariant val(callJS, objthis); objthis->PropSet(TJS_MEMBERENSURE, TJS_W("callJS"), NULL, &val, objthis); callJS->Release(); } // missing メソッド登録 tMissingFunction *missing = new tMissingFunction(); if (missing) { tTJSVariant val(missing, objthis); const tjs_char *missingName = TJS_W("missing"); objthis->PropSet(TJS_MEMBERENSURE, missingName, NULL, &val, objthis); missing->Release(); // missing 有効化 tTJSVariant name(missingName); objthis->ClassInstanceInfo(TJS_CII_SET_MISSING, 0, &name); } }
// メソッド呼び出し共通処理 tjs_error TJSInstance::callMethod(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, tTJSVariant *result, tjs_int numparams, tTJSVariant **param, iTJSDispatch2 *objthis) { HandleScope handle_scope(isolate); Context::Scope context_scope(getContext()); TryCatch try_catch; Local<Object> context = membername ? obj : objthis ? toJSValue(isolate, tTJSVariant(objthis))->ToObject() : getContext()->Global(); Local<Object> method = membername ? obj->Get(String::NewFromTwoByte(isolate, membername))->ToObject() : obj; if (!method->IsFunction()) { return TJS_E_NOTIMPL; } // 関数抽出 Local<Function> func = Local<Function>::Cast(method); // 引数 Handle<Value> *argv = new Handle<Value>[numparams]; for (int i=0;i<numparams;i++) { argv[i] = toJSValue(isolate, *param[i]); } Local<Value> ret = func->Call(context, numparams, argv); delete argv; if (ret.IsEmpty()) { JSEXCEPTION(isolate, &try_catch); } else { if (result) { *result = toVariant(isolate, ret); } } return TJS_S_OK; }
// プロパティ取得共通処理 tjs_error TJSInstance::getProp(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, tTJSVariant *result) { if (!membername) { return TJS_E_NOTIMPL; } HandleScope handle_scope(isolate); Context::Scope context_scope(getContext()); TryCatch try_catch; Local<Value> ret = obj->Get(String::NewFromTwoByte(isolate, membername)); if (ret.IsEmpty()) { return TJS_E_MEMBERNOTFOUND; } else { if (result) { if (ret->IsFunction()) { *result = toVariant(isolate, ret->ToObject(), obj); } else { *result = toVariant(isolate, ret); } } } return TJS_S_OK; }
bool SMJS_Plugin::LoadFile(const char* file, bool asGlobal){ HandleScope handle_scope(isolate); char path[512]; #if WIN32 snprintf(path, sizeof(path), "%s\\%s", GetPath(), file); #else snprintf(path, sizeof(path), "%s/%s", GetPath(), file); #endif FILE* fileHandle = fopen(path, "rb"); if(fileHandle == NULL) return false; fseek(fileHandle, 0, SEEK_END); size_t size = ftell(fileHandle); rewind(fileHandle); char* source = new char[size + 1]; for (size_t i = 0; i < size;) { i += fread(&source[i], 1, size - i, fileHandle); } source[size] = '\0'; fclose(fileHandle); bool res = RunString(path, source, asGlobal); delete[] source; return res; }
Local<Object> wrap_master_player(Isolate* isolate, Master_Player *player) { EscapableHandleScope handle_scope(isolate); Local<ObjectTemplate> localTemplate = ObjectTemplate::New(isolate); localTemplate->SetInternalFieldCount(1); Local<External> player_ptr = External::New(isolate, player); //将指针存在V8对象内部 Local<Object> player_obj = localTemplate->NewInstance(isolate->GetCurrentContext()).ToLocalChecked(); player_obj->SetInternalField(0, player_ptr); // 为当前对象设置其对外函数接口 player_obj->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "get_save_data_buffer", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, get_master_player_save_data_buffer)->GetFunction()) ; player_obj->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "respond_success_result", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, master_player_respond_success_result)->GetFunction()) ; player_obj->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "respond_error_result", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, master_player_respond_error_result)->GetFunction()) ; player_obj->Set(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, "sync_data_to_game", NewStringType::kNormal).ToLocalChecked(), FunctionTemplate::New(isolate, sync_data_to_game)->GetFunction()) ; return handle_scope.Escape(player_obj); }
/* Create and return a v8 context. Thread safe. */ void msV8CreateContext(mapObj *map) { Isolate *isolate = Isolate::GetCurrent(); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); V8Context *v8context = new V8Context(isolate); Handle<ObjectTemplate> global_templ = ObjectTemplate::New(); global_templ->Set(String::New("require"), FunctionTemplate::New(msV8Require)); global_templ->Set(String::New("print"), FunctionTemplate::New(msV8Print)); global_templ->Set(String::New("alert"), FunctionTemplate::New(msV8Print)); Handle<Context> context_ = Context::New(v8context->isolate, NULL, global_templ); v8context->context.Reset(v8context->isolate, context_); /* we have to enter the context before getting global instance */ Context::Scope context_scope(context_); Handle<Object> global = context_->Global(); Shape::Initialize(global); Point::Initialize(global); Line::Initialize(global); v8context->paths.push(map->mappath); v8context->isolate->SetData(v8context); v8context->layer = NULL; map->v8context = (void*)v8context; }
void CJS_Runtime::SetReaderDocument(CPDFSDK_Document* pReaderDoc) { if (m_pDocument != pReaderDoc) { v8::Isolate::Scope isolate_scope(m_isolate); v8::HandleScope handle_scope(m_isolate); v8::Local<v8::Context> context =v8::Local<v8::Context>::New(m_isolate, m_context); v8::Context::Scope context_scope(context); m_pDocument = pReaderDoc; if (pReaderDoc) { JSObject pThis = JS_GetThisObj(*this); if(!pThis.IsEmpty()) { if (JS_GetObjDefnID(pThis) == JS_GetObjDefnID(*this, L"Document")) { if (CJS_Document* pJSDocument = (CJS_Document*)JS_GetPrivate(pThis)) { if (Document * pDocument = (Document*)pJSDocument->GetEmbedObject()) pDocument->AttachDoc(pReaderDoc); } } } JS_SetThisObj(*this, JS_GetObjDefnID(*this, L"Document")); } else { JS_SetThisObj(*this, JS_GetObjDefnID(*this, L"app")); } } }
FX_BOOL CJS_Runtime::GetValueByName(const CFX_ByteStringC& utf8Name, CFXJSE_Value* pValue) { const FX_CHAR* name = utf8Name.c_str(); v8::Isolate::Scope isolate_scope(GetIsolate()); v8::HandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> old_context = GetIsolate()->GetCurrentContext(); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(GetIsolate(), m_context); v8::Context::Scope context_scope(context); // Caution: We're about to hand to XFA an object that in order to invoke // methods will require that the current v8::Context always has a pointer // to a CJS_Runtime in its embedder data slot. Unfortunately, XFA creates // its own v8::Context which has not initialized the embedder data slot. // Do so now. // TODO(tsepez): redesign PDF-side objects to not rely on v8::Context's // embedder data slots, and/or to always use the right context. FXJS_SetRuntimeForV8Context(old_context, this); v8::Local<v8::Value> propvalue = context->Global()->Get(v8::String::NewFromUtf8( GetIsolate(), name, v8::String::kNormalString, utf8Name.GetLength())); if (propvalue.IsEmpty()) { pValue->SetUndefined(); return FALSE; } pValue->ForceSetValue(propvalue); return TRUE; }
JS1_API bool STDCALL execute_command_handler(void *script_handle, void* event_handler_handle, const uint16_t *data_json, const uint16_t *data_other[], int32_t other_length, uint16_t **result_json, void **memory_handle) { js1::QueryScript *query_script; //TODO: add v8::try_catch here (and move scope/context to this level) and make errors reportable to theC# level query_script = reinterpret_cast<js1::QueryScript *>(script_handle); js1::PreludeScope prelude_scope(query_script); v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); v8::Handle<v8::String> result; js1::Status success = query_script->execute_handler(event_handler_handle, data_json, data_other, other_length, result); if (success != js1::S_OK) { *result_json = NULL; *memory_handle = NULL; return false; } //NOTE: incorrect return types are handled in execute_handler if (!result.IsEmpty()) { v8::String::Value * result_buffer = new v8::String::Value(result); *result_json = **result_buffer; *memory_handle = result_buffer; } else { *result_json = NULL; *memory_handle = NULL; } return true; };
void readFileSync(const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Isolate* isolate = args.GetIsolate(); v8::HandleScope handle_scope(isolate); String::Utf8Value path(args[0]->ToString()); // Do we have a js file to run? std::string jsFileContents; if( !cinder::fs::exists( fs::path::path(*path) ) ){ std::string err = "File not found: "; err.append(*path); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, err.c_str()))); return; } else { try { std::ifstream in(*path, std::ios::in ); if (in) { std::ostringstream contents; contents << in.rdbuf(); jsFileContents = contents.str(); in.close(); } } catch(std::exception &e) { std::string err = "Error: "; err.append(e.what()); isolate->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(isolate, err.c_str()))); return; } } args.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, jsFileContents.c_str())); return; }
int Fragment::Script::ScriptEngine::Init(int argc, char* argv[]) { v8::V8::InitializeICU(); v8::V8::InitializeExternalStartupData(argv[0]); v8::Platform *platform = v8::platform::CreateDefaultPlatform(); v8::V8::InitializePlatform(platform); v8::V8::Initialize(); v8::V8::SetFlagsFromCommandLine(&argc, argv, true); ShellArrayBufferAllocator array_buffer_allocator; v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = &array_buffer_allocator; v8::Isolate *isolate = v8::Isolate::New(create_params); run_shell = (argc == 1); int result; { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> context = CreateShellContext(isolate); if (context.IsEmpty()) { fprintf(stderr, "Error creating context\n"); return 1; } v8::Context::Scope context_scope(context); result = RunMain(isolate, platform, argc, argv); if (run_shell) RunShell(context, platform); } isolate->Dispose(); v8::V8::Dispose(); v8::V8::ShutdownPlatform(); delete platform; return result; }
CFXJS_ObjDefinition(v8::Isolate* isolate, const wchar_t* sObjName, FXJSOBJTYPE eObjType, CFXJS_Engine::Constructor pConstructor, CFXJS_Engine::Destructor pDestructor) : m_ObjName(sObjName), m_ObjType(eObjType), m_pConstructor(pConstructor), m_pDestructor(pDestructor), m_pIsolate(isolate) { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local<v8::FunctionTemplate> fun = v8::FunctionTemplate::New(isolate); fun->InstanceTemplate()->SetInternalFieldCount(2); if (eObjType == FXJSOBJTYPE_GLOBAL) { fun->InstanceTemplate()->Set( v8::Symbol::GetToStringTag(isolate), v8::String::NewFromUtf8(isolate, "global", v8::NewStringType::kNormal) .ToLocalChecked()); } m_FunctionTemplate.Reset(isolate, fun); v8::Local<v8::Signature> sig = v8::Signature::New(isolate, fun); m_Signature.Reset(isolate, sig); }
bool SMJS_Plugin::RunString(const char* name, const char *source, bool asGlobal){ HandleScope handle_scope(isolate); Context::Scope context_scope(context); TryCatch try_catch; v8::ScriptOrigin origin(String::New(name), v8::Integer::New(0), v8::Integer::New(0)); Handle<Script> script; if(asGlobal){ script = Script::Compile(v8::String::New(source), &origin); }else{ char *buffer = new char[strlen(source) + 100]; strcpy(buffer, "(function(global){"); strcat(buffer, source); strcat(buffer, "})(this);"); script = Script::Compile(v8::String::New(buffer), &origin); delete buffer; } if(script.IsEmpty()) { // Print errors that happened during compilation. ReportException(&try_catch); return false; } else { Handle<Value> result = script->Run(); if (result.IsEmpty()) { ReportException(&try_catch); return false; } return true; } }
void JS_ReleaseRuntime(IJS_Runtime* pJSRuntime, v8::Persistent<v8::Context>& v8PersistentContext) { v8::Isolate* isolate = (v8::Isolate*)pJSRuntime; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate, v8PersistentContext); v8::Context::Scope context_scope(context); CFX_PtrArray* pArray = (CFX_PtrArray*)isolate->GetData(0); if(!pArray) return ; for(int i=0; i<pArray->GetSize(); i++) { CJS_ObjDefintion* pObjDef = (CJS_ObjDefintion*)pArray->GetAt(i); if(!pObjDef->m_StaticObj.IsEmpty()) { v8::Local<v8::Object> pObj = v8::Local<v8::Object>::New(isolate, pObjDef->m_StaticObj); if(pObjDef->m_pDestructor) pObjDef->m_pDestructor(pObj); JS_FreePrivate(pObj); } delete pObjDef; } delete pArray; isolate->SetData(0,NULL); }
static void Print(const v8::FunctionCallbackInfo<v8::Value>& args) { bool first = true; v8::Isolate* isolate = args.GetIsolate(); InterpreterData* interpreter = static_cast<InterpreterData*>(isolate->GetData(0)); for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope(isolate); if (first) { first = false; } else { printf(" "); } if (args[i]->IsObject()) { v8::String::Utf8Value str(interpreter->toJSON(args[i], true)); const char* cstr = ToCString(str); printf("%s", cstr); } else { v8::String::Utf8Value str(args[i]); const char* cstr = ToCString(str); printf("%s", cstr); } } printf("\n"); fflush(stdout); }
// コンストラクタ TJSObject::TJSObject(Isolate *isolate, Local<Object> &obj, const tTJSVariant &variant) : TJSBase(variant) { HandleScope handle_scope(isolate); wrap(isolate, obj); Persistent<Object> ref(isolate, obj); ref.SetWeak(this, release); }
// コンストラクタ呼び出し共通処理 tjs_error TJSInstance::createMethod(Isolate *isolate, Local<Object> &obj, const tjs_char *membername, iTJSDispatch2 **result, tjs_int numparams, tTJSVariant **param) { if (membername) { return TJS_E_MEMBERNOTFOUND; } HandleScope handle_scope(isolate); Context::Scope context_scope(getContext()); TryCatch try_catch; if (!obj->IsFunction()) { return TJS_E_NOTIMPL; } // 関数抽出 Local<Function> func = Local<Function>::Cast(obj->ToObject()); // 引数 Handle<Value> *argv = new Handle<Value>[numparams]; for (int i=0;i<numparams;i++) { argv[i] = toJSValue(isolate, *param[i]); } Local<Object> ret = func->NewInstance(numparams, argv); delete argv; if (ret.IsEmpty()) { JSEXCEPTION(isolate, &try_catch); } else { if (result) { *result = toVariant(isolate, ret); } } return TJS_S_OK; }
void CJavascriptStackTrace::Dump(std::ostream& os) const { v8::HandleScope handle_scope(m_isolate); v8::TryCatch try_catch; std::ostringstream oss; for (int i=0; i<GetFrameCount(); i++) { v8::Handle<v8::StackFrame> frame = GetFrame(i)->Handle(); v8::String::Utf8Value funcName(frame->GetFunctionName()), scriptName(frame->GetScriptName()); os << "\tat "; if (funcName.length()) os << std::string(*funcName, funcName.length()) << " ("; if (frame->IsEval()) { os << "(eval)"; } else { os << std::string(*scriptName, scriptName.length()) << ":" << frame->GetLineNumber() << ":" << frame->GetColumn(); } if (funcName.length()) os << ")"; os << std::endl; } }
/** * missing 処理用の口 * TJSインスタンスにメンバが存在しなかった場合は javascriptインスタンスを参照する */ tjs_error TJSInstance::missing(tjs_uint32 flag, const tjs_char * membername, tjs_uint32 *hint, tTJSVariant *result, tjs_int numparams, tTJSVariant **params, iTJSDispatch2 *objthis) { if (numparams < 3) {return TJS_E_BADPARAMCOUNT;}; iTJSNativeInstance *ninstance; if (TJS_SUCCEEDED(objthis->NativeInstanceSupport(TJS_NIS_GETINSTANCE, classId, &ninstance))) { TJSInstance *self = (TJSInstance*)ninstance; HandleScope handle_scope(self->isolate); bool ret = false; if (!(int)*params[0]) { // get tTJSVariant result; if (TJS_SUCCEEDED(getProp(self->isolate, self->getObject(), params[1]->GetString(), &result))) { params[2]->AsObjectClosureNoAddRef().PropSet(0, NULL, NULL, &result, NULL); ret = true; } } else { // set if (TJS_SUCCEEDED(setProp(self->isolate, self->getObject(), params[1]->GetString(), params[2]))) { ret = true; } } if (result) { *result = ret; } } return TJS_E_NATIVECLASSCRASH; }
void CJavascriptException::ThrowIf(v8::Isolate *isolate, v8::TryCatch& try_catch) { if (try_catch.HasCaught() && try_catch.CanContinue()) { v8::HandleScope handle_scope(isolate); PyObject *type = NULL; v8::Handle<v8::Value> obj = try_catch.Exception(); if (obj->IsObject()) { v8::Handle<v8::Object> exc = obj->ToObject(); v8::Handle<v8::String> name = v8::String::NewFromUtf8(isolate, "name"); if (exc->Has(name)) { v8::String::Utf8Value s(v8::Handle<v8::String>::Cast(exc->Get(name))); for (size_t i=0; i<_countof(SupportErrors); i++) { if (strnicmp(SupportErrors[i].name, *s, s.length()) == 0) { type = SupportErrors[i].type; } } } } throw CJavascriptException(isolate, try_catch, type); } }
/** * TJSオブジェクトのオーバライド処理 * @param args 引数 * @return 結果 */ void TJSInstance::tjsOverride(const FunctionCallbackInfo<Value>& args) { Isolate *isolate = args.GetIsolate(); HandleScope handle_scope(isolate); tTJSVariant instance; if (getVariant(isolate, instance, args.This())) { if (args.Length() > 0) { Local<Value> func = args.Length() > 1 ? args[1] : args.This()->Get(args[0]); if (func->IsFunction()) { tTJSVariant value = toVariant(isolate, func->ToObject(), args.This()); String::Value methodName(args[0]); tjs_error error; if (TJS_FAILED(error = instance.AsObjectClosureNoAddRef().PropSet(TJS_MEMBERENSURE, *methodName, NULL, &value, NULL))) { args.GetReturnValue().Set(ERROR_KRKR(isolate, error)); return; } args.GetReturnValue().Set(Undefined(isolate)); return; } } args.GetReturnValue().Set(isolate->ThrowException(String::NewFromUtf8(isolate, "not function"))); return; } args.GetReturnValue().Set(ERROR_BADINSTANCE(isolate)); }
// The callback that is invoked by v8 whenever the JavaScript 'load' // function is called. Loads, compiles and executes its argument // JavaScript file. void Fragment::Script::ScriptEngine::Load(const v8::FunctionCallbackInfo<v8::Value> &args) { for (int i = 0; i < args.Length(); i++) { v8::HandleScope handle_scope(args.GetIsolate()); v8::String::Utf8Value file(args[i]); if (*file == NULL) { args.GetIsolate()->ThrowException( v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file", v8::NewStringType::kNormal).ToLocalChecked()); return; } v8::Local<v8::String> source; if (!ReadFile(args.GetIsolate(), *file).ToLocal(&source)) { args.GetIsolate()->ThrowException( v8::String::NewFromUtf8(args.GetIsolate(), "Error loading file", v8::NewStringType::kNormal).ToLocalChecked()); return; } if (!ExecuteString(args.GetIsolate(), source, args[i], false, false)) { args.GetIsolate()->ThrowException( v8::String::NewFromUtf8(args.GetIsolate(), "Error executing file", v8::NewStringType::kNormal).ToLocalChecked()); return; } } }
void Response::MakeWeak(v8::Isolate* isolate, v8::Local<v8::Object> self) { v8::HandleScope handle_scope(isolate); self_.Reset(isolate, self); self->SetAlignedPointerInInternalField(0, this); self_.MarkIndependent(); self_.SetWeak(this, WeakCallback); }
// Executes a string within the current v8 context. bool Fragment::Script::ScriptEngine::ExecuteString(v8::Isolate *isolate, v8::Local<v8::String> source, v8::Local<v8::Value> name, bool print_result, bool report_exceptions) { v8::HandleScope handle_scope(isolate); v8::TryCatch try_catch(isolate); v8::ScriptOrigin origin(name); v8::Local<v8::Context> context(isolate->GetCurrentContext()); v8::Local<v8::Script> script; if (!v8::Script::Compile(context, source, &origin).ToLocal(&script)) { // Print errors that happened during compilation. if (report_exceptions) ReportException(isolate, &try_catch); return false; } else { v8::Local<v8::Value> result; if (!script->Run(context).ToLocal(&result)) { assert(try_catch.HasCaught()); // Print errors that happened during execution. if (report_exceptions) ReportException(isolate, &try_catch); return false; } else { assert(!try_catch.HasCaught()); if (print_result && !result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. v8::String::Utf8Value str(result); const char *cstr = ToCString(str); printf("%s\n", cstr); } return true; } } }
CJS_Runtime::CJS_Runtime(CPDFSDK_FormFillEnvironment* pFormFillEnv) : m_pFormFillEnv(pFormFillEnv), m_bBlocking(false), m_isolateManaged(false) { v8::Isolate* pIsolate = nullptr; IPDF_JSPLATFORM* pPlatform = m_pFormFillEnv->GetFormFillInfo()->m_pJsPlatform; if (pPlatform->version <= 2) { unsigned int embedderDataSlot = 0; v8::Isolate* pExternalIsolate = nullptr; if (pPlatform->version == 2) { pExternalIsolate = reinterpret_cast<v8::Isolate*>(pPlatform->m_isolate); embedderDataSlot = pPlatform->m_v8EmbedderSlot; } FXJS_Initialize(embedderDataSlot, pExternalIsolate); } m_isolateManaged = FXJS_GetIsolate(&pIsolate); SetIsolate(pIsolate); #ifdef PDF_ENABLE_XFA v8::Isolate::Scope isolate_scope(pIsolate); v8::HandleScope handle_scope(pIsolate); #endif if (m_isolateManaged || FXJS_GlobalIsolateRefCount() == 0) DefineJSObjects(); IJS_EventContext* pContext = NewEventContext(); InitializeEngine(); ReleaseEventContext(pContext); SetFormFillEnvToDocument(); }
std::ostream& operator<<(std::ostream& s, const v8::TryCatch* try_catch) { v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); v8::String::Utf8Value exceptionText(try_catch->Exception()); v8::Local<v8::Message> message = try_catch->Message(); if (message.IsEmpty()) { s << *exceptionText << endl; } else { v8::String::Utf8Value filename(message->GetScriptResourceName()); int linenum = message->GetLineNumber(); cout << *filename << ":" << linenum << " " << *exceptionText << endl; v8::String::Utf8Value sourceline(message->GetSourceLine()); cout << *sourceline << endl; int start = message->GetStartColumn(); for (int i = 0; i < start; i++) cout << " "; int end = message->GetEndColumn(); for (int i = start; i < end; i++) cout << "^"; cout << endl; } return s; }