Skip to content

Commit d888aad

Browse files
authored
fix(runtime): same error handling in Debug and Release (#605)
* fix(runtime): throw a TypeError for invalid method receivers in every build A native method or accessor called on a receiver with no native object, or on a wrapper that is not an Objective-C instance (an interop.Pointer, a Reference), threw a JS error only when RuntimeConfig.IsDebug was set and hit tns::Assert otherwise, so the same JS aborted a Release app. Both cases now throw a catchable TypeError naming the method, class and selector. * fix(test): fail run_tests.sh on failing specs and add --configuration XCTest passes once the app delivers its junit report, whatever the report says, and the script discarded verify-junit-xml's status, so a run with failing specs exited 0. The script now exits non-zero when the report is missing or records a failure, exporting the attachments without xcparse when it is not installed. -c/--configuration Debug|Release builds the suite in that configuration; a Release TestRunner also starts the runtime with IsDebug off. * fix(runtime): log and abort from tns::Assert the same way in every build Release builds ran a bare assert(condition): no reason, no native or JS stack, and a check that NDEBUG would compile out. tns::Assert now has one path for every build: it logs the failure, the reason, the native backtrace and, when the isolate is entered on the calling thread, the JS stack, then calls abort(). * refactor(runtime): remove the logRuntimeDetail write-value checks and traces The logRuntimeDetail app config key enabled, only in a runtime compiled with DEBUG (never the shipped framework), a trace of every method call and object write plus write-value checks that aborted on conversions every other build performs. Remove the key's readers, the checks and their helpers, and the now unused tns::StopExecutionAndLogStackTrace. * fix(runtime): reject non-native receivers of native instance members An instance method whose `this` had no internal fields was sent to the class instead: NSObject.prototype.isEqual.call({}, x) ran +[NSObject isEqual:], and an instance property getter returned undefined. Instance methods now have their own callback, and they and instance property accessors share one rule: a native class constructor receiver makes a class-side call, any other receiver must be a native object, or the call throws "Cannot call method ... on a receiver that is not a native object". Class methods are unchanged. Reading a native instance property on a prototype object now throws too. * feat(runtime): add tns::Fatal and NS_CHECK/NS_DCHECK/NS_UNREACHABLE Checks.h holds the runtime's error-handling policy and one fatal path, 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. - NS_CHECK(cond, message): on in every build. - NS_DCHECK(cond) / NS_DCHECK_MSG(cond, message): on while NS_DCHECK_IS_ON, which defaults to 1 in DEBUG and AddressSanitizer builds and 0 otherwise. When off, the condition is compiled but never evaluated. - NS_UNREACHABLE(message). tns::Assert keeps its call signature and forwards to tns::Fatal with its caller's file and line. Node-API's v8impl::OnFatalError reports through tns::Fatal too. * fix(runtime): throw instead of aborting for bad native constructor and alloc calls A native class constructor called without new (NSObject(), Reflect.apply) and alloc() called with arguments hit tns::Assert. They now throw a TypeError. Constructing a protocol (new NSCopying()) throws a TypeError, and constructing a class that metadata lists but the runtime does not load throws an Error, instead of reaching ConstructObject without a class. * fix(runtime): throw instead of aborting for invalid extend() and __extends arguments ClassBuilder::ExtendCallback asserted its arguments, so NSObject.extend() with no or a non-object first argument, or an unbound call, aborted the process. It now throws a TypeError for a receiver that is not a function, a missing or non-object first argument, and a second argument that is neither an object nor null/undefined. An exception thrown while reading the options' name propagates to JS, and an implementation object whose prototype cannot be set (for example a frozen one) throws a TypeError instead of aborting. The native __extends callback hands any base that is not a native class (including other native wrapper types) to the base __extends function, propagates that function's exceptions instead of crashing on ToLocalChecked, and throws a TypeError when the derived side is not a constructor function. * fix(runtime): accept a Proxy around a native class as a native accessor receiver Native property getters and setters rejected new Proxy(NSObject, {}) before the class-side normalization, while the constructor itself and native instance methods accept it as a class-side call. Both accessor paths now let ResolveProxyReceiver admit a class target. Revoked proxies and proxies around non-native objects still throw a TypeError. * fix(runtime): reject a non-extensible extend() implementation before registering its class extend() set the implementation object's prototype only after GetExtendedClass had registered the native class, so a frozen implementation threw with the class already registered under the requested name: a corrected retry got a suffixed name while native lookup of the requested one found the failed class. The prototype change is now probed before registration and undone at once, since member discovery reads through the original prototype; the later assignment keeps its check. * ci: skip the Catalyst job's report extraction when run_tests.sh already did it run_tests.sh now extracts the junit report from the result bundle itself, and a second export-test-attachments.sh run into the same folder fails on its existing manifest.json. * fix(runtime): keep a Proxy implementation's prototype through the extend() probe v8::Object::GetPrototype() does not reach a Proxy's target while SetPrototype() forwards to it, so restoring after the probe dropped the target's prototype, and with it an inherited Symbol.iterator, before member discovery. A Proxy implementation skips the early probe; the later prototype assignment still rejects a frozen one.
1 parent ff36f6e commit d888aad

20 files changed

Lines changed: 585 additions & 207 deletions

‎.github/workflows/pull_request.yml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,9 +289,10 @@ jobs:
289289
# attempt's bundle out of it first.
290290
on_retry_command: rm -rf $TEST_FOLDER-attempt1; mv $TEST_FOLDER $TEST_FOLDER-attempt1 2>/dev/null || true
291291
- name: Extract test results
292+
# run_tests.sh extracts the report itself; extracting again would collide.
292293
if: ${{ !cancelled() }}
293294
run: |
294-
if [ -d "$TEST_FOLDER/test_results.xcresult" ]; then
295+
if [ -d "$TEST_FOLDER/test_results.xcresult" ] && ! ls "$TEST_FOLDER"/test-out/*junit*.xml >/dev/null 2>&1; then
295296
./scripts/export-test-attachments.sh --result "$TEST_FOLDER/test_results.xcresult" --output "$TEST_FOLDER/test-out"
296297
fi
297298
- name: Test report summary

‎NativeScript/napi/NapiEnv.mm‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <cstdlib>
55

66
#include "NapiThreadSafeFunction.h"
7+
#include "runtime/Checks.h"
78
#include "runtime/Helpers.h"
89
#include "runtime/NativeScriptException.h"
910
#include "runtime/Runtime.h"
@@ -187,10 +188,7 @@
187188
namespace v8impl {
188189

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

196194
} // namespace v8impl

‎NativeScript/runtime/ArgConverter.mm‎

Lines changed: 19 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
#include "NativeScriptException.h"
1313
#include "ObjectManager.h"
1414
#include "Runtime.h"
15-
#include "RuntimeConfig.h"
1615
#include "WrapperLifetime.h"
1716
#include "WrapperLifetimeCanary.h"
1817

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

137+
[[noreturn]] static void ThrowInvalidReceiver(Isolate* isolate, Class klass, const MethodMeta* meta,
138+
const std::string& receiverDescription) {
139+
const char* selectorStr = meta ? meta->selectorAsString() : "<unknown>";
140+
const char* jsNameStr = meta ? meta->jsName() : "<unknown>";
141+
const char* classNameStr = klass ? class_getName(klass) : "<unknown>";
142+
std::string message = std::string("Cannot call method '") + jsNameStr + "' on " +
143+
receiverDescription + " (class: " + classNameStr +
144+
", selector: " + selectorStr + ").";
145+
throw NativeScriptException(isolate, v8::Exception::TypeError(tns::ToV8String(isolate, message)),
146+
message);
147+
}
148+
138149
Local<Value> ArgConverter::Invoke(Local<Context> context, Class klass, Local<Object> receiver,
139150
V8Args& args, const MethodMeta* meta, bool isMethodCallback) {
140151
Isolate* isolate = v8::Isolate::GetCurrent();
@@ -154,21 +165,10 @@ bool IsKVOSubclassOf(Class klass, Class base) {
154165
tns::ThrowReleasedObject(isolate, releasedReason,
155166
std::string("method '") + jsNameStr + "' receiver");
156167
}
157-
// During fast view churn like HMR in development, JS objects can outlive their
158-
// native wrappers briefly. In Debug, throw a catchable JS error instead of crashing.
159-
// In Release, assert so crash reporting can capture unexpected cases.
160-
if (RuntimeConfig.IsDebug) {
161-
const char* selectorStr = meta ? meta->selectorAsString() : "<unknown>";
162-
const char* jsNameStr = meta ? meta->jsName() : "<unknown>";
163-
const char* classNameStr = klass ? class_getName(klass) : "<unknown>";
164-
std::string errMsg = std::string("Cannot call method '") + jsNameStr +
165-
"' on a disposed native object (class: " + classNameStr +
166-
", selector: " + selectorStr +
167-
"). This can happen during HMR or fast view churn.";
168-
throw NativeScriptException(isolate, errMsg);
169-
} else {
170-
tns::Assert(false, isolate);
171-
}
168+
ThrowInvalidReceiver(isolate, klass, meta,
169+
receiver->InternalFieldCount() > 0
170+
? "a receiver that has no native object"
171+
: "a receiver that is not a native object");
172172
}
173173

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

‎NativeScript/runtime/Checks.h‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#ifndef Checks_h
2+
#define Checks_h
3+
4+
#include <string>
5+
6+
// How runtime code handles a failed condition:
7+
//
8+
// - A condition JS can reach throws a JS error: a TypeError for a bad
9+
// argument or receiver, or the exception a failed V8 call left pending.
10+
// - A failed v8::Maybe / MaybeLocal call propagates its pending exception.
11+
// - NS_CHECK(cond, message): an invariant whose violation makes continuing
12+
// unsafe. On in every build.
13+
// - NS_DCHECK(cond) / NS_DCHECK_MSG(cond, message): a cheap internal sanity
14+
// check, on only while NS_DCHECK_IS_ON. It is the one intentional
15+
// Debug/Release difference, so it never guards anything JS can reach.
16+
// - NS_UNREACHABLE(message): a branch that cannot be taken.
17+
// - tns::Assert is legacy: a call site moves to the above when its code is
18+
// touched.
19+
//
20+
// All of them end in tns::Fatal, which logs the location, the message, the
21+
// native backtrace and, when an isolate is entered on the calling thread, the
22+
// JS stack, then aborts.
23+
//
24+
// The names are prefixed: the vendored V8 inspector headers and the Node-API
25+
// shim define their own unprefixed CHECK/DCHECK.
26+
27+
namespace tns {
28+
29+
[[noreturn]] void Fatal(const char* location, const std::string& message);
30+
31+
} // namespace tns
32+
33+
#define NS_CHECKS_STRINGIFY_HELPER(x) #x
34+
#define NS_CHECKS_STRINGIFY(x) NS_CHECKS_STRINGIFY_HELPER(x)
35+
#define NS_CHECKS_LOCATION __FILE__ ":" NS_CHECKS_STRINGIFY(__LINE__)
36+
37+
#ifndef NS_DCHECK_IS_ON
38+
#if defined(DEBUG)
39+
#define NS_DCHECK_IS_ON 1
40+
#elif defined(__has_feature)
41+
#if __has_feature(address_sanitizer)
42+
#define NS_DCHECK_IS_ON 1
43+
#else
44+
#define NS_DCHECK_IS_ON 0
45+
#endif
46+
#else
47+
#define NS_DCHECK_IS_ON 0
48+
#endif
49+
#endif
50+
51+
#define NS_CHECK(cond, message) \
52+
do { \
53+
if (!(cond)) [[unlikely]] { \
54+
::tns::Fatal(NS_CHECKS_LOCATION, \
55+
std::string("NS_CHECK(" #cond ") failed: ") + (message)); \
56+
} \
57+
} while (0)
58+
59+
#if NS_DCHECK_IS_ON
60+
#define NS_DCHECK(cond) \
61+
do { \
62+
if (!(cond)) [[unlikely]] { \
63+
::tns::Fatal(NS_CHECKS_LOCATION, "NS_DCHECK(" #cond ") failed"); \
64+
} \
65+
} while (0)
66+
#define NS_DCHECK_MSG(cond, message) \
67+
do { \
68+
if (!(cond)) [[unlikely]] { \
69+
::tns::Fatal(NS_CHECKS_LOCATION, \
70+
std::string("NS_DCHECK(" #cond ") failed: ") + (message)); \
71+
} \
72+
} while (0)
73+
#else
74+
// Never evaluated, but still compiled, so names used only here stay used.
75+
#define NS_DCHECK(cond) \
76+
do { \
77+
if (false) { \
78+
(void)(cond); \
79+
} \
80+
} while (0)
81+
#define NS_DCHECK_MSG(cond, message) \
82+
do { \
83+
if (false) { \
84+
(void)(cond); \
85+
(void)(message); \
86+
} \
87+
} while (0)
88+
#endif
89+
90+
#define NS_UNREACHABLE(message) \
91+
::tns::Fatal(NS_CHECKS_LOCATION, std::string("NS_UNREACHABLE: ") + (message))
92+
93+
#endif /* Checks_h */

‎NativeScript/runtime/ClassBuilder.mm‎

Lines changed: 63 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
4141
struct RetainTrackedClasses {
4242
std::unordered_set<void*> classes;
4343
};
44+
45+
void ThrowTypeError(Isolate* isolate, const std::string& message) {
46+
isolate->ThrowException(Exception::TypeError(tns::ToV8String(isolate, message)));
47+
}
4448
} // namespace
4549

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

57-
tns::Assert(info.Length() > 0 && info[0]->IsObject() && info.This()->IsFunction(), isolate);
61+
if (!info.This()->IsFunction()) {
62+
ThrowTypeError(isolate, "extend() must be called on a native class constructor");
63+
return;
64+
}
65+
Local<v8::Function> baseFunc = info.This().As<v8::Function>();
66+
std::string baseClassName = tns::ToString(isolate, baseFunc->GetName());
67+
if (info.Length() == 0 || !info[0]->IsObject()) {
68+
ThrowTypeError(isolate, baseClassName +
69+
".extend() expects an object with the class's members as its "
70+
"first argument");
71+
return;
72+
}
73+
if (info.Length() > 1 && !info[1]->IsNullOrUndefined() && !info[1]->IsObject()) {
74+
ThrowTypeError(isolate, baseClassName +
75+
".extend() expects an object with the native class options "
76+
"(name, protocols, exposedMethods) as its second argument");
77+
return;
78+
}
5879

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

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

6887
BaseDataWrapper* baseWrapper = tns::GetValue(isolate, baseFunc);
6988
if (baseWrapper != nullptr && baseWrapper->Type() == WrapperType::ObjCClass) {
@@ -78,16 +97,39 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
7897
if (info.Length() > 1 && info[1]->IsObject()) {
7998
nativeSignature = info[1].As<Object>();
8099
Local<Value> explicitClassName;
81-
tns::Assert(nativeSignature->Get(context, tns::ToV8String(isolate, "name"))
82-
.ToLocal(&explicitClassName),
83-
isolate);
100+
if (!nativeSignature->Get(context, tns::ToV8String(isolate, "name"))
101+
.ToLocal(&explicitClassName)) {
102+
return;
103+
}
84104
if (!explicitClassName.IsEmpty() && !explicitClassName->IsNullOrUndefined()) {
85105
staticClassName = tns::ToString(isolate, explicitClassName);
86106
}
87107
}
88108
auto cache = Caches::Get(isolate);
89109
auto isolateId = cache->getIsolateId();
90110

111+
Local<v8::Function> baseCtorFunc =
112+
cache->CtorFuncs.find(item->meta_->name())->second->Get(isolate);
113+
Local<Value> baseProto;
114+
bool success =
115+
baseCtorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&baseProto);
116+
tns::Assert(success, isolate);
117+
118+
// Probed before the native class is registered, so a refusal leaves no class
119+
// holding the requested name. The original prototype goes back right away:
120+
// member discovery below reads through it. A refused change comes back as
121+
// Nothing with no exception pending. Not for a Proxy: GetPrototype() does not
122+
// reach its target, so the restore would drop the target's prototype.
123+
Local<Value> originalProto = implementationObject->GetPrototype();
124+
if (!implementationObject->IsProxy() &&
125+
(!implementationObject->SetPrototype(context, baseProto).FromMaybe(false) ||
126+
!implementationObject->SetPrototype(context, originalProto).FromMaybe(false))) {
127+
ThrowTypeError(isolate, baseClassName +
128+
".extend() could not set the prototype of its first argument, "
129+
"which must be an extensible object");
130+
return;
131+
}
132+
91133
ScopeClassNameToIsolate(staticClassName, isolateId);
92134
Class extendedClass = ClassBuilder::GetExtendedClass(baseClassName, staticClassName, isolateId);
93135
tns::Assert(extendedClass != nil, isolate);
@@ -103,9 +145,6 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
103145
implementationObject);
104146
}
105147

106-
Local<v8::Function> baseCtorFunc =
107-
cache->CtorFuncs.find(item->meta_->name())->second->Get(isolate);
108-
109148
CacheItem* cacheItem = new CacheItem(nullptr, extendedClass);
110149
Caches::Get(isolate)->registerCacheBoundObject(cacheItem);
111150
Local<External> ext = External::New(isolate, cacheItem, v8::kExternalPointerTypeTagDefault);
@@ -120,13 +159,11 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
120159
tns::Assert(false, isolate);
121160
}
122161

123-
Local<Value> baseProto;
124-
bool success =
125-
baseCtorFunc->Get(context, tns::ToV8String(isolate, "prototype")).ToLocal(&baseProto);
126-
tns::Assert(success, isolate);
127-
128-
if (!implementationObject->SetPrototype(context, baseProto).To(&success) || !success) {
129-
tns::Assert(false, isolate);
162+
if (!implementationObject->SetPrototype(context, baseProto).FromMaybe(false)) {
163+
ThrowTypeError(isolate, baseClassName +
164+
".extend() could not set the prototype of its first argument, "
165+
"which must be an extensible object");
166+
return;
130167
}
131168
Local<v8::Function> superGetter;
132169
if (!FunctionTemplate::New(isolate, SuperAccessorGetterCallback, ext)
@@ -214,22 +251,27 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) {
214251
Local<Context> context = isolate->GetCurrentContext();
215252

216253
auto cache = Caches::Get(isolate);
217-
BaseDataWrapper* wrapper = tns::GetValue(isolate, info[1].As<Object>());
218-
if (!wrapper) {
219-
// We are not extending a native object -> call the base __extends function
254+
BaseDataWrapper* wrapper =
255+
info[1]->IsObject() ? tns::GetValue(isolate, info[1].As<Object>()) : nullptr;
256+
if (wrapper == nullptr || wrapper->Type() != WrapperType::ObjCClass) {
257+
// Not a native class: the base __extends function's inheritance.
220258
Persistent<v8::Function>* poExtendsFunc = cache->OriginalExtendsFunc.get();
221259
tns::Assert(poExtendsFunc != nullptr, isolate);
222260
Local<v8::Function> originalExtendsFunc = poExtendsFunc->Get(isolate);
223261
Local<Value> args[] = {info[0], info[1]};
224-
originalExtendsFunc->Call(context, context->Global(), info.Length(), args)
225-
.ToLocalChecked();
262+
(void)originalExtendsFunc->Call(context, context->Global(), 2, args);
226263
return;
227264
}
228265

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

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

‎NativeScript/runtime/Helpers.h‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -587,10 +587,11 @@ std::string GetSmartStackTrace(v8::Isolate* isolate, v8::TryCatch* tryCatch = nu
587587

588588
bool LiveSync(v8::Isolate* isolate);
589589

590+
// Legacy: new code uses NS_CHECK / NS_DCHECK / NS_UNREACHABLE (Checks.h), or
591+
// throws for a condition JS can reach.
590592
void Assert(bool condition, v8::Isolate* isolate = nullptr,
591-
std::string const& reason = std::string());
592-
593-
void StopExecutionAndLogStackTrace(v8::Isolate* isolate);
593+
std::string const& reason = std::string(), const char* file = __builtin_FILE(),
594+
int line = __builtin_LINE());
594595

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

0 commit comments

Comments
 (0)