#include "CallbackHandlers.h" #include "NativeScriptAssert.h" #include "MetadataNode.h" #include "Util.h" #include "V8GlobalHelpers.h" #include "V8StringConstants.h" #include "Constants.h" #include "JsArgConverter.h" #include "JsArgToArrayConverter.h" #include "ArgConverter.h" #include "v8-profiler.h" #include #include #include #include #include #include #include #include #include "HttpLoader.h" #include "MethodCache.h" #include "ModuleInternal.h" #include "SimpleProfiler.h" #include "Runtime.h" #include "WorkerMessage.h" #include "WorkerWrapper.h" #include #include #include using namespace v8; using namespace std; using namespace tns; void CallbackHandlers::Init(Isolate *isolate) { /* * Runs once per runtime, on that runtime's own thread, so everything * process-global here is resolved under call_once: a starting worker must * not rewrite handles the isolates already running are reading, even * though it would write back the same values. */ static std::once_flag globalHandlesOnce; std::call_once(globalHandlesOnce, [] { JEnv env; JAVA_LANG_STRING = env.FindClass("java/lang/String"); NS_CHECK(JAVA_LANG_STRING != nullptr); RUNTIME_CLASS = env.FindClass("com/tns/Runtime"); NS_CHECK(RUNTIME_CLASS != nullptr); RESOLVE_CLASS_METHOD_ID = env.GetMethodID(RUNTIME_CLASS, "resolveClass", "(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Z)Ljava/lang/Class;"); NS_CHECK(RESOLVE_CLASS_METHOD_ID != nullptr); CURRENT_OBJECTID_FIELD_ID = env.GetFieldID(RUNTIME_CLASS, "currentObjectId", "I"); NS_CHECK(CURRENT_OBJECTID_FIELD_ID != nullptr); CURRENT_OBJECTCLASS_FIELD_ID = env.GetFieldID(RUNTIME_CLASS, "currentObjectClass", "Ljava/lang/Class;"); NS_CHECK(CURRENT_OBJECTCLASS_FIELD_ID != nullptr); REGISTER_CONSTRUCTED_INSTANCE_ID = env.GetMethodID(RUNTIME_CLASS, "registerConstructedInstance", "(Ljava/lang/Object;I)J"); NS_CHECK(REGISTER_CONSTRUCTED_INSTANCE_ID != nullptr); GET_TYPE_METADATA = env.GetStaticMethodID(RUNTIME_CLASS, "getTypeMetadata", "(Ljava/lang/String;I)[Ljava/lang/String;"); NS_CHECK(GET_TYPE_METADATA != nullptr); ENABLE_VERBOSE_LOGGING_METHOD_ID = env.GetMethodID(RUNTIME_CLASS, "enableVerboseLogging", "()V"); NS_CHECK(ENABLE_VERBOSE_LOGGING_METHOD_ID != nullptr); DISABLE_VERBOSE_LOGGING_METHOD_ID = env.GetMethodID(RUNTIME_CLASS, "disableVerboseLogging", "()V"); NS_CHECK(DISABLE_VERBOSE_LOGGING_METHOD_ID != nullptr); MethodCache::Init(); }); // Per isolate: writes into this runtime's own MetadataNode cache. MetadataNode::Init(isolate); } /* * Marks a JS -> Java call in flight on the runtime (see * Runtime::JavaCallDepth): a JS callback that throws while the depth is * non-zero is part of a JS-initiated chain and must propagate back to the * outer JS catch instead of being contained at the boundary. */ namespace { struct JavaCallScope { explicit JavaCallScope(Runtime* runtime) : runtime_(runtime) { runtime_->GetObjectManager()->FlushFinalizedBatchIfPending(); runtime_->EnterJavaCall(); } ~JavaCallScope() { runtime_->LeaveJavaCall(); } Runtime* runtime_; }; } // namespace // Publishes the instance JS is constructing to Runtime.initInstance for the duration of the // Java constructor, and restores the enclosing construction afterwards: JS run by a // callback the constructor makes may construct another instance. Raw JNI, so that the // destructor never throws. class CallbackHandlers::ConstructionScope { public: ConstructionScope(Runtime* runtime, int javaObjectId, jclass clazz) : _runtime(runtime), _previous(runtime->CurrentConstruction()) { Publish({javaObjectId, clazz}); } ~ConstructionScope() { Publish(_previous); } private: // The class is written only when it changes: initInstance reads it only while an id is // published, so a stale one is harmless, and repeated constructions of one class then // cost a single field write each way. void Publish(const Runtime::Construction& construction) { _runtime->CurrentConstruction() = construction; JNIEnv* env = JEnv(); jobject javaRuntime = _runtime->GetJavaRuntime(); jclass& published = _runtime->PublishedConstructionClass(); if (construction.id != -1 && construction.clazz != published) { env->SetObjectField(javaRuntime, CURRENT_OBJECTCLASS_FIELD_ID, construction.clazz); published = construction.clazz; } env->SetIntField(javaRuntime, CURRENT_OBJECTID_FIELD_ID, construction.id); } Runtime* _runtime; Runtime::Construction _previous; }; bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local &jsObject, const std::string &fullClassName, const ArgsWrapper &argWrapper, const Local &implementationObject, bool isInterface, const std::string &baseClassName) { bool success; DEBUG_WRITE("RegisterInstance called for '%s'", fullClassName.c_str()); auto runtime = Runtime::GetRuntime(isolate); auto objectManager = runtime->GetObjectManager(); // The Java constructor may synchronously call back into JS (extended // class init) - that whole window is a JS-initiated chain. JavaCallScope javaCallScope(runtime); JEnv env; jclass generatedJavaClass = ResolveClass(isolate, baseClassName, fullClassName, implementationObject, isInterface); int javaObjectID = objectManager->GenerateNewObjectID(); objectManager->Link(jsObject, javaObjectID, nullptr); // resolve constructor const auto &mi = MethodCache::ResolveConstructorSignature(argWrapper, fullClassName, generatedJavaClass, isInterface); jobject instance; { ConstructionScope construction(runtime, javaObjectID, generatedJavaClass); if (argWrapper.type == ArgType::Interface) { instance = env.NewObject(generatedJavaClass, mi.mid); } else { // resolve arguments before passing them on to the constructor JsArgConverter argConverter(argWrapper.args, mi.signature); auto ctorArgs = argConverter.ToArgs(); instance = env.NewObjectA(generatedJavaClass, mi.mid, ctorArgs); } } jlong usedJavaMemory = env.CallLongMethod(runtime->GetJavaRuntime(), REGISTER_CONSTRUCTED_INSTANCE_ID, instance, javaObjectID); AdjustAmountOfExternalAllocatedMemory(isolate, usedJavaMemory); JniLocalRef localInstance(instance); success = !localInstance.IsNull(); if (success) { // ResolveClass returned the class cache's global ref for fullClassName. objectManager->SetJavaClass(jsObject, generatedJavaClass); } else { DEBUG_WRITE_FORCE("RegisterInstance failed with null new instance class: %s", fullClassName.c_str()); } return success; } jclass CallbackHandlers::ResolveClass(Isolate *isolate, const string &baseClassName, const string &fullClassName, const Local &implementationObject, bool isInterface) { JEnv env; jclass globalRefToGeneratedClass = env.CheckForClassInCache(fullClassName); if (globalRefToGeneratedClass == nullptr) { // get needed arguments in order to load binding JniLocalRef javaBaseClassName(env.NewStringUTF(baseClassName.c_str())); JniLocalRef javaFullClassName(env.NewStringUTF(fullClassName.c_str())); jobjectArray methodOverrides = GetMethodOverrides(env, implementationObject); jobjectArray implementedInterfaces = GetImplementedInterfaces(env, implementationObject); auto runtime = Runtime::GetRuntime(isolate); // create or load generated binding (java class) jclass generatedClass = (jclass) env.CallObjectMethod(runtime->GetJavaRuntime(), RESOLVE_CLASS_METHOD_ID, (jstring) javaBaseClassName, (jstring) javaFullClassName, methodOverrides, implementedInterfaces, isInterface); globalRefToGeneratedClass = env.InsertClassIntoCache(fullClassName, generatedClass); env.DeleteGlobalRef(methodOverrides); env.DeleteGlobalRef(implementedInterfaces); } return globalRefToGeneratedClass; } // Called by ExtendMethodCallback when extending a class string CallbackHandlers::ResolveClassName(Isolate *isolate, jclass &clazz) { auto runtime = Runtime::GetRuntime(isolate); auto objectManager = runtime->GetObjectManager(); auto className = objectManager->GetClassName(clazz); return className; } Local CallbackHandlers::GetArrayElement(Local context, const Local &array, uint32_t index, const string &arraySignature) { return arrayElementAccessor.GetArrayElement(context, array, index, arraySignature); } void CallbackHandlers::SetArrayElement(Local context, const Local &array, uint32_t index, const string &arraySignature, Local &value) { arrayElementAccessor.SetArrayElement(context, array, index, arraySignature, value); } Local CallbackHandlers::GetJavaField(Isolate *isolate, const Local &caller, FieldCallbackData *fieldData) { return fieldAccessor.GetJavaField(isolate, caller, fieldData); } void CallbackHandlers::SetJavaField(Isolate *isolate, const Local &target, const Local &value, FieldCallbackData *fieldData) { fieldAccessor.SetJavaField(isolate, target, value, fieldData); } // java.lang.String is final, so an object returned through any other declared // type can only be a String if that type is one of String's supertypes. static bool CanBeJavaString(const std::string &jniReturnType) { return jniReturnType == "Ljava/lang/Object;" || jniReturnType == "Ljava/lang/CharSequence;" || jniReturnType == "Ljava/lang/Comparable;" || jniReturnType == "Ljava/io/Serializable;" || jniReturnType == "Ljava/lang/constant/Constable;" || jniReturnType == "Ljava/lang/constant/ConstantDesc;"; } void CallbackHandlers::CallJavaMethod(const Local &caller, const string &className, const string &methodName, MetadataEntry *entry, bool isFromInterface, bool isStatic, bool isSuper, const v8::FunctionCallbackInfo &args) { SET_PROFILER_FRAME(); JEnv env; jclass clazz; jmethodID mid; const string *sig = nullptr; const string *returnType = nullptr; auto retType = MethodReturnType::Unknown; const MethodCache::CacheMethodInfo *mi = nullptr; auto isolate = args.GetIsolate(); // The Java method may synchronously call back into JS (an overridden // method on the receiver) - that whole window is a JS-initiated chain. JavaCallScope javaCallScope(Runtime::GetRuntime(isolate)); if ((entry != nullptr) && entry->getIsResolved()) { auto &entrySignature = entry->getSig(); isStatic = entry->isStatic; if (entry->memberId == nullptr) { clazz = env.FindClass(className); if (clazz == nullptr) { MetadataNode *callerNode = MetadataNode::GetNodeFromHandle(caller); const string callerClassName = callerNode->GetName(); DEBUG_WRITE("Cannot resolve class: %s while calling method: %s callerClassName: %s", className.c_str(), methodName.c_str(), callerClassName.c_str()); clazz = env.FindClass(callerClassName); if (clazz == nullptr) { //todo: plamen5kov: throw exception here DEBUG_WRITE("Cannot resolve caller's class name: %s", callerClassName.c_str()); return; } if (isStatic) { if (isFromInterface) { auto methodAndClassPair = env.GetInterfaceStaticMethodIDAndJClass(className, methodName, entrySignature); entry->memberId = methodAndClassPair.first; clazz = methodAndClassPair.second; } else { entry->memberId = env.GetStaticMethodID(clazz, methodName, entrySignature); } } else { entry->memberId = env.GetMethodID(clazz, methodName, entrySignature); } if (entry->memberId == nullptr) { //todo: plamen5kov: throw exception here DEBUG_WRITE("Cannot resolve a method %s on caller class: %s", methodName.c_str(), callerClassName.c_str()); return; } } else { if (isStatic) { if (isFromInterface) { auto methodAndClassPair = env.GetInterfaceStaticMethodIDAndJClass(className, methodName, entrySignature); entry->memberId = methodAndClassPair.first; clazz = methodAndClassPair.second; } else { entry->memberId = env.GetStaticMethodID(clazz, methodName, entrySignature); } } else { entry->memberId = env.GetMethodID(clazz, methodName, entrySignature); } if (entry->memberId == nullptr) { //todo: plamen5kov: throw exception here DEBUG_WRITE("Cannot resolve a method %s on class: %s", methodName.c_str(), className.c_str()); return; } } entry->clazz = clazz; } mid = reinterpret_cast(entry->memberId); clazz = entry->clazz; sig = &entrySignature; returnType = &entry->getReturnType(); retType = entry->getRetType(); } else { DEBUG_WRITE("Resolving method: %s on className %s", methodName.c_str(), className.c_str()); clazz = env.FindClass(className); if (clazz != nullptr) { mi = &MethodCache::ResolveMethodSignature(className, methodName, args, isStatic); if (mi->mid == nullptr) { DEBUG_WRITE("Cannot resolve class=%s, method=%s, isStatic=%d, isSuper=%d", className.c_str(), methodName.c_str(), isStatic, isSuper); return; } } else { MetadataNode *callerNode = MetadataNode::GetNodeFromHandle(caller); const string callerClassName = callerNode->GetName(); DEBUG_WRITE("Resolving method on caller class: %s.%s on className %s", callerClassName.c_str(), methodName.c_str(), className.c_str()); mi = &MethodCache::ResolveMethodSignature(callerClassName, methodName, args, isStatic); if (mi->mid == nullptr) { DEBUG_WRITE( "Cannot resolve class=%s, method=%s, isStatic=%d, isSuper=%d, callerClass=%s", className.c_str(), methodName.c_str(), isStatic, isSuper, callerClassName.c_str()); return; } } clazz = mi->clazz; mid = mi->mid; sig = &mi->signature; returnType = &mi->returnType; retType = mi->retType; } if (!isStatic) { DEBUG_WRITE("CallJavaMethod called %s.%s. Instance id: %d, isSuper=%d", className.c_str(), methodName.c_str(), caller.IsEmpty() ? -42 : caller->GetIdentityHash(), isSuper); } else { DEBUG_WRITE("CallJavaMethod called %s.%s. static method", className.c_str(), methodName.c_str()); } JsArgConverter argConverter = (entry != nullptr && entry->isExtensionFunction) ? JsArgConverter(caller, args, *sig, entry) : JsArgConverter(args, false, *sig, entry); if (!argConverter.IsValid()) { JsArgConverter::Error err = argConverter.GetError(); throw NativeScriptException(err.msg); } JniLocalRef callerJavaObject; jvalue *javaArgs = argConverter.ToArgs(); auto runtime = Runtime::GetRuntimeFromIsolateData(isolate); auto objectManager = runtime->GetObjectManager(); if (!isStatic) { callerJavaObject = objectManager->GetJavaObjectByJsObject(caller); if (callerJavaObject.IsNull()) { stringstream ss; if (args.IsConstructCall()) { ss << "No java object found on which to call \"" << methodName << "\" method. It is possible your Javascript object is not linked with the corresponding Java class. Try passing context(this) to the constructor function."; } else { ss << "Failed calling " << methodName << " on a " << className << " instance. The JavaScript instance no longer has available Java instance counterpart."; } throw NativeScriptException(ss.str()); } } switch (retType) { case MethodReturnType::Void: { if (isStatic) { env.CallStaticVoidMethodA(clazz, mid, javaArgs); } else if (isSuper) { env.CallNonvirtualVoidMethodA(callerJavaObject, clazz, mid, javaArgs); } else { env.CallVoidMethodA(callerJavaObject, mid, javaArgs); } break; } case MethodReturnType::Boolean: { jboolean result; if (isStatic) { result = env.CallStaticBooleanMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualBooleanMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallBooleanMethodA(callerJavaObject, mid, javaArgs); } args.GetReturnValue().Set(result != 0); break; } case MethodReturnType::Byte: { jbyte result; if (isStatic) { result = env.CallStaticByteMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualByteMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallByteMethodA(callerJavaObject, mid, javaArgs); } args.GetReturnValue().Set(result); break; } case MethodReturnType::Char: { jchar result; if (isStatic) { result = env.CallStaticCharMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualCharMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallCharMethodA(callerJavaObject, mid, javaArgs); } args.GetReturnValue().Set(ArgConverter::jcharToV8String(isolate, result)); break; } case MethodReturnType::Short: { jshort result; if (isStatic) { result = env.CallStaticShortMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualShortMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallShortMethodA(callerJavaObject, mid, javaArgs); } args.GetReturnValue().Set(result); break; } case MethodReturnType::Int: { jint result; if (isStatic) { result = env.CallStaticIntMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualIntMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallIntMethodA(callerJavaObject, mid, javaArgs); } args.GetReturnValue().Set(result); break; } case MethodReturnType::Long: { jlong result; if (isStatic) { result = env.CallStaticLongMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualLongMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallLongMethodA(callerJavaObject, mid, javaArgs); } auto jsLong = ArgConverter::ConvertFromJavaLong(isolate, result); args.GetReturnValue().Set(jsLong); break; } case MethodReturnType::Float: { jfloat result; if (isStatic) { result = env.CallStaticFloatMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualFloatMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallFloatMethodA(callerJavaObject, mid, javaArgs); } args.GetReturnValue().Set((double) result); //TODO: handle float value here correctly. break; } case MethodReturnType::Double: { jdouble result; if (isStatic) { result = env.CallStaticDoubleMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualDoubleMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallDoubleMethodA(callerJavaObject, mid, javaArgs); } args.GetReturnValue().Set(result); break; } case MethodReturnType::String: { jobject result = nullptr; bool exceptionOccurred; if (isStatic) { result = env.CallStaticObjectMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualObjectMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallObjectMethodA(callerJavaObject, mid, javaArgs); } if (result != nullptr) { auto objectResult = ArgConverter::jstringToV8String(isolate, static_cast(result)); args.GetReturnValue().Set(objectResult); env.DeleteLocalRef(result); } else { args.GetReturnValue().SetNull(); } break; } case MethodReturnType::Object: { jobject result = nullptr; bool exceptionOccurred; if (isStatic) { result = env.CallStaticObjectMethodA(clazz, mid, javaArgs); } else if (isSuper) { result = env.CallNonvirtualObjectMethodA(callerJavaObject, clazz, mid, javaArgs); } else { result = env.CallObjectMethodA(callerJavaObject, mid, javaArgs); } if (result != nullptr) { auto isString = (returnType == nullptr || CanBeJavaString(*returnType)) && env.IsInstanceOf(result, JAVA_LANG_STRING); Local objectResult; if (isString) { objectResult = ArgConverter::jstringToV8String(isolate, (jstring) result); } else { objectResult = objectManager->GetOrCreateJSWrapper(result); } args.GetReturnValue().Set(objectResult); env.DeleteLocalRef(result); } else { args.GetReturnValue().SetNull(); } break; } default: { NS_DCHECK(false); break; } } // static uint32_t adjustMemCount = 0; // // if ((++adjustMemCount % 2) == 0) { // AdjustAmountOfExternalAllocatedMemory(env, isolate); // } } void CallbackHandlers::AdjustAmountOfExternalAllocatedMemory(Isolate *isolate, int64_t usedJavaMemory) { auto runtime = Runtime::GetRuntime(isolate); runtime->AdjustAmountOfExternalAllocatedMemory(usedJavaMemory); runtime->TryCallGC(); } Local CallbackHandlers::CreateJSWrapper(Isolate *isolate, jint javaObjectID, const string &typeName) { auto runtime = Runtime::GetRuntime(isolate); auto objectManager = runtime->GetObjectManager(); return objectManager->CreateJSWrapper(javaObjectID, typeName); } jobjectArray CallbackHandlers::GetImplementedInterfaces(JEnv &env, const Local &implementationObject) { if (implementationObject.IsEmpty()) { return CallbackHandlers::GetJavaStringArray(env, 0); } vector interfacesToImplement; auto isolate = v8::Isolate::GetCurrent(); auto context = GetCreationContextOrCurrent(isolate, implementationObject); Local interfacesName = String::NewFromUtf8Literal(isolate, "interfaces"); Local prop; if (implementationObject->Get(context, interfacesName).ToLocal(&prop) && !prop.IsEmpty() && prop->IsArray()) { auto interfacesArr = prop->ToObject(context).ToLocalChecked(); Local lengthName = String::NewFromUtf8Literal(isolate, "length"); unsigned length = interfacesArr->Get(context,lengthName).ToLocalChecked() ->Uint32Value(context).ToChecked(); for (int j = 0; j < length; j++) { auto element = interfacesArr->Get(context, j).ToLocalChecked(); if (element->IsFunction()) { auto node = MetadataNode::GetTypeMetadataName(isolate, element); node = Util::ReplaceAll(node, std::string("/"), std::string(".")); jstring value = env.NewStringUTF(node.c_str()); interfacesToImplement.push_back(value); } } } int interfacesCount = interfacesToImplement.size(); jobjectArray implementedInterfaces = CallbackHandlers::GetJavaStringArray(env, interfacesCount); for (int i = 0; i < interfacesCount; i++) { env.SetObjectArrayElement(implementedInterfaces, i, interfacesToImplement[i]); } for (int i = 0; i < interfacesCount; i++) { env.DeleteLocalRef(interfacesToImplement[i]); } return implementedInterfaces; } jobjectArray CallbackHandlers::GetMethodOverrides(JEnv &env, const Local &implementationObject) { if (implementationObject.IsEmpty()) { return CallbackHandlers::GetJavaStringArray(env, 0); } vector methodNames; auto isolate = v8::Isolate::GetCurrent(); auto context = GetCreationContextOrCurrent(isolate, implementationObject); auto propNames = implementationObject->GetOwnPropertyNames(context).ToLocalChecked(); for (int i = 0; i < propNames->Length(); i++) { auto name = propNames->Get(context, i).ToLocalChecked().As(); if (name->StringEquals(V8StringConstants::GetSuper(isolate))) { continue; } auto method = implementationObject->Get(context, name).ToLocalChecked(); bool methodFound = !method.IsEmpty() && method->IsFunction(); if (methodFound) { String::Utf8Value stringValue(isolate, name); jstring value = env.NewStringUTF(*stringValue); methodNames.push_back(value); } } int methodCount = methodNames.size(); jobjectArray methodOverrides = CallbackHandlers::GetJavaStringArray(env, methodCount); for (int i = 0; i < methodCount; i++) { env.SetObjectArrayElement(methodOverrides, i, methodNames[i]); } for (int i = 0; i < methodCount; i++) { env.DeleteLocalRef(methodNames[i]); } return methodOverrides; } void CallbackHandlers::RunOnMainThreadCallback(const FunctionCallbackInfo &args) { NS_DCHECK(args[0]->IsFunction()); Isolate *isolate = args.GetIsolate(); v8::Locker locker(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); uint64_t key = ++count_; Local callback = args[0].As(); // resolve the loop before inserting: an entry cached with no post to // consume it would pin the callback until isolate teardown auto mainLoop = Runtime::GetMainEventLoop(); if (mainLoop == nullptr) { return; } std::shared_ptr gate; if (auto wrapper = WorkerWrapper::FromIsolate(isolate)) { gate = wrapper->Gate(); } { std::lock_guard lock(cacheMutex_); bool inserted; std::tie(std::ignore, inserted) = cache_.try_emplace(key, isolate, callback, std::move(gate)); NS_DCHECK(inserted && "Main thread callback ID should not be duplicated"); } // bare entry: the closure locks the CALLER's isolate (possibly a // worker's), so the loop must not take the main isolate's Locker first - // nesting the two can deadlock against multithreaded-JS entry paths mainLoop->PostInternalBare([key]() { RunMainThreadEntry(key); }); } void CallbackHandlers::RunMainThreadEntry(uint64_t key) { Isolate *isolate; std::shared_ptr gate; { std::lock_guard lock(cacheMutex_); auto it = cache_.find(key); if (it == cache_.end()) { return; } isolate = it->second.isolate_; gate = it->second.gate_; } // A worker that has started shutting down may dispose its isolate at any // moment, so its callback is dropped without touching the isolate. std::unique_lock gateLock; if (gate != nullptr) { gateLock = std::unique_lock(gate->mutex); if (!gate->open) { return; } } v8::Locker locker(isolate); if (gateLock.owns_lock()) { gateLock.unlock(); } Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); Local cb; { std::lock_guard lock(cacheMutex_); auto it = cache_.find(key); if (it == cache_.end()) { return; } cb = it->second.callback_.Get(isolate); cache_.erase(it); } Runtime* runtime = Runtime::GetRuntime(isolate); v8::Local context = runtime->GetContext(); Context::Scope context_scope(context); v8::TryCatch tc(isolate); cb->Call(context, context->Global(), 0, nullptr); // ignore JS return value if (tc.HasCaught() && !NativeScriptException::ContainUncaughtCallbackException(isolate, tc)) { if (gate != nullptr) { // A worker's error belongs to the worker, as if the callback had // run on its own thread: its onerror, then the parent's Worker // object. Thrown from here it would become a Java exception on the // main thread. Under the "report" policy the containment above // is the whole report: the parent never hears about the error. CallWorkerScopeOnErrorHandle(isolate, tc); return; } // surfaces via the event loop's guard as a pending Java exception throw NativeScriptException(tc); } } void CallbackHandlers::LogMethodCallback(const v8::FunctionCallbackInfo &args) { try { if ((args.Length() > 0) && args[0]->IsString()) { auto isolate = args.GetIsolate(); auto context = isolate->GetCurrentContext(); String::Utf8Value message(isolate, args[0]->ToString(context).ToLocalChecked()); DEBUG_WRITE("%s", *message); } } catch (NativeScriptException &e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::DrainMicrotaskCallback(const v8::FunctionCallbackInfo &args) { try { auto isolate = args.GetIsolate(); isolate->PerformMicrotaskCheckpoint(); } catch (NativeScriptException &e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::QueueMacrotaskCallback(const v8::FunctionCallbackInfo &args) { try { auto isolate = args.GetIsolate(); if (args.Length() < 1 || !args[0]->IsFunction()) { isolate->ThrowException(v8::Exception::TypeError(ArgConverter::ConvertToV8String( isolate, "__ns__queueMacrotask: callback must be a function"))); return; } auto eventLoop = Runtime::GetRuntime(isolate)->GetEventLoop(); if (eventLoop == nullptr) { return; } auto callback = std::make_shared>(isolate, args[0].As()); // the ordered lane rides the Java MessageQueue, so the callback runs // as a macrotask in strict FIFO order with JS timers and Handler.post eventLoop->PostOrdered([isolate, callback]() { // Java-dispatched callback with no live runtime: log-and-drop, // never throw across the boundary auto runtime = Runtime::TryGetRuntime(isolate); if (runtime == nullptr) { DEBUG_WRITE("__ns__queueMacrotask: dropping macrotask, its runtime is gone"); callback->Reset(); return; } auto context = runtime->GetContext(); Context::Scope context_scope(context); TryCatch tc(isolate); auto cb = callback->Get(isolate); cb->Call(context, context->Global(), 0, nullptr); callback->Reset(); if (tc.HasCaught() && !NativeScriptException::ContainUncaughtCallbackException(isolate, tc)) { if (EventLoop::IsPumping()) { // A pump drained this entry and keeps making JNI calls // after we return; the loop reports the exception from // its next token dispatch instead. auto loop = runtime->GetEventLoop(); if (loop != nullptr) { loop->DeferJavaThrow(std::make_shared(tc)); } } else { NativeScriptException(tc).ReThrowToJava(); } } }); } catch (NativeScriptException &e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::TimeCallback(const v8::FunctionCallbackInfo &args) { auto nano = std::chrono::time_point_cast( std::chrono::system_clock::now()); double duration = nano.time_since_epoch().count(); args.GetReturnValue().Set(duration); } void CallbackHandlers::ReleaseNativeCounterpartCallback( const v8::FunctionCallbackInfo &info) { try { SET_PROFILER_FRAME(); validateProvidedArgumentsLength(info, 1); auto isolate = info.GetIsolate(); Handle obj = info[0].As(); auto runtime = Runtime::GetRuntime(isolate); auto objectManager = runtime->GetObjectManager(); objectManager->ReleaseNativeCounterpart(obj); } catch (NativeScriptException &e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::validateProvidedArgumentsLength(const v8::FunctionCallbackInfo &args, int expectedSize) { if (args.Length() != expectedSize) { throw NativeScriptException("Unexpected arguments count!"); } } void CallbackHandlers::DumpReferenceTablesMethodCallback( const v8::FunctionCallbackInfo &args) { DumpReferenceTablesMethod(); } void CallbackHandlers::DumpReferenceTablesMethod() { try { JEnv env; jclass vmDbgClass = env.FindClass("dalvik/system/VMDebug"); if (vmDbgClass != nullptr) { jmethodID mid = env.GetStaticMethodID(vmDbgClass, "dumpReferenceTables", "()V"); if (mid != 0) { env.CallStaticVoidMethod(vmDbgClass, mid); } } } catch (NativeScriptException &e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::EnableVerboseLoggingMethodCallback( const v8::FunctionCallbackInfo &args) { try { auto isolate = args.GetIsolate(); auto runtime = Runtime::GetRuntime(isolate); tns::LogEnabled = true; JEnv env; env.CallVoidMethod(runtime->GetJavaRuntime(), ENABLE_VERBOSE_LOGGING_METHOD_ID); } catch (NativeScriptException &e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::DisableVerboseLoggingMethodCallback( const v8::FunctionCallbackInfo &args) { try { auto isolate = args.GetIsolate(); auto runtime = Runtime::GetRuntime(isolate); tns::LogEnabled = false; JEnv env; env.CallVoidMethod(runtime->GetJavaRuntime(), DISABLE_VERBOSE_LOGGING_METHOD_ID); } catch (NativeScriptException &e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::ExitMethodCallback(const v8::FunctionCallbackInfo &args) { auto msg = ArgConverter::ConvertToString(args[0].As()); DEBUG_WRITE_FATAL("FORCE EXIT: %s", msg.c_str()); exit(-1); } bool CallbackHandlers::AddCastFunctions(Local context, Local target) { return castFunctions.AddCastFunctions(context, target); } vector CallbackHandlers::GetTypeMetadata(const string &name, int index) { JEnv env; string canonicalName = Util::ConvertFromJniToCanonicalName(name); JniLocalRef className(env.NewStringUTF(canonicalName.c_str())); jint idx = index; JniLocalRef pubApi( env.CallStaticObjectMethod(RUNTIME_CLASS, GET_TYPE_METADATA, (jstring) className, idx)); jsize length = env.GetArrayLength(pubApi); NS_DCHECK(length > 0); vector result; for (jsize i = 0; i < length; i++) { JniLocalRef s(env.GetObjectArrayElement(pubApi, i)); const char *pc = env.GetStringUTFChars(s, nullptr); result.push_back(string(pc)); env.ReleaseStringUTFChars(s, pc); } return result; } Local CallbackHandlers::CallJSMethod(Isolate *isolate, JNIEnv *_env, const Local &jsObject, const Local &methodName, const JavaCallArgs &args) { SET_PROFILER_FRAME(); JEnv env(_env); Local result; auto context = Runtime::GetRuntime(isolate)->GetContext(); auto method = jsObject->Get(context, methodName).ToLocalChecked(); if (method.IsEmpty() || method->IsUndefined()) { stringstream ss; ss << "Cannot find method '" << ArgConverter::ConvertToString(methodName) << "' implementation"; throw NativeScriptException(ss.str()); } else if (!method->IsFunction()) { stringstream ss; ss << "Property '" << ArgConverter::ConvertToString(methodName) << "' is not a function"; throw NativeScriptException(ss.str()); } else { EscapableHandleScope handleScope(isolate); auto jsMethod = method.As(); int argc = args.count; constexpr int kInlineArgs = 16; Local inlineArguments[kInlineArgs]; std::vector> heapArguments; Local* arguments = inlineArguments; if (argc > kInlineArgs) { heapArguments.resize(argc); arguments = heapArguments.data(); } ArgConverter::ConvertJavaArgsToJsArgs(isolate, env, args, argc, arguments); TryCatch tc(isolate); Local jsResult; { SET_PROFILER_FRAME(); jsMethod->Call(context, jsObject, argc, argc == 0 ? nullptr : arguments).ToLocal( &jsResult); } //TODO: if javaResult is a pure js object create a java object that represents this object in java land if (tc.HasCaught()) { if (NativeScriptException::ContainUncaughtCallbackException(isolate, tc)) { // Reported per uncaughtErrorPolicy; the native caller resumes // with a default value. jsResult = v8::Undefined(isolate); } else { stringstream ss; ss << "Calling js method " << ArgConverter::ConvertToString(methodName) << " failed"; throw NativeScriptException(tc, ss.str()); } } result = handleScope.Escape(jsResult); } return result; } Local CallbackHandlers::FindClass(Isolate *isolate, const string &className) { Local clazz; JEnv env; jclass c = env.FindClass(className); if (env.ExceptionCheck() == JNI_FALSE) { auto runtime = Runtime::GetRuntime(isolate); auto objectManager = runtime->GetObjectManager(); clazz = objectManager->GetOrCreateJSWrapper(c); } return clazz; } int CallbackHandlers::GetArrayLength(Isolate *isolate, const Local &arr) { auto runtime = Runtime::GetRuntime(isolate); auto objectManager = runtime->GetObjectManager(); JEnv env; auto javaArr = objectManager->GetJavaObjectByJsObject(arr); auto length = env.GetArrayLength(javaArr); return length; } jobjectArray CallbackHandlers::GetJavaStringArray(JEnv &env, int length) { if (length > CallbackHandlers::MAX_JAVA_STRING_ARRAY_LENGTH) { stringstream ss; ss << "You are trying to override more methods than the limit of " << CallbackHandlers::MAX_JAVA_STRING_ARRAY_LENGTH; throw NativeScriptException(ss.str()); } JniLocalRef tmpArr(env.NewObjectArray(length, JAVA_LANG_STRING, nullptr)); return (jobjectArray) env.NewGlobalRef(tmpArr); } namespace { const int kDefaultWorkerPriority = 10; // android.os.Process.THREAD_PRIORITY_BACKGROUND const char *const kWorkerPriorityNames = "'lowest', 'background', 'lessFavorable', 'default', 'moreFavorable', " "'foreground', 'display', 'urgentDisplay', 'video', 'audio', 'urgentAudio' " "or a number between -20 and 19"; // The android.os.Process THREAD_PRIORITY_* nice values, under their camelCase // names; anything else is a caller error. bool MapWorkerPriorityName(const std::string &name, int &priority) { if (name == "lowest") { priority = 19; } else if (name == "background") { priority = 10; } else if (name == "lessFavorable") { priority = 1; } else if (name == "default") { priority = 0; } else if (name == "moreFavorable") { priority = -1; } else if (name == "foreground") { priority = -2; } else if (name == "display") { priority = -4; } else if (name == "urgentDisplay") { priority = -8; } else if (name == "video") { priority = -10; } else if (name == "audio") { priority = -16; } else if (name == "urgentAudio") { priority = -19; } else { return false; } return true; } // Nice values outside the kernel's range are clamped rather than rejected: a // caller asking for "as low as possible" gets it. Clamping happens on the // double, before any integer conversion - ToInt32 wraps modulo 2^32, which // would turn a value past the range into an in-range one. NaN sits on no point // of the scale and is left to the caller to accept or reject. std::optional ClampWorkerPriority(Local value) { double priority = value.As()->Value(); if (std::isnan(priority)) { return std::nullopt; } if (priority < -20) { return -20; } if (priority > 19) { return 19; } return static_cast(priority); } // Carries a real TypeError instance so `catch (e) { e instanceof TypeError }` // holds in JS; NewThreadCallback's catch block rethrows it unchanged. [[noreturn]] void ThrowWorkerOptionTypeError(Isolate *isolate, const std::string &message) { Local error = Exception::TypeError(ArgConverter::ConvertToV8String(isolate, message)); throw NativeScriptException(isolate, error, message); } [[noreturn]] void ThrowWorkerOptionRangeError(Isolate *isolate, const std::string &message) { Local error = Exception::RangeError(ArgConverter::ConvertToV8String(isolate, message)); throw NativeScriptException(isolate, error, message); } #ifndef V8_HAS_JS_DISPATCH_TABLE_RESERVATION_PARAM [[noreturn]] void ThrowWorkerOptionError(Isolate *isolate, const std::string &message) { Local error = Exception::Error(ArgConverter::ConvertToV8String(isolate, message)); throw NativeScriptException(isolate, error, message); } #endif // Reads `key` from `object`. A false return means the getter threw: the // exception is already pending on the isolate and construction must stop // without running anything else on it. bool ReadWorkerOption(Isolate *isolate, Local context, Local object, const char *key, Local &out) { return object->Get(context, ArgConverter::ConvertToV8String(isolate, key)).ToLocal(&out); } /* * Resolves the Worker thread priority to an android.os.Process nice value from * `android.priority`, falling back to the deprecated top-level * `androidPriority`. Defaults to THREAD_PRIORITY_BACKGROUND (10). * Returns false when an option getter threw (see ReadWorkerOption). */ bool GetWorkerThreadPriority(Isolate *isolate, Local context, const v8::FunctionCallbackInfo &args, int &priority) { priority = kDefaultWorkerPriority; if (args.Length() < 2 || !args[1]->IsObject()) { return true; } auto options = args[1].As(); bool resolved = false; Local androidVal; if (!ReadWorkerOption(isolate, context, options, "android", androidVal)) { return false; } if (!androidVal->IsNullOrUndefined()) { if (!androidVal->IsObject()) { ThrowWorkerOptionTypeError(isolate, "Worker option \"android\" must be an object."); } Local priorityVal; if (!ReadWorkerOption(isolate, context, androidVal.As(), "priority", priorityVal)) { return false; } if (!priorityVal->IsUndefined()) { std::optional resolvedPriority; if (priorityVal->IsNumber()) { resolvedPriority = ClampWorkerPriority(priorityVal); } else if (priorityVal->IsString()) { int named; if (MapWorkerPriorityName(ArgConverter::ConvertToString(priorityVal.As()), named)) { resolvedPriority = named; } } if (!resolvedPriority) { ThrowWorkerOptionTypeError( isolate, std::string("Worker option \"android.priority\" must be one of ") + kWorkerPriorityNames + "."); } priority = *resolvedPriority; resolved = true; } } Local legacyVal; if (!ReadWorkerOption(isolate, context, options, "androidPriority", legacyVal)) { return false; } if (legacyVal->IsNullOrUndefined()) { return true; } static std::once_flag warnedDeprecated; std::call_once(warnedDeprecated, []() { DEBUG_WRITE_FORCE("NativeScript: the Worker option \"androidPriority\" is deprecated. " "Use \"android\": { \"priority\": ... } instead."); }); if (resolved) { return true; } if (legacyVal->IsNumber()) { // The deprecated option takes NaN as nice 0 (THREAD_PRIORITY_DEFAULT) // rather than rejecting it. priority = ClampWorkerPriority(legacyVal).value_or(0); return true; } if (legacyVal->IsString() && MapWorkerPriorityName(ArgConverter::ConvertToString(legacyVal.As()), priority)) { return true; } throw NativeScriptException( std::string("Invalid value for the Worker 'androidPriority' option. Expected one of: ") + kWorkerPriorityNames + "."); } constexpr double kBytesPerMegabyte = 1024 * 1024; // Bounds the double-to-size_t conversion below: converting a byte count that // does not fit size_t is undefined, and size_t is 32 bits on armeabi-v7a and // x86. The division floors, so the product always fits. v8 clamps heap sizes // far under this on every device, so nothing real is excluded. constexpr size_t kMaxLimitMegabytes = std::numeric_limits::max() / static_cast(kBytesPerMegabyte); // v8 needs the reservation to be a whole number of table segments and no larger // than its compile-time maximum; whole megabytes satisfy the first on every // platform's segment size, and 256 is the maximum. constexpr double kMaxJsDispatchTableSizeMb = 256; #ifdef V8_HAS_JS_DISPATCH_TABLE_RESERVATION_PARAM // Every isolate otherwise reserves 256 MB of address space for its JS dispatch // table; 64 MB still holds four million dispatch entries, far more than a // worker allocates. Only workers get the smaller reservation - the main // isolate keeps v8's default. constexpr size_t kDefaultWorkerJsDispatchTableBytes = 64 * 1024 * 1024; #endif // Reads one megabyte-valued `resourceLimits` key into `megabytes`, leaving it // empty when the key is absent (v8's own default stays in place). Returns false // when the getter threw (see ReadWorkerOption). A present value must be a // finite number worth at least one byte and at most kMaxLimitMegabytes. bool ReadMegabyteLimit(Isolate *isolate, Local context, Local resourceLimits, const char *key, std::optional &megabytes) { Local value; if (!ReadWorkerOption(isolate, context, resourceLimits, key, value)) { return false; } if (value->IsUndefined()) { return true; } std::string name = std::string("resourceLimits.") + key; if (!value->IsNumber()) { ThrowWorkerOptionTypeError(isolate, "Worker option \"" + name + "\" must be a number."); } double parsed = value.As()->Value(); if (!std::isfinite(parsed) || parsed * kBytesPerMegabyte < 1 || parsed > static_cast(kMaxLimitMegabytes)) { ThrowWorkerOptionRangeError(isolate, "Worker option \"" + name + "\" must be a finite number of megabytes worth at " "least one byte and at most " + std::to_string(kMaxLimitMegabytes) + "."); } megabytes = parsed; return true; } /* * Node's `resourceLimits` shape. Unknown keys are ignored, so the options Node * has and this runtime cannot honor (codeRangeSizeMb, stackSizeMb) stay * harmless to pass. Returns false when a getter threw (see ReadWorkerOption). */ bool ParseWorkerResourceLimits(Isolate *isolate, Local context, const v8::FunctionCallbackInfo &args, IsolateLimits &limits) { if (args.Length() < 2 || !args[1]->IsObject()) { return true; } Local value; if (!ReadWorkerOption(isolate, context, args[1].As(), "resourceLimits", value)) { return false; } if (value->IsNullOrUndefined()) { return true; } if (!value->IsObject()) { ThrowWorkerOptionTypeError(isolate, "Worker option \"resourceLimits\" must be an object."); } Local resourceLimits = value.As(); std::optional megabytes; if (!ReadMegabyteLimit(isolate, context, resourceLimits, "maxOldGenerationSizeMb", megabytes)) { return false; } if (megabytes) { limits.maxOldGenerationSizeBytes = static_cast(*megabytes * kBytesPerMegabyte); } megabytes.reset(); if (!ReadMegabyteLimit(isolate, context, resourceLimits, "maxYoungGenerationSizeMb", megabytes)) { return false; } if (megabytes) { limits.maxYoungGenerationSizeBytes = static_cast(*megabytes * kBytesPerMegabyte); } megabytes.reset(); if (!ReadMegabyteLimit(isolate, context, resourceLimits, "jsDispatchTableSizeMb", megabytes)) { return false; } if (megabytes) { if (*megabytes != std::floor(*megabytes) || *megabytes < 1 || *megabytes > kMaxJsDispatchTableSizeMb) { ThrowWorkerOptionRangeError( isolate, "Worker option \"resourceLimits.jsDispatchTableSizeMb\" must be a " "whole number of megabytes between 1 and 256."); } #ifdef V8_HAS_JS_DISPATCH_TABLE_RESERVATION_PARAM limits.jsDispatchTableReservationBytes = static_cast(*megabytes) * static_cast(kBytesPerMegabyte); #else ThrowWorkerOptionError(isolate, "Worker option \"resourceLimits.jsDispatchTableSizeMb\" requires a " "v8 build with a configurable JS dispatch table."); #endif } return true; } } // namespace void CallbackHandlers::NewThreadCallback(const v8::FunctionCallbackInfo &args) { try { if (!args.IsConstructCall()) { throw NativeScriptException("Worker should be called as a constructor!"); } if (args.Length() == 0) { throw NativeScriptException("Not enough arguments."); } if (args.Length() > 2) { throw NativeScriptException("Too many arguments passed."); } auto thiz = args.This(); auto isolate = v8::Isolate::GetCurrent(); auto context = isolate->GetCurrentContext(); std::string workerPath; // Handle both string URLs and URL objects if (args[0]->IsString()) { workerPath = ArgConverter::ConvertToString(args[0].As()); } else if (args[0]->IsObject()) { Local urlObj = args[0].As(); Local toStringMethod; if (urlObj->Get(context, ArgConverter::ConvertToV8String(isolate, "toString")).ToLocal(&toStringMethod)) { if (toStringMethod->IsFunction()) { Local toString = toStringMethod.As(); Local result; if (toString->Call(context, urlObj, 0, nullptr).ToLocal(&result)) { if (result->IsString()) { std::string stringResult = ArgConverter::ConvertToString(result.As()); // Reject plain objects that return "[object Object]" from toString() if (stringResult == "[object Object]") { throw NativeScriptException("Worker constructor expects a string URL or URL object."); } workerPath = stringResult; } else { throw NativeScriptException("Worker URL object toString() must return a string."); } } else { throw NativeScriptException("Error calling toString() on Worker URL object."); } } else { throw NativeScriptException("Worker URL object must have a toString() method."); } } else { throw NativeScriptException("Worker URL object must have a toString() method."); } } else { throw NativeScriptException("Worker constructor expects a string URL or URL object."); } int priority; IsolateLimits resourceLimits; if (!GetWorkerThreadPriority(isolate, context, args, priority) || !ParseWorkerResourceLimits(isolate, context, args, resourceLimits)) { return; } #ifdef V8_HAS_JS_DISPATCH_TABLE_RESERVATION_PARAM if (!resourceLimits.jsDispatchTableReservationBytes.has_value()) { resourceLimits.jsDispatchTableReservationBytes = kDefaultWorkerJsDispatchTableBytes; } #endif // An http(s) entry has no filesystem form to validate or to resolve // against the caller's directory: it is already absolute, and the // module loader's HTTP branch fetches it on the worker's own thread // under the same security gate every other remote load passes. The // URL is what the worker registers its entry under, so it is also what // the settle gate probes — it must reach the wrapper unrewritten. const bool isHttpEntry = ModuleInternal::IsHttpModulePath(workerPath); // Resolve tilde paths before creating the worker std::string resolvedPath = workerPath; if (!isHttpEntry && !workerPath.empty() && workerPath[0] == '~') { // Convert ~/path to ApplicationPath/path std::string tail = workerPath.size() >= 2 && workerPath[1] == '/' ? workerPath.substr(2) : workerPath.substr(1); resolvedPath = Constants::APP_ROOT_FOLDER_PATH + tail; } /* * Relative worker paths are resolved against the calling module's * directory. The caller may have no script name (e.g. eval'd code) or * the script may not be found there - in both cases fall back to * app-root-relative resolution, mirroring the iOS runtime. */ std::string currentDir = Constants::APP_ROOT_FOLDER_PATH; auto stack = isHttpEntry ? Local() : StackTrace::CurrentStackTrace(isolate, 1, StackTrace::kScriptName); if (!stack.IsEmpty() && stack->GetFrameCount() > 0) { auto currentExecutingScriptName = stack->GetFrame(isolate, 0)->GetScriptName(); auto currentExecutingScriptNameStr = ArgConverter::ConvertToString( currentExecutingScriptName); auto lastForwardSlash = currentExecutingScriptNameStr.find_last_of("/"); if (lastForwardSlash != std::string::npos) { auto callerDir = currentExecutingScriptNameStr.substr(0, lastForwardSlash + 1); string fileSchema("file://"); if (callerDir.compare(0, fileSchema.length(), fileSchema) == 0) { callerDir = callerDir.substr(fileSchema.length()); } currentDir = callerDir; } } // The worker runs on its own thread, with its own working directory // and module registry, so it gets the entry resolved here rather than // the spec: nothing on the other side can redo this resolution, and // the entry's registry key must be what was resolved here. std::string entryPath; if (isHttpEntry) { // Repaired, not canonicalized: the canonical key depends on the // worker's own canonicalization vocabulary, which is installed on // its isolate, and both the loader and the settle gate derive it // there from this URL. entryPath = NormalizeHttpModuleUrl(resolvedPath); } else { // Throws if the path is invalid or the file doesn't exist. try { entryPath = ModuleInternal::CheckFileExists(isolate, resolvedPath, currentDir); } catch (NativeScriptException& e) { if (currentDir == Constants::APP_ROOT_FOLDER_PATH) { throw; } // not found next to the caller - retry against the app root entryPath = ModuleInternal::CheckFileExists(isolate, resolvedPath, Constants::APP_ROOT_FOLDER_PATH); currentDir = Constants::APP_ROOT_FOLDER_PATH; } } auto workerId = WorkerWrapper::NextWorkerId(); V8SetPrivateValue(isolate, thiz, ArgConverter::ConvertToV8String(isolate, "workerId"), Number::New(isolate, workerId)); // Resolve the jclass/jmethodID handles the worker thread will need, // here on the main thread where class loading is safe. WorkerWrapper::EnsureJniCached(); auto wrapper = std::make_shared(isolate, workerId, entryPath, currentDir, priority, std::move(resourceLimits), thiz); WorkerWrapper::Insert(workerId, wrapper); DEBUG_WRITE("Called Worker constructor id=%d", workerId); wrapper->Start(); } catch (NativeScriptException &e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::WorkerObjectPostMessageCallback(const v8::FunctionCallbackInfo &args) { auto isolate = args.GetIsolate(); HandleScope scope(isolate); try { if (args.Length() < 1) { isolate->ThrowException(ArgConverter::ConvertToV8String(isolate, "Failed to execute 'postMessage' on 'Worker': 1 argument required.")); return; } if (args.Length() > 2) { isolate->ThrowException(ArgConverter::ConvertToV8String(isolate, "Failed to execute 'postMessage' on 'Worker': no more than 2 arguments accepted.")); return; } auto thiz = args.This(); // Worker instance Local jsId; auto maybejsId = V8GetPrivateValue(isolate, thiz, ArgConverter::ConvertToV8String(isolate, "workerId"), jsId); auto context = isolate->GetCurrentContext(); // get worker's ID that is associated with the WorkerWrapper auto id = jsId->Int32Value(context).ToChecked(); auto wrapper = WorkerWrapper::GetById(id); if (wrapper == nullptr || wrapper->IsTerminating() || wrapper->IsClosing()) { DEBUG_WRITE( "MAIN: WorkerObjectPostMessageCallback - worker(id=%d) is terminated or closing. No message will be sent.", id); return; } Local transferList = args.Length() > 1 ? args[1] : v8::Undefined(isolate).As(); auto message = std::make_shared(); if (message->Serialize(isolate, context, args[0], transferList, serialization::HostObjectPolicy::kDegrade) .IsNothing()) { // The transfer list was rejected or the value could not be cloned; // the exception is already pending and nothing may be posted. return; } wrapper->PostMessage(message); DEBUG_WRITE( "MAIN: WorkerObjectPostMessageCallback called postMessage on Worker object(id=%d)", id); } catch (NativeScriptException &ex) { ex.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::WorkerGlobalPostMessageCallback(const v8::FunctionCallbackInfo &args) { auto isolate = args.GetIsolate(); HandleScope scope(isolate); try { TryCatch tc(isolate); // TODO: Pete: Discuss whether this is the way to go if (args.Length() < 1) { isolate->ThrowException(ArgConverter::ConvertToV8String(isolate, "Failed to execute 'postMessage' on WorkerGlobalScope: 1 argument required.")); } else if (args.Length() > 2) { isolate->ThrowException(ArgConverter::ConvertToV8String(isolate, "Failed to execute 'postMessage' on WorkerGlobalScope: no more than 2 arguments accepted.")); } if (tc.HasCaught()) { CallWorkerScopeOnErrorHandle(isolate, tc); return; } auto wrapper = WorkerWrapper::FromIsolate(isolate); if (wrapper == nullptr || wrapper->IsTerminating()) { DEBUG_WRITE( "WORKER: WorkerGlobalPostMessageCallback - worker is terminating. No message will be sent."); return; } auto context = isolate->GetCurrentContext(); Local transferList = args.Length() > 1 ? args[1] : v8::Undefined(isolate).As(); auto message = std::make_shared(); if (message->Serialize(isolate, context, args[0], transferList, serialization::HostObjectPolicy::kDegrade) .IsNothing()) { // The transfer list was rejected or the value could not be cloned; // the exception is already pending and nothing may be posted. return; } wrapper->PostMessageToParent(message); DEBUG_WRITE("WORKER: WorkerGlobalPostMessageCallback called."); } catch (NativeScriptException &ex) { ex.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::WorkerObjectTerminateCallback(const v8::FunctionCallbackInfo &args) { auto isolate = args.GetIsolate(); DEBUG_WRITE("WORKER: WorkerObjectTerminateCallback called."); try { HandleScope scope(isolate); auto thiz = args.This(); // Worker instance auto context = isolate->GetCurrentContext(); Local jsId; auto maybejsId = V8GetPrivateValue(isolate, thiz, ArgConverter::ConvertToV8String(isolate, "workerId"), jsId); // get worker's ID that is associated on the other side - in Java auto id = jsId->Int32Value(context).ToChecked(); Local isTerminated; V8GetPrivateValue(isolate, thiz, ArgConverter::ConvertToV8String(isolate, "isTerminated"), isTerminated); if (!isTerminated.IsEmpty() && isTerminated->BooleanValue(isolate)) { DEBUG_WRITE( "Main: WorkerObjectTerminateCallback - Worker(id=%d)'s terminate has already been called.", id); return; } V8SetPrivateValue(isolate, thiz, ArgConverter::ConvertToV8String(isolate, "isTerminated"), Boolean::New(isolate, true)); auto wrapper = WorkerWrapper::GetById(id); if (wrapper != nullptr) { // Only starts the wind-down. The Worker object stays rooted and // the registry entry stays until the worker thread's own last act // notifies the parent, so no GC can condemn a wrapper whose thread // is still draining. wrapper->Terminate(); } } catch (NativeScriptException &ex) { ex.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::WorkerGlobalCloseCallback(const v8::FunctionCallbackInfo &args) { auto isolate = args.GetIsolate(); DEBUG_WRITE("WORKER: WorkerThreadCloseCallback called."); try { HandleScope scope(isolate); auto context = isolate->GetCurrentContext(); auto globalObject = context->Global(); auto isTerminating = globalObject->Get( context, ArgConverter::ConvertToV8String(isolate, "isTerminating")).ToLocalChecked(); if (!isTerminating.IsEmpty() && isTerminating->BooleanValue(isolate)) { DEBUG_WRITE("WORKER: WorkerThreadCloseCallback - Worker is currently terminating..."); return; } globalObject->Set(context, ArgConverter::ConvertToV8String(isolate, "isTerminating"), Boolean::New(isolate, true)); // execute onclose handler if one is implemented auto callback = globalObject->Get(context, ArgConverter::ConvertToV8String(isolate, "onclose")).ToLocalChecked(); auto isEmpty = callback.IsEmpty(); auto isFunction = callback->IsFunction(); TryCatch tc(isolate); if (!isEmpty && isFunction) { Local args1[] = {}; auto func = callback.As(); DEBUG_WRITE("WORKER: WorketThreadCloseCallback onclose handle is being called."); func->Call(context, Undefined(isolate), 0, args1); DEBUG_WRITE("WORKER: WorketThreadCloseCallback onclose handle was called."); } if (tc.HasCaught()) { CallWorkerScopeOnErrorHandle(isolate, tc); } auto wrapper = WorkerWrapper::FromIsolate(isolate); if (wrapper != nullptr) { wrapper->Close(); } } catch (NativeScriptException &ex) { ex.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } /* * Extracts message/filename/stack/line info from a TryCatch into plain * strings that can safely cross to the main thread. Robust against empty * v8 messages (e.g. when execution was terminated). */ static void ExtractTryCatchInfo(Isolate *isolate, Local context, TryCatch &tc, std::string &message, std::string &source, std::string &stackTrace, int &lineno) { message = ""; source = ""; stackTrace = ""; lineno = 0; if (!tc.Message().IsEmpty()) { lineno = tc.Message()->GetLineNumber(context).FromMaybe(0); message = ArgConverter::ConvertToString(tc.Message()->Get()); Local src; if (tc.Message()->GetScriptResourceName()->ToString(context).ToLocal(&src)) { source = ArgConverter::ConvertToString(src); } } if (message.empty() && !tc.Exception().IsEmpty()) { Local exStr; if (tc.Exception()->ToDetailString(context).ToLocal(&exStr)) { message = ArgConverter::ConvertToString(exStr); } } // `stack` may be an accessor. One that throws only costs the stack: caught // here, its exception cannot replace the one `tc` holds. TryCatch stackTc(isolate); Local outStackTrace = tc.StackTrace(context).FromMaybe(Local()); if (!outStackTrace.IsEmpty()) { Local stackTraceStr = outStackTrace->ToDetailString(context).FromMaybe(Local()); if (!stackTraceStr.IsEmpty()) { stackTrace = ArgConverter::ConvertToString(stackTraceStr); } } } void CallbackHandlers::CallWorkerScopeOnErrorHandle(Isolate *isolate, TryCatch &tc) { try { auto wrapper = WorkerWrapper::FromIsolate(isolate); if (wrapper != nullptr && wrapper->IsTerminating()) { // The worker was terminated mid-execution (e.g. terminate() // interrupting a busy loop) - nothing to report. return; } TryCatch innerTc(isolate); // See if `onerror` handle is implemented auto context = isolate->GetCurrentContext(); auto globalObject = context->Global(); // execute onerror handle if one is implemented Local callback; if (!globalObject->Get(context, ArgConverter::ConvertToV8String(isolate, "onerror")) .ToLocal(&callback)) { return; } auto isFunction = callback->IsFunction(); if (isFunction && !tc.Message().IsEmpty()) { auto msg = tc.Message()->Get(); Local args1[] = {msg}; auto func = callback.As(); Local result; func->Call(context, Undefined(isolate), 1, args1).ToLocal(&result); // return 'true'-like value, don't bubble up to main Worker.onerror if (!result.IsEmpty() && result->BooleanValue(isolate)) { // Do nothing, exception has been handled return; } } if (wrapper == nullptr) { return; } std::string message, source, stackTrace; int lineno; // A scope handler that threw replaces the error it was offered: the // parent sees the handler's own error, and only that one. if (innerTc.HasCaught()) { ExtractTryCatchInfo(isolate, context, innerTc, message, source, stackTrace, lineno); wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno, innerTc.Exception()); return; } // Unhandled at the worker scope - including when there is no scope // handler at all - so it becomes the parent's error event. ExtractTryCatchInfo(isolate, context, tc, message, source, stackTrace, lineno); wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno, tc.Exception()); } catch (NativeScriptException &ex) { ex.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void CallbackHandlers::RemoveIsolateEntries(v8::Isolate *isolate) { { std::lock_guard lock(cacheMutex_); for (auto it = cache_.begin(); it != cache_.end();) { if (it->second.isolate_ == isolate) { it = cache_.erase(it); } else { ++it; } } } } robin_hood::unordered_map CallbackHandlers::cache_; std::mutex CallbackHandlers::cacheMutex_; std::atomic_int64_t CallbackHandlers::count_ = {0}; short CallbackHandlers::MAX_JAVA_STRING_ARRAY_LENGTH = 100; jclass CallbackHandlers::RUNTIME_CLASS = nullptr; jclass CallbackHandlers::JAVA_LANG_STRING = nullptr; jfieldID CallbackHandlers::CURRENT_OBJECTID_FIELD_ID = nullptr; jfieldID CallbackHandlers::CURRENT_OBJECTCLASS_FIELD_ID = nullptr; jmethodID CallbackHandlers::RESOLVE_CLASS_METHOD_ID = nullptr; jmethodID CallbackHandlers::REGISTER_CONSTRUCTED_INSTANCE_ID = nullptr; jmethodID CallbackHandlers::GET_TYPE_METADATA = nullptr; jmethodID CallbackHandlers::ENABLE_VERBOSE_LOGGING_METHOD_ID = nullptr; jmethodID CallbackHandlers::DISABLE_VERBOSE_LOGGING_METHOD_ID = nullptr; NumericCasts CallbackHandlers::castFunctions; ArrayElementAccessor CallbackHandlers::arrayElementAccessor; FieldAccessor CallbackHandlers::fieldAccessor;