-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathBacktraceUnityBridge.mm
More file actions
1021 lines (934 loc) · 41.6 KB
/
Copy pathBacktraceUnityBridge.mm
File metadata and controls
1021 lines (934 loc) · 41.6 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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Stable C ABI used by the Backtrace Unity macOS native client.
#import <AppKit/AppKit.h>
#import <CommonCrypto/CommonDigest.h>
#import <CoreData/CoreData.h>
#import <Foundation/Foundation.h>
#ifndef PLCRASHREPORTER_PREFIX
#define PLCRASHREPORTER_PREFIX BTUnity
#endif
#if __has_include(<BTUnityCrashReporter/BTUnityCrashReporter.h>)
#import <BTUnityCrashReporter/BTUnityCrashReporter.h>
#elif __has_include("BTUnityCrashReporter.h")
#import "BTUnityCrashReporter.h"
#else
#error "The Unity bundle target requires the private BTUnityCrashReporter module"
#endif
#if __has_include(<Backtrace/Backtrace-Swift.h>)
#import <Backtrace/Backtrace-Swift.h>
#else
#import "Backtrace-Swift.h"
#endif
// `shutdownForNativeBridge` is an Objective-C runtime entry point intentionally kept out of Backtrace Cocoa's public Swift API.
// Release generated headers omit internal Swift declarations,
// the private Unity bridge declares the selector it alone is allowed to call.
@interface BacktraceClient (BacktraceUnityBridgeLifecycle)
- (void)shutdownForNativeBridge;
@end
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sysctl.h>
#define BT_EXPORT extern "C" __attribute__((visibility("default")))
typedef struct {
const char *Key;
const char *Value;
} Entry;
typedef NS_ENUM(int32_t, BTUnityInitializationResult) {
BTUnityInitializationResultSuccess = 0,
BTUnityInitializationResultAlreadyInitializedActive = 1,
BTUnityInitializationResultInvalidArguments = 2,
BTUnityInitializationResultStorageInitializationFailed = 3,
BTUnityInitializationResultInvalidSubmissionUrl = 4,
BTUnityInitializationResultClientInitializationFailed = 5,
BTUnityInitializationResultUnexpectedFailure = 6,
BTUnityInitializationResultProcessLifetimeDisabled = 7,
};
@interface BTUnityRuntimeState : NSObject
@property(nonatomic, strong, readonly) BacktraceClient *client;
@property(nonatomic, strong, readonly) BacktraceCrashReporter *crashReporter;
- (instancetype)initWithClient:(BacktraceClient *)client
crashReporter:(BacktraceCrashReporter *)crashReporter;
@end
@implementation BTUnityRuntimeState
- (instancetype)initWithClient:(BacktraceClient *)client
crashReporter:(BacktraceCrashReporter *)crashReporter {
self = [super init];
if (self != nil) {
_client = client;
_crashReporter = crashReporter;
}
return self;
}
@end
// PLCrashReporter does not provide an API to uninstall its process-wide fatal handler.
// Keep the client, reporter, and callback context alive until process exit even after managed code calls Disable().
// A later Start must remain already-initialized rather than installing a second reporter over process-global state.
static BTUnityRuntimeState *BTUnityRuntime = nil;
static NSMutableArray<BacktraceCrashReporter *> *BTUnityCrashReporterOwners = nil;
static BacktraceLogLevel BTUnityConfiguredLogLevel = BacktraceLogLevelWarning;
static BOOL BTUnityManagedInterfaceEnabled = NO;
static BOOL BTUnityHandlerInstallationAttempted = NO;
// Keep this literal in the final binary. The artifact validator uses it as a storage-contract marker,
// all compatibility entry points derive their PLCrashReporter base path from the same versioned relative path.
static NSString *const BTUnityCrashStorageRelativePath = @"Backtrace/NativeCrash/v1/plcrash";
static NSString *const BTUnityLegacyIdentifierPrefix = @"io.backtrace.unity.legacy.";
static NSString *const BTUnityStorageErrorDomain = @"io.backtrace.unity.macos.storage";
static NSString *const BTPLCrashReporterDefaultNamespace =
@"com.plausiblelabs.crashreporter.data";
static NSString *const BTUnityExceptionContractMarker =
@"BacktraceUnityExceptionContract:all-c-exports-contained-v1";
static const char BTUnityLifecycleContractMarker[] __attribute__((used, retain)) =
"BacktraceUnityLifecycleContract:process-lifetime-handler-distinct-disabled-v2";
static const char BTUnityLoggingContractMarker[] __attribute__((used, retain)) =
"BacktraceUnityLoggingContract:warning-default-explicit-setter-silent-none-redacted-v3";
static BOOL BTShouldLog(BacktraceLogLevel messageLevel) {
@synchronized([BacktraceClient class]) {
return BTUnityConfiguredLogLevel != BacktraceLogLevelNone &&
BTUnityConfiguredLogLevel <= messageLevel;
}
}
static NSString *BTReplaceBridgeLogMatches(NSString *value,
NSString *pattern,
NSString *replacement) {
NSError *expressionError = nil;
NSRegularExpression *expression =
[NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive |
NSRegularExpressionAnchorsMatchLines
error:&expressionError];
if (expression == nil || expressionError != nil) {
return nil;
}
return [expression stringByReplacingMatchesInString:value
options:0
range:NSMakeRange(0, value.length)
withTemplate:replacement];
}
// Bridge diagnostics are copied into Unity player logs, so treat every URL, filesystem path, and credential-shaped suffix as sensitive.
// A match consumes the rest of its line instead of attempting to preserve a possibly encoded token or a path containing spaces.
static NSString *BTSanitizeBridgeLogText(NSString *message) {
@try {
NSString *sanitized = message ?: @"";
NSArray<NSArray<NSString *> *> *rules = @[
@[@"\\b(?:https?|file)://[^\\r\\n]*", @"<redacted-url>"],
@[@"(^|[\\s(\\[{:;=\\\"'“])~?/[^\\r\\n]*", @"$1<redacted-path>"],
@[@"\\b(?:token|api[_-]?key|authorization|password|secret)\\s*[:=][^\\r\\n]*",
@"<redacted-credential>"],
];
for (NSArray<NSString *> *rule in rules) {
sanitized = BTReplaceBridgeLogMatches(sanitized, rule[0], rule[1]);
if (sanitized == nil) {
return @"<redacted-diagnostic>";
}
}
return sanitized;
} @catch (__unused NSException *exception) {
return @"<redacted-diagnostic>";
}
}
// NSError descriptions and exception reasons are owned by Foundation or another caller and can contain arbitrary values.
// Preserve their stable category separately and never copy the uncontrolled detail into a player log.
static NSString *BTSanitizedExternalDetail(NSString *detail) {
return detail.length > 0 ? @"<redacted-detail>" : @"";
}
static void BTLogBridgeMessage(BacktraceLogLevel level, NSString *message) {
if (!BTShouldLog(level)) {
return;
}
@try {
NSLog(@"[Backtrace] %@", BTSanitizeBridgeLogText(message));
} @catch (__unused NSException *exception) {
if (BTShouldLog(level)) {
fprintf(stderr, "[Backtrace] <redacted-diagnostic>\n");
}
}
}
static void BTLogCaughtException(const char *operation, NSException *exception) {
if (!BTShouldLog(BacktraceLogLevelError)) {
return;
}
@try {
NSString *exceptionName = BTSanitizeBridgeLogText(exception.name ?: @"NSException");
NSString *exceptionReason = BTSanitizedExternalDetail(exception.reason);
BTLogBridgeMessage(
BacktraceLogLevelError,
[NSString stringWithFormat:@"%@ caught an exception in %s: %@ %@",
BTUnityExceptionContractMarker,
operation,
exceptionName,
exceptionReason]);
} @catch (NSException *loggingException) {
(void)loggingException;
if (BTShouldLog(BacktraceLogLevelError)) {
fprintf(stderr, "[Backtrace] native bridge caught an exception in %s\n", operation);
}
}
}
static NSString *BTString(const char *value) {
if (value == NULL) {
return @"";
}
NSString *result = [NSString stringWithUTF8String:value];
return result ?: @"";
}
static char *BTDuplicateString(NSString *value) {
const char *source = (value ?: @"").UTF8String;
if (source == NULL) {
source = "";
}
const size_t size = strlen(source) + 1;
char *copy = static_cast<char *>(malloc(size));
if (copy != NULL) {
memcpy(copy, source, size);
}
return copy;
}
static BOOL BTDebuggerAttached(void) {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
struct kinfo_proc info;
memset(&info, 0, sizeof(info));
size_t size = sizeof(info);
if (sysctl(mib, 4, &info, &size, NULL, 0) == -1) {
return NO;
}
return (info.kp_proc.p_flag & P_TRACED) != 0;
}
static BOOL BTValidSubmissionUrl(NSString *rawUrl, NSURL **urlOut) {
if (rawUrl.length == 0) {
return NO;
}
NSURLComponents *components = [NSURLComponents componentsWithString:rawUrl];
NSString *scheme = components.scheme.lowercaseString;
if (!([scheme isEqualToString:@"https"] || [scheme isEqualToString:@"http"]) ||
components.host.length == 0) {
return NO;
}
NSURL *url = components.URL;
if (url == nil) {
return NO;
}
if (urlOut != NULL) {
*urlOut = url;
}
return YES;
}
static NSError *BTStorageError(NSInteger code, NSString *description) {
return [NSError errorWithDomain:BTUnityStorageErrorDomain
code:code
userInfo:@{NSLocalizedDescriptionKey: description}];
}
static NSString *BTInitializationErrorDetail(NSString *summary, NSError *error) {
if (error == nil) {
return summary;
}
return [NSString stringWithFormat:@"%@ (%@:%ld %@)",
summary,
BTSanitizeBridgeLogText(error.domain),
(long)error.code,
BTSanitizedExternalDetail(error.localizedDescription)];
}
static BOOL BTValidBundleIdentifier(NSString *value) {
if (value.length == 0 || value.length > 255) {
return NO;
}
NSCharacterSet *asciiAlphanumeric = [NSCharacterSet characterSetWithCharactersInString:
@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"];
for (NSString *component in [value componentsSeparatedByString:@"."]) {
if (component.length == 0 ||
![asciiAlphanumeric characterIsMember:[component characterAtIndex:0]] ||
![asciiAlphanumeric characterIsMember:[component characterAtIndex:component.length - 1]]) {
return NO;
}
for (NSUInteger index = 1; index + 1 < component.length; ++index) {
const unichar character = [component characterAtIndex:index];
if (character != '-' && ![asciiAlphanumeric characterIsMember:character]) {
return NO;
}
}
}
return YES;
}
static NSString *BTSHA256Hex(NSString *value) {
NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
if (data == nil) {
return nil;
}
unsigned char digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.bytes, (CC_LONG)data.length, digest);
NSMutableString *hex = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
for (NSUInteger index = 0; index < CC_SHA256_DIGEST_LENGTH; ++index) {
[hex appendFormat:@"%02x", digest[index]];
}
return hex;
}
static NSString *BTLegacyStorageIdentifier(NSError **errorOut) {
NSString *bundleIdentifier = NSBundle.mainBundle.bundleIdentifier;
if (BTValidBundleIdentifier(bundleIdentifier)) {
return bundleIdentifier;
}
NSURL *identityURL = NSBundle.mainBundle.bundleURL;
if (!identityURL.isFileURL || identityURL.path.length == 0) {
identityURL = NSBundle.mainBundle.executableURL;
}
NSString *identityPath = identityURL.isFileURL
? identityURL.URLByResolvingSymlinksInPath.URLByStandardizingPath.path
: nil;
NSString *digest = identityPath.length == 0 ? nil : BTSHA256Hex(identityPath);
if (digest.length == 0) {
if (errorOut != NULL) {
*errorOut = BTStorageError(
1,
@"The application has no valid bundle identifier or stable executable path.");
}
return nil;
}
NSString *fallback = [BTUnityLegacyIdentifierPrefix stringByAppendingString:digest];
if (!BTValidBundleIdentifier(fallback)) {
if (errorOut != NULL) {
*errorOut = BTStorageError(2, @"Unable to derive a safe application storage identifier.");
}
return nil;
}
BTLogBridgeMessage(
BacktraceLogLevelWarning,
@"native crash storage is using a per-application fallback identifier because the main bundle identifier is missing or invalid.");
return fallback;
}
static NSString *BTLegacyCrashReportBasePath(NSError **errorOut) {
NSString *identifier = BTLegacyStorageIdentifier(errorOut);
if (identifier == nil) {
return nil;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *cachesURL = [fileManager URLForDirectory:NSCachesDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES
error:errorOut];
if (cachesURL == nil || !cachesURL.isFileURL) {
if (cachesURL != nil && errorOut != NULL) {
*errorOut = BTStorageError(3, @"The user caches directory is not a file URL.");
}
return nil;
}
NSURL *baseURL = [cachesURL URLByAppendingPathComponent:identifier isDirectory:YES];
baseURL = [baseURL URLByAppendingPathComponent:BTUnityCrashStorageRelativePath
isDirectory:YES];
return baseURL.URLByStandardizingPath.path;
}
static NSString *BTPrepareCrashReportBasePath(NSString *rawPath, NSError **errorOut) {
NSString *path = [rawPath stringByExpandingTildeInPath].stringByStandardizingPath;
if (path.length == 0 || !path.isAbsolutePath) {
if (errorOut != NULL) {
*errorOut = BTStorageError(4, @"The PLCrashReporter base path must be absolute.");
}
return nil;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
if ([fileManager fileExistsAtPath:path isDirectory:&isDirectory]) {
if (!isDirectory) {
if (errorOut != NULL) {
*errorOut = BTStorageError(5, @"The PLCrashReporter base path is not a directory.");
}
return nil;
}
} else if (![fileManager createDirectoryAtPath:path
withIntermediateDirectories:YES
attributes:nil
error:errorOut]) {
return nil;
}
// Compare canonical paths only after the requested directory exists so every
// path component, including a caller-supplied alias, can be resolved.
NSURL *resolvedURL = [NSURL fileURLWithPath:path isDirectory:YES]
.URLByResolvingSymlinksInPath.URLByStandardizingPath;
NSString *resolvedPath = resolvedURL.path;
if (resolvedPath.length == 0 || !resolvedPath.isAbsolutePath) {
if (errorOut != NULL) {
*errorOut = BTStorageError(6, @"The PLCrashReporter base path could not be resolved.");
}
return nil;
}
NSError *cachesError = nil;
NSURL *cachesURL = [fileManager URLForDirectory:NSCachesDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES
error:&cachesError];
NSString *defaultBasePath = cachesURL.isFileURL
? cachesURL.URLByResolvingSymlinksInPath.URLByStandardizingPath.path
: nil;
if (defaultBasePath.length == 0) {
if (errorOut != NULL) {
*errorOut = BTStorageError(
7,
@"PLCrashReporter's default cache namespace could not be resolved.");
}
return nil;
}
// A nil PLCrashReporter basePath resolves to NSCachesDirectory,
// and then to <basePath>/com.plausiblelabs.crashreporter.data/<application>.
// Passing that same base directory explicitly would recreate Unity's shared namespace.
if ([resolvedPath isEqualToString:defaultBasePath]) {
if (errorOut != NULL) {
*errorOut = BTStorageError(
8,
[NSString stringWithFormat:
@"The PLCrashReporter base path must not use its default %@ namespace.",
BTPLCrashReporterDefaultNamespace]);
}
return nil;
}
if (![fileManager isWritableFileAtPath:resolvedPath]) {
if (errorOut != NULL) {
*errorOut = BTStorageError(9, @"The PLCrashReporter base path is not writable.");
}
return nil;
}
return resolvedPath;
}
static const char *BTInitializationResultName(BTUnityInitializationResult result) {
switch (result) {
case BTUnityInitializationResultSuccess:
return "success";
case BTUnityInitializationResultAlreadyInitializedActive:
return "alreadyInitializedActive";
case BTUnityInitializationResultInvalidArguments:
return "invalidArguments";
case BTUnityInitializationResultStorageInitializationFailed:
return "storageInitializationFailed";
case BTUnityInitializationResultInvalidSubmissionUrl:
return "invalidSubmissionUrl";
case BTUnityInitializationResultClientInitializationFailed:
return "clientInitializationFailed";
case BTUnityInitializationResultUnexpectedFailure:
return "unexpectedFailure";
case BTUnityInitializationResultProcessLifetimeDisabled:
return "processLifetimeDisabled";
}
return "unknown";
}
static void BTLogInitializationResult(BTUnityInitializationResult result, NSString *detail) {
const BacktraceLogLevel level = result == BTUnityInitializationResultSuccess
? BacktraceLogLevelInfo
: (result == BTUnityInitializationResultAlreadyInitializedActive ||
result == BTUnityInitializationResultProcessLifetimeDisabled
? BacktraceLogLevelWarning
: BacktraceLogLevelError);
NSString *message = nil;
if (detail.length > 0) {
message = [NSString stringWithFormat:@"native initialization %s: %@",
BTInitializationResultName(result), detail];
} else {
message = [NSString stringWithFormat:@"native initialization %s",
BTInitializationResultName(result)];
}
BTLogBridgeMessage(level, message);
}
static BOOL BTValidLogLevel(int32_t rawLevel) {
return rawLevel >= BacktraceLogLevelDebug && rawLevel <= BacktraceLogLevelNone;
}
static NSSet<BacktraceBaseDestination *> *BTLoggingDestinations(BacktraceLogLevel level) {
if (level == BacktraceLogLevelNone) {
return [NSSet set];
}
BacktraceConsoleDestination *console =
[[BacktraceConsoleDestination alloc] initWithLevel:level];
return [NSSet setWithObject:console];
}
static void BTApplyConfiguredLogging(BacktraceClientConfiguration *configuration) {
(void)BTUnityLoggingContractMarker;
configuration.loggingDestinations = BTLoggingDestinations(BTUnityConfiguredLogLevel);
}
static BacktraceClient *BTActiveUnityClient(void) {
@synchronized([BacktraceClient class]) {
return BTUnityManagedInterfaceEnabled ? BTUnityRuntime.client : nil;
}
}
static void BTRecordHandlerInstallationState(BacktraceCrashReporter *crashReporter) {
if (crashReporter == nil) {
return;
}
if (crashReporter.handlerInstallationAttempted) {
BTUnityHandlerInstallationAttempted = YES;
return;
}
// Initialization failed before PLCrashReporter enable was entered,
// there is no process-wide callback to retain and a later Start may safely retry.
[BTUnityCrashReporterOwners removeObjectIdenticalTo:crashReporter];
}
static NSMutableDictionary<NSString *, NSString *> *BTBuildAttributes(
const char *attributeKeys[],
const char *attributeValues[],
int32_t attributeCount) {
NSMutableDictionary<NSString *, NSString *> *attributes =
[NSMutableDictionary dictionaryWithCapacity:static_cast<NSUInteger>(attributeCount)];
for (int32_t index = 0; index < attributeCount; ++index) {
const char *rawKey = attributeKeys[index];
if (rawKey == NULL) {
continue;
}
NSString *key = BTString(rawKey);
if (key.length == 0) {
continue;
}
attributes[key] = BTString(attributeValues[index]);
}
return attributes;
}
static NSMutableArray<NSURL *> *BTBuildAttachments(
const char *attachments[],
int32_t attachmentCount) {
NSMutableArray<NSURL *> *urls =
[NSMutableArray arrayWithCapacity:static_cast<NSUInteger>(attachmentCount)];
for (int32_t index = 0; index < attachmentCount; ++index) {
const char *rawPath = attachments[index];
if (rawPath == NULL || rawPath[0] == '\0') {
continue;
}
[urls addObject:[NSURL fileURLWithPath:BTString(rawPath)]];
}
return urls;
}
static BOOL BTValidArrayArguments(const char *attributeKeys[],
const char *attributeValues[],
int32_t attributeCount,
const char *attachments[],
int32_t attachmentCount) {
if (attributeCount < 0 || attachmentCount < 0) {
return NO;
}
if (attributeCount > 0 && (attributeKeys == NULL || attributeValues == NULL)) {
return NO;
}
if (attachmentCount > 0 && attachments == NULL) {
return NO;
}
return YES;
}
static BTUnityInitializationResult BTStartIntegration(
const char *submissionUrl,
const char *attributeKeys[],
const char *attributeValues[],
int32_t attributeCount,
bool enableOom,
const char *attachments[],
int32_t attachmentCount,
bool enableClientSideUnwinding,
int32_t reportsPerMinute,
NSString *crashReportBasePath,
bool preserveLegacyAlreadyInitializedResult) {
@try {
@autoreleasepool {
@synchronized([BacktraceClient class]) {
(void)BTUnityLifecycleContractMarker;
if (BTUnityRuntime != nil) {
if (BTUnityManagedInterfaceEnabled) {
BTLogInitializationResult(
BTUnityInitializationResultAlreadyInitializedActive,
@"The existing native integration remains operational.");
return BTUnityInitializationResultAlreadyInitializedActive;
}
BTLogInitializationResult(
BTUnityInitializationResultProcessLifetimeDisabled,
@"Native integration was disabled for this process; restart the process before starting it again.");
return BTUnityInitializationResultProcessLifetimeDisabled;
}
if (BTUnityHandlerInstallationAttempted) {
BTLogInitializationResult(
BTUnityInitializationResultProcessLifetimeDisabled,
@"The process-wide crash handler cannot be safely installed again; restart the process before retrying.");
return BTUnityInitializationResultProcessLifetimeDisabled;
}
if (BacktraceClient.shared != nil) {
const BTUnityInitializationResult sharedClientResult =
preserveLegacyAlreadyInitializedResult
? BTUnityInitializationResultAlreadyInitializedActive
: BTUnityInitializationResultClientInitializationFailed;
BTLogInitializationResult(
sharedClientResult,
@"Another Backtrace client already owns the process-wide shared client state.");
return sharedClientResult;
}
if (submissionUrl == NULL || reportsPerMinute < 0 ||
!BTValidArrayArguments(attributeKeys,
attributeValues,
attributeCount,
attachments,
attachmentCount) ||
crashReportBasePath.length == 0) {
BTLogInitializationResult(BTUnityInitializationResultInvalidArguments,
@"One or more native initialization arguments are invalid.");
return BTUnityInitializationResultInvalidArguments;
}
NSURL *url = nil;
if (!BTValidSubmissionUrl(BTString(submissionUrl), &url)) {
BTLogInitializationResult(BTUnityInitializationResultInvalidSubmissionUrl,
@"The submission URL must be an absolute HTTP(S) URL.");
return BTUnityInitializationResultInvalidSubmissionUrl;
}
NSError *storageError = nil;
NSString *reportBasePath = BTPrepareCrashReportBasePath(crashReportBasePath, &storageError);
if (reportBasePath == nil) {
BTLogInitializationResult(
BTUnityInitializationResultStorageInitializationFailed,
BTInitializationErrorDetail(
@"Unable to prepare isolated native crash storage.", storageError));
return BTUnityInitializationResultStorageInitializationFailed;
}
BacktraceCrashReporter *crashReporter = nil;
@try {
const PLCrashReporterSymbolicationStrategy strategy = enableClientSideUnwinding
? PLCrashReporterSymbolicationStrategyAll
: PLCrashReporterSymbolicationStrategyNone;
PLCrashReporterConfig *crashConfig = [[PLCrashReporterConfig alloc]
initWithSignalHandlerType:PLCrashReporterSignalHandlerTypeBSD
symbolicationStrategy:strategy
basePath:reportBasePath];
if (crashConfig == nil) {
BTLogInitializationResult(BTUnityInitializationResultStorageInitializationFailed,
@"PLCrashReporter rejected its configuration.");
return BTUnityInitializationResultStorageInitializationFailed;
}
crashReporter = [[BacktraceCrashReporter alloc] initWithConfig:crashConfig];
if (crashReporter == nil) {
BTLogInitializationResult(BTUnityInitializationResultStorageInitializationFailed,
@"Backtrace could not create the crash reporter wrapper.");
return BTUnityInitializationResultStorageInitializationFailed;
}
// Retain every reporter handed to BacktraceClient before initialization can
// attempt process-wide handler registration. This also keeps a callback owner
// alive if PLCrashReporter partially registers signals and then reports an
// initialization failure.
if (BTUnityCrashReporterOwners == nil) {
BTUnityCrashReporterOwners = [NSMutableArray array];
}
[BTUnityCrashReporterOwners addObject:crashReporter];
BacktraceCredentials *credentials =
[[BacktraceCredentials alloc] initWithSubmissionUrl:url];
BacktraceClientConfiguration *configuration =
[[BacktraceClientConfiguration alloc]
initWithCredentials:credentials
dbSettings:[BacktraceDatabaseSettings new]
reportsPerMin:static_cast<NSInteger>(reportsPerMinute)
allowsAttachingDebugger:NO
oomMode:(enableOom ? BacktraceOomModeFull : BacktraceOomModeNone)];
BTApplyConfiguredLogging(configuration);
NSError *clientError = nil;
BacktraceClient *client = [[BacktraceClient alloc]
initWithConfiguration:configuration
crashReporter:crashReporter
error:&clientError];
BTRecordHandlerInstallationState(crashReporter);
if (client == nil || clientError != nil) {
BTLogInitializationResult(
BTUnityInitializationResultClientInitializationFailed,
BTInitializationErrorDetail(
@"BacktraceClient initialization failed.", clientError));
return BTUnityInitializationResultClientInitializationFailed;
}
client.attributes = BTBuildAttributes(attributeKeys, attributeValues, attributeCount);
client.attachments = BTBuildAttachments(attachments, attachmentCount);
// Publish process-lifetime state only after every fallible initialization step succeeds.
// The runtime must outlive Disable() because PLCrashReporter cannot unregister the fatal handler or its unretained callback context.
BTUnityRuntime = [[BTUnityRuntimeState alloc] initWithClient:client
crashReporter:crashReporter];
BTUnityManagedInterfaceEnabled = YES;
BacktraceClient.shared = client;
BTLogInitializationResult(BTUnityInitializationResultSuccess, nil);
return BTUnityInitializationResultSuccess;
} @catch (NSException *exception) {
BTRecordHandlerInstallationState(crashReporter);
BTLogCaughtException("BTStartIntegration.configuration", exception);
return BTUnityInitializationResultUnexpectedFailure;
}
}
}
} @catch (NSException *exception) {
BTLogCaughtException("BTStartIntegration", exception);
return BTUnityInitializationResultUnexpectedFailure;
}
}
static void BTFreeAttributeEntries(Entry *entries, int32_t size) {
if (entries == NULL) {
return;
}
const int32_t count = size > 0 ? size : 0;
for (int32_t index = 0; index < count; ++index) {
free(const_cast<char *>(entries[index].Key));
free(const_cast<char *>(entries[index].Value));
}
free(entries);
}
BT_EXPORT int32_t BacktraceUnityBridgeVersion(void) {
@try {
return 3;
} @catch (NSException *exception) {
BTLogCaughtException("BacktraceUnityBridgeVersion", exception);
return 0;
}
}
BT_EXPORT int32_t SetBacktraceLogLevel(int32_t rawLevel) {
@try {
@autoreleasepool {
@synchronized([BacktraceClient class]) {
if (!BTValidLogLevel(rawLevel)) {
return BTUnityInitializationResultInvalidArguments;
}
BTUnityConfiguredLogLevel = static_cast<BacktraceLogLevel>(rawLevel);
NSSet<BacktraceBaseDestination *> *destinations =
BTLoggingDestinations(BTUnityConfiguredLogLevel);
[BacktraceLogger setDestinations:destinations];
if (BTUnityRuntime != nil) {
BTUnityRuntime.client.loggingDestinations = destinations;
}
return BTUnityInitializationResultSuccess;
}
}
} @catch (NSException *exception) {
BTLogCaughtException("SetBacktraceLogLevel", exception);
return BTUnityInitializationResultUnexpectedFailure;
}
}
BT_EXPORT int32_t StartBacktraceIntegrationV3(
const char *submissionUrl,
const char *attributeKeys[],
const char *attributeValues[],
int32_t attributeCount,
bool enableOom,
const char *attachments[],
int32_t attachmentCount,
bool enableClientSideUnwinding,
int32_t reportsPerMinute,
const char *crashReportBasePath) {
@try {
@autoreleasepool {
return BTStartIntegration(submissionUrl,
attributeKeys,
attributeValues,
attributeCount,
enableOom,
attachments,
attachmentCount,
enableClientSideUnwinding,
reportsPerMinute,
crashReportBasePath == NULL
? nil
: BTString(crashReportBasePath),
false);
}
} @catch (NSException *exception) {
BTLogCaughtException("StartBacktraceIntegrationV3", exception);
return BTUnityInitializationResultUnexpectedFailure;
}
}
BT_EXPORT int32_t StartBacktraceIntegrationV2(
const char *submissionUrl,
const char *attributeKeys[],
const char *attributeValues[],
int32_t attributeCount,
bool enableOom,
const char *attachments[],
int32_t attachmentCount,
bool enableClientSideUnwinding,
int32_t reportsPerMinute) {
@try {
@autoreleasepool {
NSError *storageError = nil;
NSString *basePath = BTLegacyCrashReportBasePath(&storageError);
if (basePath == nil) {
BTLogInitializationResult(
BTUnityInitializationResultStorageInitializationFailed,
BTInitializationErrorDetail(
@"Unable to derive isolated native crash storage.", storageError));
return BTUnityInitializationResultStorageInitializationFailed;
}
BTUnityInitializationResult result = BTStartIntegration(submissionUrl,
attributeKeys,
attributeValues,
attributeCount,
enableOom,
attachments,
attachmentCount,
enableClientSideUnwinding,
reportsPerMinute,
basePath,
true);
// V2 shipped with one already-initialized value.
// Preserve that compatibility while V3 exposes the operational distinction to managed Unity code.
return result == BTUnityInitializationResultProcessLifetimeDisabled
? BTUnityInitializationResultAlreadyInitializedActive
: result;
}
} @catch (NSException *exception) {
BTLogCaughtException("StartBacktraceIntegrationV2", exception);
return BTUnityInitializationResultUnexpectedFailure;
}
}
BT_EXPORT void StartBacktraceIntegration(
const char *submissionUrl,
const char *attributeKeys[],
const char *attributeValues[],
int32_t attributeCount,
bool enableOom,
const char *attachments[],
int32_t attachmentCount,
bool enableClientSideUnwinding) {
@try {
@autoreleasepool {
NSError *storageError = nil;
NSString *basePath = BTLegacyCrashReportBasePath(&storageError);
if (basePath == nil) {
BTLogInitializationResult(
BTUnityInitializationResultStorageInitializationFailed,
BTInitializationErrorDetail(
@"Unable to derive isolated native crash storage.", storageError));
return;
}
(void)BTStartIntegration(submissionUrl,
attributeKeys,
attributeValues,
attributeCount,
enableOom,
attachments,
attachmentCount,
enableClientSideUnwinding,
30,
basePath,
true);
}
} @catch (NSException *exception) {
BTLogCaughtException("StartBacktraceIntegration", exception);
}
}
BT_EXPORT void GetAttributes(Entry **entriesOut, int32_t *sizeOut) {
Entry *entries = NULL;
int32_t count = 0;
@try {
@autoreleasepool {
if (entriesOut != NULL) {
*entriesOut = NULL;
}
if (sizeOut != NULL) {
*sizeOut = 0;
}
if (entriesOut == NULL || sizeOut == NULL) {
return;
}
BacktraceClient *client = BTActiveUnityClient();
NSDictionary<NSString *, NSString *> *attributes =
client == nil ? @{} : client.attributes;
NSArray<NSString *> *keys =
[attributes.allKeys sortedArrayUsingSelector:@selector(compare:)];
if (keys.count == 0 || keys.count > INT32_MAX) {
return;
}
count = static_cast<int32_t>(keys.count);
entries = static_cast<Entry *>(calloc(static_cast<size_t>(count), sizeof(Entry)));
if (entries == NULL) {
return;
}
for (int32_t index = 0; index < count; ++index) {
NSString *key = keys[static_cast<NSUInteger>(index)];
NSString *value = [NSString stringWithFormat:@"%@", attributes[key] ?: @""];
entries[index].Key = BTDuplicateString(key);
entries[index].Value = BTDuplicateString(value);
if (entries[index].Key == NULL || entries[index].Value == NULL) {
BTFreeAttributeEntries(entries, count);
entries = NULL;
return;
}
}
*entriesOut = entries;
*sizeOut = count;
entries = NULL; // Ownership transfers to the managed caller.
}
} @catch (NSException *exception) {
BTFreeAttributeEntries(entries, count);
if (entriesOut != NULL) {
*entriesOut = NULL;
}
if (sizeOut != NULL) {
*sizeOut = 0;
}
BTLogCaughtException("GetAttributes", exception);
}
}
BT_EXPORT void FreeAttributes(Entry *entries, int32_t size) {
@try {
BTFreeAttributeEntries(entries, size);
} @catch (NSException *exception) {
BTLogCaughtException("FreeAttributes", exception);
}
}
BT_EXPORT void NativeReport(const char *message,
bool setMainThreadAsFaultingThread,
bool ignoreIfDebugger) {
@try {
@autoreleasepool {
(void)setMainThreadAsFaultingThread;
BacktraceClient *client = BTActiveUnityClient();
if (client == nil ||
(ignoreIfDebugger && BTDebuggerAttached())) {
return;
}
[client sendWithMessage:BTString(message)
attachmentPaths:@[]
completion:^(__unused BacktraceResult *result) {}];
}
} @catch (NSException *exception) {
BTLogCaughtException("NativeReport", exception);
}
}
BT_EXPORT void AddAttribute(const char *key, const char *value) {
@try {
@autoreleasepool {
BacktraceClient *client = BTActiveUnityClient();
if (client == nil || key == NULL) {
return;
}
NSString *attributeKey = BTString(key);
if (attributeKey.length == 0) {
return;
}
NSMutableDictionary<NSString *, NSString *> *attributes =
[client.attributes mutableCopy] ?: [NSMutableDictionary dictionary];
attributes[attributeKey] = BTString(value);
client.attributes = attributes;
}
} @catch (NSException *exception) {
BTLogCaughtException("AddAttribute", exception);
}
}
BT_EXPORT const char *BtCrash(void) {
@try {
return "ok";
} @catch (NSException *exception) {
BTLogCaughtException("BtCrash", exception);
return "error";
}
}
BT_EXPORT void Disable(void) {
@try {