Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -289,9 +289,10 @@ jobs:
# attempt's bundle out of it first.
on_retry_command: rm -rf $TEST_FOLDER-attempt1; mv $TEST_FOLDER $TEST_FOLDER-attempt1 2>/dev/null || true
- name: Extract test results
# run_tests.sh extracts the report itself; extracting again would collide.
if: ${{ !cancelled() }}
run: |
if [ -d "$TEST_FOLDER/test_results.xcresult" ]; then
if [ -d "$TEST_FOLDER/test_results.xcresult" ] && ! ls "$TEST_FOLDER"/test-out/*junit*.xml >/dev/null 2>&1; then
./scripts/export-test-attachments.sh --result "$TEST_FOLDER/test_results.xcresult" --output "$TEST_FOLDER/test-out"
fi
- name: Test report summary
Expand Down
6 changes: 2 additions & 4 deletions NativeScript/napi/NapiEnv.mm
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <cstdlib>

#include "NapiThreadSafeFunction.h"
#include "runtime/Checks.h"
#include "runtime/Helpers.h"
#include "runtime/NativeScriptException.h"
#include "runtime/Runtime.h"
Expand Down Expand Up @@ -187,10 +188,7 @@
namespace v8impl {

void OnFatalError(const char* location, const char* message) {
Log(@"NativeScript Node-API fatal error: %s%s%s", message,
location != nullptr ? " at " : "", location != nullptr ? location : "");
tns::LogBacktrace();
abort();
tns::Fatal(location, std::string("Node-API: ") + (message != nullptr ? message : ""));
}

} // namespace v8impl
47 changes: 19 additions & 28 deletions NativeScript/runtime/ArgConverter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
#include "NativeScriptException.h"
#include "ObjectManager.h"
#include "Runtime.h"
#include "RuntimeConfig.h"
#include "WrapperLifetime.h"
#include "WrapperLifetimeCanary.h"

Expand Down Expand Up @@ -135,6 +134,18 @@ bool IsKVOSubclassOf(Class klass, Class base) {
return Caches::Get(isolate)->EmptyObjCtorFunc.get();
}

[[noreturn]] static void ThrowInvalidReceiver(Isolate* isolate, Class klass, const MethodMeta* meta,
const std::string& receiverDescription) {
const char* selectorStr = meta ? meta->selectorAsString() : "<unknown>";
const char* jsNameStr = meta ? meta->jsName() : "<unknown>";
const char* classNameStr = klass ? class_getName(klass) : "<unknown>";
std::string message = std::string("Cannot call method '") + jsNameStr + "' on " +
receiverDescription + " (class: " + classNameStr +
", selector: " + selectorStr + ").";
throw NativeScriptException(isolate, v8::Exception::TypeError(tns::ToV8String(isolate, message)),
message);
}

Local<Value> ArgConverter::Invoke(Local<Context> context, Class klass, Local<Object> receiver,
V8Args& args, const MethodMeta* meta, bool isMethodCallback) {
Isolate* isolate = v8::Isolate::GetCurrent();
Expand All @@ -154,21 +165,10 @@ bool IsKVOSubclassOf(Class klass, Class base) {
tns::ThrowReleasedObject(isolate, releasedReason,
std::string("method '") + jsNameStr + "' receiver");
}
// During fast view churn like HMR in development, JS objects can outlive their
// native wrappers briefly. In Debug, throw a catchable JS error instead of crashing.
// In Release, assert so crash reporting can capture unexpected cases.
if (RuntimeConfig.IsDebug) {
const char* selectorStr = meta ? meta->selectorAsString() : "<unknown>";
const char* jsNameStr = meta ? meta->jsName() : "<unknown>";
const char* classNameStr = klass ? class_getName(klass) : "<unknown>";
std::string errMsg = std::string("Cannot call method '") + jsNameStr +
"' on a disposed native object (class: " + classNameStr +
", selector: " + selectorStr +
"). This can happen during HMR or fast view churn.";
throw NativeScriptException(isolate, errMsg);
} else {
tns::Assert(false, isolate);
}
ThrowInvalidReceiver(isolate, klass, meta,
receiver->InternalFieldCount() > 0
? "a receiver that has no native object"
: "a receiver that is not a native object");
}

if (wrapper->Type() == WrapperType::ObjCAllocObject) {
Expand All @@ -183,18 +183,9 @@ bool IsKVOSubclassOf(Class klass, Class base) {
// For extended classes we will call the base method
callSuper = isMethodCallback && it != cache->ClassPrototypes.end();
} else {
if (RuntimeConfig.IsDebug) {
const char* selectorStr = meta ? meta->selectorAsString() : "<unknown>";
const char* jsNameStr = meta ? meta->jsName() : "<unknown>";
const char* classNameStr = klass ? class_getName(klass) : "<unknown>";
std::string errMsg = std::string("Unexpected receiver wrapper type ") +
std::to_string((int)wrapper->Type()) + " for method '" + jsNameStr +
"' (class: " + classNameStr + ", selector: " + selectorStr +
"). This can happen during HMR or fast view churn.";
throw NativeScriptException(isolate, errMsg);
} else {
tns::Assert(false, isolate);
}
ThrowInvalidReceiver(isolate, klass, meta,
"a receiver that is not a native object instance (wrapper type " +
std::to_string((int)wrapper->Type()) + ")");
}
}

Expand Down
93 changes: 93 additions & 0 deletions NativeScript/runtime/Checks.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#ifndef Checks_h
#define Checks_h

#include <string>

// How runtime code handles a failed condition:
//
// - A condition JS can reach throws a JS error: a TypeError for a bad
// argument or receiver, or the exception a failed V8 call left pending.
// - A failed v8::Maybe / MaybeLocal call propagates its pending exception.
// - NS_CHECK(cond, message): an invariant whose violation makes continuing
// unsafe. On in every build.
// - NS_DCHECK(cond) / NS_DCHECK_MSG(cond, message): a cheap internal sanity
// check, on only while NS_DCHECK_IS_ON. It is the one intentional
// Debug/Release difference, so it never guards anything JS can reach.
// - NS_UNREACHABLE(message): a branch that cannot be taken.
// - tns::Assert is legacy: a call site moves to the above when its code is
// touched.
//
// All of them end in tns::Fatal, which logs the location, the message, the
// native backtrace and, when an isolate is entered on the calling thread, the
// JS stack, then aborts.
//
// The names are prefixed: the vendored V8 inspector headers and the Node-API
// shim define their own unprefixed CHECK/DCHECK.

namespace tns {

[[noreturn]] void Fatal(const char* location, const std::string& message);

} // namespace tns

#define NS_CHECKS_STRINGIFY_HELPER(x) #x
#define NS_CHECKS_STRINGIFY(x) NS_CHECKS_STRINGIFY_HELPER(x)
#define NS_CHECKS_LOCATION __FILE__ ":" NS_CHECKS_STRINGIFY(__LINE__)

#ifndef NS_DCHECK_IS_ON
#if defined(DEBUG)
#define NS_DCHECK_IS_ON 1
#elif defined(__has_feature)
#if __has_feature(address_sanitizer)
#define NS_DCHECK_IS_ON 1
#else
#define NS_DCHECK_IS_ON 0
#endif
#else
#define NS_DCHECK_IS_ON 0
#endif
#endif

#define NS_CHECK(cond, message) \
do { \
if (!(cond)) [[unlikely]] { \
::tns::Fatal(NS_CHECKS_LOCATION, \
std::string("NS_CHECK(" #cond ") failed: ") + (message)); \
} \
} while (0)

#if NS_DCHECK_IS_ON
#define NS_DCHECK(cond) \
do { \
if (!(cond)) [[unlikely]] { \
::tns::Fatal(NS_CHECKS_LOCATION, "NS_DCHECK(" #cond ") failed"); \
} \
} while (0)
#define NS_DCHECK_MSG(cond, message) \
do { \
if (!(cond)) [[unlikely]] { \
::tns::Fatal(NS_CHECKS_LOCATION, \
std::string("NS_DCHECK(" #cond ") failed: ") + (message)); \
} \
} while (0)
#else
// Never evaluated, but still compiled, so names used only here stay used.
#define NS_DCHECK(cond) \
do { \
if (false) { \
(void)(cond); \
} \
} while (0)
#define NS_DCHECK_MSG(cond, message) \
do { \
if (false) { \
(void)(cond); \
(void)(message); \
} \
} while (0)
#endif

#define NS_UNREACHABLE(message) \
::tns::Fatal(NS_CHECKS_LOCATION, std::string("NS_UNREACHABLE: ") + (message))

#endif /* Checks_h */
84 changes: 63 additions & 21 deletions NativeScript/runtime/ClassBuilder.mm
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
struct RetainTrackedClasses {
std::unordered_set<void*> classes;
};

void ThrowTypeError(Isolate* isolate, const std::string& message) {
isolate->ThrowException(Exception::TypeError(tns::ToV8String(isolate, message)));
}
} // namespace

Local<FunctionTemplate> ClassBuilder::GetExtendFunction(Isolate* isolate,
Expand All @@ -54,16 +58,31 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
void ClassBuilder::ExtendCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();

tns::Assert(info.Length() > 0 && info[0]->IsObject() && info.This()->IsFunction(), isolate);
if (!info.This()->IsFunction()) {
ThrowTypeError(isolate, "extend() must be called on a native class constructor");
return;
}
Local<v8::Function> baseFunc = info.This().As<v8::Function>();
std::string baseClassName = tns::ToString(isolate, baseFunc->GetName());
if (info.Length() == 0 || !info[0]->IsObject()) {
ThrowTypeError(isolate, baseClassName +
".extend() expects an object with the class's members as its "
"first argument");
return;
}
if (info.Length() > 1 && !info[1]->IsNullOrUndefined() && !info[1]->IsObject()) {
ThrowTypeError(isolate, baseClassName +
".extend() expects an object with the native class options "
"(name, protocols, exposedMethods) as its second argument");
return;
}

try {
Local<Context> context = isolate->GetCurrentContext();
CacheItem* item = static_cast<CacheItem*>(
info.Data().As<External>()->Value(v8::kExternalPointerTypeTagDefault));

Local<Object> implementationObject = info[0].As<Object>();
Local<v8::Function> baseFunc = info.This().As<v8::Function>();
std::string baseClassName = tns::ToString(isolate, baseFunc->GetName());

BaseDataWrapper* baseWrapper = tns::GetValue(isolate, baseFunc);
if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::ObjCClass) {
Expand All @@ -78,16 +97,39 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
if (info.Length() > 1 && info[1]->IsObject()) {
nativeSignature = info[1].As<Object>();
Local<Value> explicitClassName;
tns::Assert(nativeSignature->Get(context, tns::ToV8String(isolate, "name"))
.ToLocal(&explicitClassName),
isolate);
if (!nativeSignature->Get(context, tns::ToV8String(isolate, "name"))
.ToLocal(&explicitClassName)) {
return;
}
if (!explicitClassName.IsEmpty() && !explicitClassName->IsNullOrUndefined()) {
staticClassName = tns::ToString(isolate, explicitClassName);
}
}
auto cache = Caches::Get(isolate);
auto isolateId = cache->getIsolateId();

Local<v8::Function> baseCtorFunc =
cache->CtorFuncs.find(item->meta_->name())->second->Get(isolate);
Local<Value> baseProto;
bool success =
baseCtorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&baseProto);
tns::Assert(success, isolate);

// Probed before the native class is registered, so a refusal leaves no class
// holding the requested name. The original prototype goes back right away:
// member discovery below reads through it. A refused change comes back as
// Nothing with no exception pending. Not for a Proxy: GetPrototype() does not
// reach its target, so the restore would drop the target's prototype.
Local<Value> originalProto = implementationObject->GetPrototype();
Comment thread
edusperoni marked this conversation as resolved.
Resolved
if (!implementationObject->IsProxy() &&
(!implementationObject->SetPrototype(context, baseProto).FromMaybe(false) ||
!implementationObject->SetPrototype(context, originalProto).FromMaybe(false))) {
ThrowTypeError(isolate, baseClassName +
".extend() could not set the prototype of its first argument, "
"which must be an extensible object");
return;
}

ScopeClassNameToIsolate(staticClassName, isolateId);
Class extendedClass = ClassBuilder::GetExtendedClass(baseClassName, staticClassName, isolateId);
tns::Assert(extendedClass != nil, isolate);
Expand All @@ -103,9 +145,6 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
implementationObject);
}

Local<v8::Function> baseCtorFunc =
cache->CtorFuncs.find(item->meta_->name())->second->Get(isolate);

CacheItem* cacheItem = new CacheItem(nullptr, extendedClass);
Caches::Get(isolate)->registerCacheBoundObject(cacheItem);
Local<External> ext = External::New(isolate, cacheItem, v8::kExternalPointerTypeTagDefault);
Expand All @@ -120,13 +159,11 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
tns::Assert(false, isolate);
}

Local<Value> baseProto;
bool success =
baseCtorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&baseProto);
tns::Assert(success, isolate);

if (!implementationObject->SetPrototype(context, baseProto).To(&success) || !success) {
tns::Assert(false, isolate);
if (!implementationObject->SetPrototype(context, baseProto).FromMaybe(false)) {
Comment thread
edusperoni marked this conversation as resolved.
Resolved
ThrowTypeError(isolate, baseClassName +
".extend() could not set the prototype of its first argument, "
"which must be an extensible object");
return;
}
Local<v8::Function> superGetter;
if (!FunctionTemplate::New(isolate, SuperAccessorGetterCallback, ext)
Expand Down Expand Up @@ -214,22 +251,27 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
Local<Context> context = isolate->GetCurrentContext();

auto cache = Caches::Get(isolate);
BaseDataWrapper* wrapper = tns::GetValue(isolate, info[1].As<Object>());
if (!wrapper) {
// We are not extending a native object -> call the base __extends function
BaseDataWrapper* wrapper =
info[1]->IsObject() ? tns::GetValue(isolate, info[1].As<Object>()) : nullptr;
if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCClass) {
// Not a native class: the base __extends function's inheritance.
Persistent<v8::Function>* poExtendsFunc = cache->OriginalExtendsFunc.get();
tns::Assert(poExtendsFunc != nullptr, isolate);
Local<v8::Function> originalExtendsFunc = poExtendsFunc->Get(isolate);
Local<Value> args[] = {info[0], info[1]};
originalExtendsFunc->Call(context, context->Global(), info.Length(), args)
.ToLocalChecked();
(void)originalExtendsFunc->Call(context, context->Global(), 2, args);
return;
}

ObjCClassWrapper* classWrapper = static_cast<ObjCClassWrapper*>(wrapper);
Class baseClass = classWrapper->Klass();
std::string baseClassName = class_getName(baseClass);

if (!info[0]->IsFunction()) {
ThrowTypeError(isolate,
"__extends() expects a constructor function to extend " + baseClassName);
return;
}
Local<v8::Function> extendedClassCtorFunc = info[0].As<v8::Function>();
std::string extendedClassName = tns::ToString(isolate, extendedClassCtorFunc->GetName());

Expand Down
7 changes: 4 additions & 3 deletions NativeScript/runtime/Helpers.h
Original file line number Diff line number Diff line change
Expand Up @@ -587,10 +587,11 @@ std::string GetSmartStackTrace(v8::Isolate* isolate, v8::TryCatch* tryCatch = nu

bool LiveSync(v8::Isolate* isolate);

// Legacy: new code uses NS_CHECK / NS_DCHECK / NS_UNREACHABLE (Checks.h), or
// throws for a condition JS can reach.
void Assert(bool condition, v8::Isolate* isolate = nullptr,
std::string const& reason = std::string());

void StopExecutionAndLogStackTrace(v8::Isolate* isolate);
std::string const& reason = std::string(), const char* file = __builtin_FILE(),
int line = __builtin_LINE());

// Helpers from Node
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const char* data, int length) {
Expand Down
Loading
Loading