Repository navigation
Expand file tree
/
Copy pathHelpers.h
More file actions
789 lines (691 loc) · 33.2 KB
/
Copy pathHelpers.h
File metadata and controls
789 lines (691 loc) · 33.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
#ifndef Helpers_h
#define Helpers_h
#include <atomic>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <functional>
#include <optional>
#include <string>
#include <vector>
#include "ArcMacro.h"
#include "Common.h"
#include "DataWrapper.h"
#ifdef __OBJC__
#include <Foundation/Foundation.h>
#else
#include <CoreFoundation/CoreFoundation.h>
extern "C" void NSLog(CFStringRef format, ...);
#endif
#if defined(__has_include)
#if __has_include(<os/log.h>)
#include <os/log.h>
#define TNS_HAVE_OS_LOG 1
#else
#define TNS_HAVE_OS_LOG 0
#endif
#else
#define TNS_HAVE_OS_LOG 0
#endif
#include "LogChunks.h"
namespace tns {
inline v8::Local<v8::String> ToV8String(v8::Isolate* isolate, const std::string& value) {
return v8::String::NewFromUtf8(isolate, value.c_str(), v8::NewStringType::kNormal,
(int)value.length())
.ToLocalChecked();
}
inline v8::Local<v8::String> ToV8String(v8::Isolate* isolate, const char* value, int length) {
return v8::String::NewFromUtf8(isolate, value, v8::NewStringType::kNormal, length)
.ToLocalChecked();
}
// Without this overload a bare `const char*` — every string literal, every
// c_str(), every jsName() — picks the std::string one and pays for a temporary
// just to reach V8.
inline v8::Local<v8::String> ToV8String(v8::Isolate* isolate, const char* value) {
return v8::String::NewFromUtf8(isolate, value).ToLocalChecked();
}
#ifdef __OBJC__
// Both sides store text as either 8-bit or UTF-16, never UTF-8, so the buffer is
// handed to V8 in whichever width CFString already holds. Going through
// -UTF8String instead would encode the string twice (once for the bytes, once
// for -lengthOfBytesUsingEncoding:), allocate, and return nil for strings
// containing a lone surrogate — silently turning them into "".
inline v8::Local<v8::String> ToV8String(v8::Isolate* isolate, const NSString* value) {
if (value == nil) {
return v8::String::Empty(isolate);
}
CFStringRef str = (__bridge CFStringRef)value;
CFIndex length = CFStringGetLength(str);
if (length == 0) {
return v8::String::Empty(isolate);
}
// An ASCII pointer is handed back only when every code unit is < 0x80, so the
// code unit count doubles as the byte count.
if (const char* ascii = CFStringGetCStringPtr(str, kCFStringEncodingASCII)) {
return v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(ascii),
v8::NewStringType::kNormal, (int)length)
.ToLocalChecked();
}
if (const UniChar* utf16 = CFStringGetCharactersPtr(str)) {
return v8::String::NewFromTwoByte(isolate, reinterpret_cast<const uint16_t*>(utf16),
v8::NewStringType::kNormal, (int)length)
.ToLocalChecked();
}
// Tagged pointers and some bridged strings expose neither buffer, so the
// contents have to be copied out. The narrow attempt writes at most `length`
// bytes, which always fits the UTF-16-sized buffer.
constexpr CFIndex kStackUnits = 256;
uint16_t stackBuffer[kStackUnits];
std::vector<uint16_t> heapBuffer;
uint16_t* buffer = stackBuffer;
if (length > kStackUnits) {
heapBuffer.resize((size_t)length);
buffer = heapBuffer.data();
}
CFRange range = CFRangeMake(0, length);
CFIndex usedLength = 0;
if (CFStringGetBytes(str, range, kCFStringEncodingASCII, 0, false,
reinterpret_cast<UInt8*>(buffer), length, &usedLength) == length) {
return v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(buffer),
v8::NewStringType::kNormal, (int)length)
.ToLocalChecked();
}
CFStringGetCharacters(str, range, reinterpret_cast<UniChar*>(buffer));
return v8::String::NewFromTwoByte(isolate, buffer, v8::NewStringType::kNormal, (int)length)
.ToLocalChecked();
}
#endif
// Unwraps a value to the v8::String the text conversions below read from.
// A throwing toString() is swallowed rather than left pending, which is the
// contract v8::String::Utf8Value offered and callers were written against.
inline bool ToStringLocal(v8::Isolate* isolate, const v8::Local<v8::Value>& value,
v8::Local<v8::String>& out) {
if (value.IsEmpty()) {
return false;
}
if (value->IsString()) {
out = value.As<v8::String>();
return true;
}
if (value->IsStringObject()) {
out = value.As<v8::StringObject>()->ValueOf();
return true;
}
v8::TryCatch tc(isolate);
return value->ToString(isolate->GetCurrentContext()).ToLocal(&out);
}
inline std::string ToString(v8::Isolate* isolate, const v8::Local<v8::Value>& value) {
v8::Local<v8::String> str;
if (!ToStringLocal(isolate, value, str)) {
return std::string();
}
{
v8::String::ValueView view(isolate, str);
if (view.is_one_byte()) {
const uint8_t* data = view.data8();
uint32_t length = view.length();
uint32_t i = 0;
while (i < length && data[i] < 0x80) {
i++;
}
// Pure ASCII already is its own UTF-8 encoding, so it can be copied
// straight out. A one-byte string with a high byte is Latin-1 and still
// needs widening, which the encode below handles.
if (i == length) {
return std::string(reinterpret_cast<const char*>(data), length);
}
}
}
size_t length = str->Utf8LengthV2(isolate);
std::string result(length, '\0');
if (length > 0) {
str->WriteUtf8V2(isolate, result.data(), length, v8::String::WriteFlags::kReplaceInvalidUtf8);
}
return result;
}
#ifdef __OBJC__
// Encodes via V8 rather than -UTF8String, which returns nil for a string holding
// a lone surrogate — leaving callers to construct a std::string from nullptr.
// The unpaired half becomes U+FFFD, since it has no UTF-8 spelling.
inline std::string ToString(v8::Isolate* isolate, const NSString* value) {
return tns::ToString(isolate, tns::ToV8String(isolate, value));
}
// The exact UTF-8 bytes of `value`, sized by length so an embedded U+0000 is
// kept (a C-string conversion stops there); nullopt for nil or for a string
// with a lone surrogate, which has no UTF-8 spelling (-UTF8String returns NULL).
inline std::optional<std::string> ToExactUtf8(const NSString* value) {
if (value == nil) {
return std::nullopt;
}
CFStringRef str = (__bridge CFStringRef)value;
const CFRange range = CFRangeMake(0, CFStringGetLength(str));
CFIndex byteCount = 0;
if (CFStringGetBytes(str, range, kCFStringEncodingUTF8, 0, false, nullptr, 0, &byteCount) !=
range.length) {
return std::nullopt;
}
std::string bytes(static_cast<size_t>(byteCount), '\0');
CFStringGetBytes(str, range, kCFStringEncodingUTF8, 0, false,
reinterpret_cast<UInt8*>(bytes.data()), byteCount, nullptr);
return bytes;
}
inline NSString* ToNSString(const std::string& v) {
return [[[NSString alloc] initWithBytes:v.c_str() length:v.length()
encoding:NSUTF8StringEncoding] S_AUTORELEASE];
}
// Reads the V8 string's native UTF-16 buffer directly so lone surrogates and
// embedded NUL survive the bridge; a UTF-8 round-trip loses both.
inline NSString* ToNSString(v8::Isolate* isolate, const v8::Local<v8::Value>& value) {
if (value.IsEmpty()) {
return @"";
}
if (value->IsStringObject()) {
v8::Local<v8::String> obj = value.As<v8::StringObject>()->ValueOf();
return ToNSString(isolate, obj);
}
v8::Local<v8::String> str;
if (!value->ToString(isolate->GetCurrentContext()).ToLocal(&str)) {
return @"";
}
v8::String::ValueView result(isolate, str);
if (result.is_one_byte()) {
// A one-byte V8 string is Latin-1, not UTF-8.
return [[[NSString alloc] initWithBytes:result.data8()
length:result.length()
encoding:NSISOLatin1StringEncoding] S_AUTORELEASE];
}
return [NSString stringWithCharacters:(const unichar*)result.data16() length:result.length()];
}
#endif
std::u16string ToUtf16String(v8::Isolate* isolate, const v8::Local<v8::Value>& value);
inline double ToNumber(v8::Isolate* isolate, const v8::Local<v8::Value>& value) {
double result = NAN;
if (value.IsEmpty()) {
return result;
}
if (value->IsNumberObject()) {
result = value.As<v8::NumberObject>()->ValueOf();
} else if (value->IsNumber()) {
result = value.As<v8::Number>()->Value();
} else {
v8::Local<v8::Number> number;
v8::Local<v8::Context> context = isolate->GetCurrentContext();
bool success = value->ToNumber(context).ToLocal(&number);
if (success) {
result = number->Value();
}
}
return result;
}
inline bool ToBool(const v8::Local<v8::Value>& value) {
bool result = false;
if (value.IsEmpty()) {
return result;
}
if (value->IsBooleanObject()) {
result = value.As<v8::BooleanObject>()->ValueOf();
} else if (value->IsBoolean()) {
result = value.As<v8::Boolean>()->Value();
}
return result;
}
bool Exists(const char* fullPath);
std::string ReadText(const std::string& file);
void SetPrivateValue(const v8::Local<v8::Object>& obj, const v8::Local<v8::String>& propName,
const v8::Local<v8::Value>& value);
v8::Local<v8::Value> GetPrivateValue(const v8::Local<v8::Object>& obj,
const v8::Local<v8::String>& propName);
// Follows a Proxy chain to its innermost target; empty when any link is
// revoked. Non-proxies come back unchanged.
inline v8::Local<v8::Value> UnwrapProxy(v8::Local<v8::Value> value) {
while (!value.IsEmpty() && value->IsProxy()) {
v8::Local<v8::Proxy> proxy = value.As<v8::Proxy>();
if (proxy->IsRevoked()) {
return v8::Local<v8::Value>();
}
value = proxy->GetTarget();
}
return value;
}
// UnwrapProxy for values crossing into native code: a revoked proxy throws a
// NativeScriptException carrying a TypeError.
v8::Local<v8::Value> UnwrapProxyOrThrow(v8::Isolate* isolate, v8::Local<v8::Value> value);
// The value native code should read properties and elements from, given the
// original value and its unwrapped target. A Proxy over an ordinary object or
// Array is read through its traps, so native code sees what JS sees. Any other
// target is read directly: native wrappers keep their state on the target, and
// objects with internal slots (Map, Set, buffers, Date, RegExp, boxed
// primitives, functions) reject a Proxy receiver in their own methods.
v8::Local<v8::Value> ProxyReadSource(v8::Local<v8::Value> original, v8::Local<v8::Value> target);
// The object's creation context, or the isolate's current (else main) context
// for objects that have none, such as proxies.
v8::Local<v8::Context> GetCreationContextOrCurrent(v8::Isolate* isolate,
const v8::Local<v8::Object>& obj);
// Set/Get/DeleteValue all resolve through proxies: wrapper state is keyed by
// the Proxy target, so a proxied wrapper yields its target's wrapper.
// GetValue alone also follows a `this.super` alias to its receiver
// (SuperAliasReceiver), so code that writes back to an object it read with
// GetValue must first resolve an alias, or it overwrites the alias's receiver
// field instead of the wrapper it read.
void SetValue(v8::Isolate* isolate, const v8::Local<v8::Object>& obj, BaseDataWrapper* value);
BaseDataWrapper* GetValue(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
// A tagged pointer carries its value in the pointer itself: it is never
// retained, released or deallocated, and its retain count means nothing. Only
// x86_64 macOS and Mac Catalyst tag the low bit; every iOS target, the x86_64
// simulator included, tags the high bit.
inline bool IsTaggedPointer(id obj) {
// Through void*: clang rejects bit tests on ObjC object pointers.
uintptr_t bits = reinterpret_cast<uintptr_t>(static_cast<const void*>(obj));
#if defined(__x86_64__) && (TARGET_OS_OSX || TARGET_OS_MACCATALYST)
return (bits & 1) != 0;
#else
return (bits >> 63) != 0;
#endif
}
// The receiver a `this.super` alias (ClassBuilder::SuperAccessorGetterCallback)
// stands for, or empty when obj is not one. An alias keeps its receiver in
// internal field 0 and the string "super" in internal field 1; it owns no
// wrapper, so GetValue reads the receiver's at every use.
v8::Local<v8::Object> SuperAliasReceiver(const v8::Local<v8::Object>& obj);
// What happens when JS touches a wrapper whose native counterpart has already
// been released (its internal field was neutered by DisposeValue) — a state a
// resurrected object can expose by outliving a referenced object's native
// half; see docs/knowledge/v8-resurrecting-finalizers.md. Process-wide,
// configured via the `releasedObjectPolicy` key of ns:runtime's setConfig.
enum class ReleasedObjectPolicy {
// No-op the operation and fire the `releasednativeaccess` global event
// (console.warn additionally in debug). The default.
kReport = 0,
// Throw a catchable JS ReferenceError at the touch site.
kThrow = 1,
};
ReleasedObjectPolicy GetReleasedObjectPolicy();
void SetReleasedObjectPolicy(ReleasedObjectPolicy policy);
// Like GetValue, but applies ReleasedObjectPolicy when the object carries no
// wrapper: throws (kThrow) or schedules a `releasednativeaccess` event
// (kReport, deduplicated per object), returning nullptr either way.
// `operation` names the API surface for the event payload / error message.
// Callers must no-op on nullptr; paths that would otherwise read the internal
// field unchecked must go through this.
BaseDataWrapper* GetValueOrReport(v8::Isolate* isolate, const v8::Local<v8::Value>& val,
const char* operation);
// Why an ObjC object's wrapper no longer has its native object. Internal field
// 0, where the External would otherwise sit, holds a per-isolate Symbol for the
// reason: GetValue only reads Externals, so every existing caller sees "no
// wrapper". Reasons are recognised by identity, never by value, because other
// templates keep raw aligned pointers in field 0, which read back as arbitrary
// Smis.
enum class ReleasedReason : int32_t {
kNone = 0,
// The wrapper's finalizer released it while JS could still reach the
// wrapper (only possible through a graph a resurrected wrapper keeps alive).
kCollected = 1,
// __releaseNativeCounterpart.
kExplicit = 2,
// Runtime teardown.
kTeardown = 3,
// A receiver lent to JS while its object ran -dealloc.
kDeallocated = 4,
};
// Creates the isolate's markers, so marking never allocates in a finalizer.
void InitReleasedMarkers(v8::Isolate* isolate);
void MarkReleased(v8::Isolate* isolate, const v8::Local<v8::Object>& obj, ReleasedReason reason);
// Follows Proxies and `this.super` aliases to the wrapper they stand for.
ReleasedReason GetReleasedReason(const v8::Local<v8::Value>& val);
const char* ReleasedReasonMessage(ReleasedReason reason);
// Counts the access and throws the ReferenceError as a NativeScriptException,
// for paths that must not reach native code once the error is raised.
[[noreturn]] void ThrowReleasedObject(v8::Isolate* isolate, ReleasedReason reason,
const std::string& operation);
// Applies ReleasedObjectPolicy to a released ObjC wrapper reaching native code
// in place of its object. Throws a ReferenceError under kThrow when `canThrow`;
// otherwise schedules the `releasednativeaccess` event (deduplicated per
// object). The caller then passes nil (or NSNull where nil is not allowed).
// Returns false when it threw.
bool ReportReleasedObject(v8::Isolate* isolate, const v8::Local<v8::Value>& val,
ReleasedReason reason, const char* operation, bool canThrow);
// Whether the runtime warns when JS state on a wrapper is lost while its native
// object lives on. Process-wide; defaults to the app's debug flag, overridden by
// the "wrapperLifetime": { "warnings": bool } app config or ns:runtime's
// `wrapperLifetimeWarnings` key.
bool WrapperLifetimeWarningsEnabled();
void SetWrapperLifetimeWarnings(bool enabled);
void DeleteValue(v8::Isolate* isolate, const v8::Local<v8::Value>& val);
bool DeleteWrapperIfUnused(v8::Isolate* isolate, const v8::Local<v8::Value>& obj,
BaseDataWrapper* value);
std::vector<v8::Local<v8::Value>> ArgsToVector(const v8::FunctionCallbackInfo<v8::Value>& info);
inline bool IsString(const v8::Local<v8::Value>& value) {
return !value.IsEmpty() && (value->IsString() || value->IsStringObject());
}
inline bool IsNumber(const v8::Local<v8::Value>& value) {
return !value.IsEmpty() && (value->IsNumber() || value->IsNumberObject());
}
inline bool IsBigInt(const v8::Local<v8::Value>& value) {
return !value.IsEmpty() && (value->IsBigInt() || value->IsBigIntObject());
}
inline bool IsBool(const v8::Local<v8::Value>& value) {
return !value.IsEmpty() && (value->IsBoolean() || value->IsBooleanObject());
}
bool IsArrayOrArrayLike(v8::Isolate* isolate, const v8::Local<v8::Value>& value);
void* TryGetBufferFromArrayBuffer(const v8::Local<v8::Value>& value, bool& isArrayBuffer);
void ExecuteOnRunLoop(CFRunLoopRef queue, void (^func)(void), bool async = true);
void ExecuteOnDispatchQueue(dispatch_queue_t queue, std::function<void()> func, bool async = true);
void ExecuteOnMainThread(std::function<void()> func, bool async = true);
void LogError(v8::Isolate* isolate, v8::TryCatch& tc);
void LogBacktrace(int skip = 1);
// Robust logging: prefer os_log when available (supports privacy markers).
// To ensure messages are not redacted by the unified logging system we
// format the final message into a C string and pass it as a single
// "%{public}s" argument to os_log. When os_log is not available we
// fall back to NSLog (Objective-C) or CF/NSLog bridge in pure C++ builds.
// The log format (see LogChunks.h) the CLI asked for, or 0 for plain split lines.
int LogFormat();
// Unique per split message in the process, for the headers of format 1.
uint32_t NextLogMessageId();
bool IsDevNull(int fd);
#if TNS_HAVE_OS_LOG
// Logs the two parts as one entry.
static inline void TNS_WriteOsLogEntry(os_log_t log, os_log_type_t type, std::string_view first,
std::string_view second) {
os_log_with_type(log, type, "%{public}.*s%{public}.*s",
static_cast<int>(first.size()), first.data(), static_cast<int>(second.size()),
second.data());
}
static inline void TNS_WriteToOsLog(std::string_view text, os_log_type_t type = OS_LOG_TYPE_DEFAULT,
std::string_view prefix = "", os_log_t log = OS_LOG_DEFAULT) {
if (prefix.size() + text.size() <= kMaxLogChunkBytes) {
TNS_WriteOsLogEntry(log, type, prefix, text);
} else if (LogFormat() >= 1) {
ForEachFramedLogChunk(prefix, text, NextLogMessageId(),
[&](std::string_view header, std::string_view piece) {
TNS_WriteOsLogEntry(log, type, header, piece);
});
} else {
// Repeated on every piece, so that each stays a complete log line.
ForEachLogChunk(text, kMaxLogChunkBytes - prefix.size(),
[&](std::string_view chunk, LogChunkBreak) {
TNS_WriteOsLogEntry(log, type, prefix, chunk);
});
}
}
#endif
#ifdef __OBJC__
// Overload for Objective-C string literals (NSString*)
static inline void TNS_FormatAndLog(NSString* fmt, ...) {
va_list ap;
va_start(ap, fmt);
// Use NSString's formatting to handle both C and Objective-C format
// specifiers
NSString* formattedString = [[NSString alloc] initWithFormat:fmt arguments:ap];
va_end(ap);
if (!formattedString) {
return;
}
// Convert to C string for logging. The buffer belongs to the string, so it
// must outlive the call below.
const char* cStr = [formattedString UTF8String];
if (cStr) {
#if TNS_HAVE_OS_LOG
TNS_WriteToOsLog(cStr);
#else
NSLog(@"%s", cStr);
#endif
}
[formattedString S_RELEASE];
}
#endif
// Main implementation for C string literals
static inline void TNS_FormatAndLog(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
// Fast path: try a reasonably sized stack buffer first to avoid heap
// allocation and a second formatting pass in the common case.
const int STACK_BUF_SIZE = 1024;
char stack_buf[STACK_BUF_SIZE];
va_list ap_copy;
va_copy(ap_copy, ap);
int needed = vsnprintf(stack_buf, STACK_BUF_SIZE, fmt, ap_copy);
va_end(ap_copy);
if (needed < 0) {
va_end(ap);
return;
}
if (needed < STACK_BUF_SIZE) {
// Message fit into stack buffer — single formatting pass.
#if TNS_HAVE_OS_LOG
TNS_WriteToOsLog(stack_buf);
#else
// Fall back to NSLog. Use Objective-C API when compiling as ObjC++.
#ifdef __OBJC__
NSLog(@"%s", stack_buf);
#else
NSLog(CFSTR("%s"), stack_buf);
#endif
#endif
} else {
// Needs heap allocation; format again into the correctly sized buffer.
std::vector<char> buffer((size_t)needed + 1);
vsnprintf(buffer.data(), buffer.size(), fmt, ap);
#if TNS_HAVE_OS_LOG
TNS_WriteToOsLog(buffer.data());
#else
// Fall back to NSLog. Use Objective-C API when compiling as ObjC++.
#ifdef __OBJC__
NSLog(@"%s", buffer.data());
#else
NSLog(CFSTR("%s"), buffer.data());
#endif
#endif
}
va_end(ap);
}
// Keep the existing Log(...) macro name for call-site compatibility.
#define Log(...) tns::TNS_FormatAndLog(__VA_ARGS__)
// ── Category-scoped debug tracing ─────────────────────────────
//
// A process-wide bitmask of enabled categories, tested inline at every call
// site, so a disabled category costs one relaxed load and a well-predicted
// branch. Present in every build: these are traces, and a release build that
// cannot be traced is a release build that cannot be diagnosed. Error and
// lifecycle logs are unconditional and do not belong here.
//
// Turned on by the NS_DEBUG environment variable (read once at process init)
// or by ns:runtime's `debug` config key.
enum class LogCategory : uint8_t {
Esm, // module resolution, compilation, linking, evaluation
Fetch, // the HTTP module transport
Registry, // registry invalidation and dynamic-import cache bookkeeping
kCount
};
// One bit per LogCategory. Written from process init and from main-isolate
// setConfig; read from every thread. Relaxed suffices — a trace line racing a
// toggle changes nothing but that line.
inline std::atomic<uint32_t> g_enabledLogCategories{0};
inline bool LogCategoryEnabled(LogCategory category) {
return (g_enabledLogCategories.load(std::memory_order_relaxed) &
(1u << static_cast<uint8_t>(category))) != 0;
}
// Writes one trace line under `category`, prefixed with the category name.
// Out of line so nothing but the enabled test lands at the call site.
void EmitDebugLog(LogCategory category, const char* format, ...)
__attribute__((format(printf, 2, 3)));
const char* LogCategoryName(LogCategory category);
// Every category name, comma separated — for the "valid categories are …"
// diagnostic.
std::string AllLogCategoryNames();
// A comma-separated category list to a mask. Unknown names are skipped and
// reported through `hadUnknown` rather than failing the whole list.
uint32_t ParseLogCategories(const std::string& list, bool* hadUnknown);
// The canonical comma-separated list of the categories currently enabled.
std::string EnabledLogCategoryNames();
void SetEnabledLogCategories(uint32_t mask);
// Applies NS_DEBUG. Call once, before anything worth tracing runs.
void InitializeLogCategoriesFromEnvironment();
// A MACRO rather than a function or template on purpose: the arguments must
// not be evaluated unless the category is on, and call sites routinely build
// strings that cost far more than the line they would print.
#define TNS_DEBUG(category, ...) \
do { \
if (tns::LogCategoryEnabled(tns::LogCategory::category)) [[unlikely]] { \
tns::EmitDebugLog(tns::LogCategory::category, __VA_ARGS__); \
} \
} while (0)
// Short identification for objects backed by a native wrapper (ObjC class
// name etc.); empty when the value is a plain JS object. Never runs JS.
std::string GetNativeWrapperHint(v8::Isolate* isolate, const v8::Local<v8::Value>& value);
std::string ReplaceAll(const std::string source, std::string find, std::string replacement);
const std::string BuildStacktraceFrameLocationPart(v8::Isolate* isolate,
v8::Local<v8::StackFrame> frame);
const std::string BuildStacktraceFrameMessage(v8::Isolate* isolate,
v8::Local<v8::StackFrame> frame);
const std::string GetStackTrace(v8::Isolate* isolate);
const std::string GetCurrentScriptUrl(v8::Isolate* isolate);
// Returns stack trace string remapped to original sources using global __ns_remapStack if present.
std::string RemapStackTraceIfAvailable(v8::Isolate* isolate, const std::string& stackTrace);
// Smart stack extraction that prefers:
// 1) exception.stack if provided
// 2) TryCatch.StackTrace / Message()->GetStackTrace when TryCatch provided
// 3) Current stack via GetStackTrace
std::string GetSmartStackTrace(v8::Isolate* isolate, v8::TryCatch* tryCatch = nullptr,
v8::Local<v8::Value> exception = v8::Local<v8::Value>());
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(), 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) {
return v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(data),
v8::NewStringType::kNormal, length)
.ToLocalChecked();
}
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const signed char* data,
int length) {
return v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(data),
v8::NewStringType::kNormal, length)
.ToLocalChecked();
}
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const unsigned char* data,
int length) {
return v8::String::NewFromOneByte(isolate, data, v8::NewStringType::kNormal, length)
.ToLocalChecked();
}
// Convenience wrapper around v8::String::NewFromOneByte().
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const char* data, int length = -1);
// For the people that compile with -funsigned-char.
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const signed char* data,
int length = -1);
inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const unsigned char* data,
int length = -1);
v8::Local<v8::FunctionTemplate> NewFunctionTemplate(
v8::Isolate* isolate, v8::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>(),
v8::Local<v8::Signature> signature = v8::Local<v8::Signature>(),
v8::ConstructorBehavior behavior = v8::ConstructorBehavior::kAllow,
v8::SideEffectType side_effect = v8::SideEffectType::kHasSideEffect,
const v8::CFunction* c_function = nullptr);
// Convenience methods for NewFunctionTemplate().
void SetMethod(v8::Local<v8::Context> context, v8::Local<v8::Object> that, const char* name,
v8::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>());
// Similar to SetProtoMethod but without receiver signature checks.
void SetMethod(v8::Isolate* isolate, v8::Local<v8::Template> that, const char* name,
v8::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>());
// Whether the runtime registers v8::CFunction fast-call overloads next to the
// slow callbacks. A registered overload is inert wherever the optimizing tiers
// are absent — iOS ships V8 in lite mode, which implies jitless, so every call
// there goes through the slow callback — and only fires on JIT-enabled embeds.
#ifndef NATIVESCRIPT_ENABLE_FAST_API
#define NATIVESCRIPT_ENABLE_FAST_API 1
#endif
void SetFastMethod(v8::Isolate* isolate, v8::Local<v8::Template> that, const char* name,
v8::FunctionCallback slow_callback, const v8::CFunction* c_function,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
void SetFastMethod(v8::Local<v8::Context> context, v8::Local<v8::Object> that, const char* name,
v8::FunctionCallback slow_callback, const v8::CFunction* c_function,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
void SetFastMethodNoSideEffect(v8::Isolate* isolate, v8::Local<v8::Template> that, const char* name,
v8::FunctionCallback slow_callback, const v8::CFunction* c_function,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
void SetFastMethodNoSideEffect(v8::Local<v8::Context> context, v8::Local<v8::Object> that,
const char* name, v8::FunctionCallback slow_callback,
const v8::CFunction* c_function,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
void SetProtoMethod(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> that, const char* name,
v8::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
void SetInstanceMethod(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> that, const char* name,
v8::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
// Safe variants denote the function has no side effects.
void SetMethodNoSideEffect(v8::Local<v8::Context> context, v8::Local<v8::Object> that,
const char* name, v8::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
void SetProtoMethodNoSideEffect(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> that,
const char* name, v8::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
void SetMethodNoSideEffect(v8::Isolate* isolate, v8::Local<v8::Template> that, const char* name,
v8::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
enum class SetConstructorFunctionFlag {
NONE,
SET_CLASS_NAME,
};
void SetConstructorFunction(
v8::Local<v8::Context> context, v8::Local<v8::Object> that, const char* name,
v8::Local<v8::FunctionTemplate> tmpl,
SetConstructorFunctionFlag flag = SetConstructorFunctionFlag::SET_CLASS_NAME);
void SetConstructorFunction(
v8::Local<v8::Context> context, v8::Local<v8::Object> that, v8::Local<v8::String> name,
v8::Local<v8::FunctionTemplate> tmpl,
SetConstructorFunctionFlag flag = SetConstructorFunctionFlag::SET_CLASS_NAME);
void SetConstructorFunction(
v8::Isolate* isolate, v8::Local<v8::Template> that, const char* name,
v8::Local<v8::FunctionTemplate> tmpl,
SetConstructorFunctionFlag flag = SetConstructorFunctionFlag::SET_CLASS_NAME);
void SetConstructorFunction(
v8::Isolate* isolate, v8::Local<v8::Template> that, v8::Local<v8::String> name,
v8::Local<v8::FunctionTemplate> tmpl,
SetConstructorFunctionFlag flag = SetConstructorFunctionFlag::SET_CLASS_NAME);
template <int N>
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(v8::Isolate* isolate, const char (&data)[N]) {
return OneByteString(isolate, data, N - 1);
}
template <std::size_t N>
inline v8::Local<v8::String> FIXED_ONE_BYTE_STRING(v8::Isolate* isolate,
const std::array<char, N>& arr) {
return OneByteString(isolate, arr.data(), N - 1);
}
class PersistentToLocal {
public:
// If persistent.IsWeak() == false, then do not call persistent.Reset()
// while the returned Local<T> is still in scope, it will destroy the
// reference to the object.
template <class TypeName>
static inline v8::Local<TypeName> Default(v8::Isolate* isolate,
const v8::PersistentBase<TypeName>& persistent) {
if (persistent.IsWeak()) {
return PersistentToLocal::Weak(isolate, persistent);
} else {
return PersistentToLocal::Strong(persistent);
}
}
// Unchecked conversion from a non-weak Persistent<T> to Local<T>,
// use with care!
//
// Do not call persistent.Reset() while the returned Local<T> is still in
// scope, it will destroy the reference to the object.
template <class TypeName>
static inline v8::Local<TypeName> Strong(const v8::PersistentBase<TypeName>& persistent) {
// DCHECK(!persistent.IsWeak());
return *reinterpret_cast<v8::Local<TypeName>*>(
const_cast<v8::PersistentBase<TypeName>*>(&persistent));
}
template <class TypeName>
static inline v8::Local<TypeName> Weak(v8::Isolate* isolate,
const v8::PersistentBase<TypeName>& persistent) {
return v8::Local<TypeName>::New(isolate, persistent);
}
};
} // namespace tns
#endif /* Helpers_h */