-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathdynarmic_callbacks.cpp
More file actions
2602 lines (2537 loc) · 108 KB
/
Copy pathdynarmic_callbacks.cpp
File metadata and controls
2602 lines (2537 loc) · 108 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
#include "dynarmic_internal.h"
#include "dynarmic_syscalls.h"
#include "darwin_file_syscalls.h"
#include "crash_exception.h"
namespace {
struct GuestCrashExceptionPayload {
std::string report;
std::string fallbackReason;
uint32_t fallbackNamespace;
uint64_t fallbackCode;
};
}
static void AppendCrashReportText(
std::string &report, const std::string &text) {
constexpr char truncatedMarker[] = "\n[report truncated]\n";
constexpr size_t markerLength = sizeof(truncatedMarker) - 1;
constexpr size_t payloadLimit =
LC32_FULL_CRASH_REPORT_MAX - markerLength;
if (text.empty()) {
return;
}
if (report.size() >= payloadLimit) {
if (report.size() == payloadLimit) {
report.append(truncatedMarker, markerLength);
}
return;
}
const size_t available = payloadLimit - report.size();
if (text.size() <= available) {
report.append(text);
return;
}
report.append(text.data(), available);
report.append(truncatedMarker, markerLength);
}
static void AppendCrashReportFormat(
std::string &report, const char *format, ...) {
va_list arguments;
va_start(arguments, format);
const std::string formatted = FormatString(format, arguments);
va_end(arguments);
AppendCrashReportText(report, formatted);
}
static const char *GuestSignalName(int signal) {
switch (signal) {
case SIGABRT: return "SIGABRT";
case SIGBUS: return "SIGBUS";
case SIGILL: return "SIGILL";
case SIGINT: return "SIGINT";
case SIGSEGV: return "SIGSEGV";
case SIGSYS: return "SIGSYS";
case SIGTRAP: return "SIGTRAP";
default: return "unknown";
}
}
static std::string GuestImageBasename(const std::string &path) {
const size_t separator = path.find_last_of('/');
return separator == std::string::npos
? path
: path.substr(separator + 1);
}
static std::string SanitizeCompactCrashText(
const std::string &text, size_t maximumLength) {
std::string result;
result.reserve(std::min(text.size(), maximumLength));
bool previousWasSpace = false;
bool truncated = false;
for (const unsigned char character : text) {
const bool whitespace = character == '\n' || character == '\r' ||
character == '\t';
const unsigned char output = whitespace ? ' ' : character;
if (output == ' ' && previousWasSpace) {
continue;
}
if (output < 0x20 || output == 0x7f) {
continue;
}
if (result.size() == maximumLength) {
truncated = true;
break;
}
result.push_back(static_cast<char>(output));
previousWasSpace = output == ' ';
}
if (truncated && result.size() >= 3) {
result.replace(result.size() - 3, 3, "...");
}
return result;
}
static bool GuestAbortReasonIsUsable(
const GuestAbortMetadata &metadata) {
return metadata.valid && metadata.reasonNamespace > 0 &&
metadata.reasonNamespace <=
LC32_OS_REASON_MAX_VALID_NAMESPACE;
}
static uint32_t GuestAbortReasonNamespace(
const GuestAbortMetadata &metadata) {
return GuestAbortReasonIsUsable(metadata)
? metadata.reasonNamespace
: LC32_OS_REASON_LIBSYSTEM;
}
static uint64_t GuestAbortReasonCode(
const GuestAbortMetadata &metadata) {
return GuestAbortReasonIsUsable(metadata)
? metadata.reasonCode
: LC32_GUEST_CRASH_REASON_CODE;
}
[[noreturn]] static void ThrowGuestCrashExceptionPayload(
const GuestAbortMetadata &metadata,
std::string fullReport,
std::string compactReason) {
if (compactReason.empty()) {
compactReason = "LiveExec32 guest process crashed";
}
if (compactReason.size() > LC32_OS_REASON_STRING_MAX) {
compactReason.resize(LC32_OS_REASON_STRING_MAX);
}
const uint32_t reasonNamespace =
GuestAbortReasonNamespace(metadata);
const uint64_t reasonCode =
GuestAbortReasonCode(metadata);
/* DumpCrashReport catches this private transport value before its broad
* failure handlers, then raises the Objective-C exception from that
* handler. An NSException raised here would otherwise be swallowed by
* the catch (...) which protects report construction. */
throw GuestCrashExceptionPayload{
std::move(fullReport), std::move(compactReason),
reasonNamespace, reasonCode};
}
class DynarmicCallbacks32 final : public Dynarmic::A32::UserCallbacks {
private:
bool dumpingBacktrace = false;
~DynarmicCallbacks32() = default;
public:
void destroy() {
this->cp15 = nullptr;
delete this;
}
DynarmicCallbacks32(khash_t(memory) *memory)
: memory{memory}, cp15(std::make_shared<DynarmicCP15>()) {}
bool IsReadOnlyMemory(
u32 vaddr __attribute__((unused)))
override {
/*
* Debugger writes and later mprotect calls can still change a
* read-only page. Keep this conservative so Dynarmic never embeds a
* value as permanently immutable.
*/
return false;
}
std::optional<uint32_t> MemoryReadCode(u32 vaddr) override {
#if TRACE_BRANCH
static u32 lastRead;
if (vaddr - lastRead != 4 && vaddr == cpu->Regs()[15]) {
lastRead = vaddr;
DumpBacktrace(false);
}
#endif
uint32_t result = 0;
if (!read_guest_memory_with_permissions(
vaddr, &result, sizeof(result),
PROT_EXEC)) {
return std::nullopt;
}
return result;
}
u16 MemoryReadThumbCode(u32 vaddr) {
u16 code = 0;
if (!read_guest_memory_with_permissions(
vaddr, &code, sizeof(code),
PROT_EXEC)) {
return 0;
}
// printf("MemoryReadThumbCode[%s->%s:%d]: vaddr=0x%x, code=0x%04x\n", __FILE__, __func__, __LINE__, vaddr, code);
return code;
}
/*
* Yield to the remote debugger without running the built-in backtrace.
* The latter reads more guest memory and can recursively fault before
* gdbstub gets a chance to report the original stop.
*/
void StopForDebugger(int signal, bool pendingSignal) {
RecordGuestStopSignal(signal, pendingSignal);
cpu->HaltExecution(LC32HaltReasonTrap);
}
// FIXME: sometimes it will try to access 0x4, 0x8 and 0xc, I disassembled and found nothing, is there something to do with cpsr? For now let it do stuff in an empty page...
void HandleBadMemoryAccess(
const char *operation, u32 address) {
#if !IGNORE_BAD_MEM_ACCESS
SetPendingGuestCrashMessage(
"%s at guest address 0x%08x", operation, address);
// Diagnostic frame walking is not guest execution. A failed unwind
// read must not replace the original debugger stop with SIGSEGV.
if (!dumpingBacktrace) {
if (guestDebuggerEnabled.load(std::memory_order_relaxed)) {
StopForDebugger(SIGSEGV, true);
} else {
DumpCrashReport(SIGSEGV);
}
}
#endif
}
u8 MemoryRead8(u32 vaddr) override {
u8 value = 0;
if (read_guest_memory_with_permissions(
vaddr, &value, sizeof(value),
PROT_READ)) {
#if TRACE_RW
printf("Trace: read08(0x%04x) = 0x%01x\n", vaddr, value);
#endif
return value;
} else {
fprintf(stderr, "MemoryRead8[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryRead8", vaddr);
return 0;
}
}
u16 MemoryRead16(u32 vaddr, bool trace) {
u16 value = 0;
if (read_guest_memory_with_permissions(
vaddr, &value, sizeof(value),
PROT_READ)) {
#if TRACE_RW
if (trace)
printf("Trace: read16(0x%04x) = 0x%02x\n", vaddr, value);
#endif
return value;
} else {
fprintf(stderr, "MemoryRead16[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
// trace = tolerance bad mem access, else crash
if(trace) {
HandleBadMemoryAccess("MemoryRead16", vaddr);
} else {
SetPendingGuestCrashMessage(
"MemoryRead16 at guest address 0x%08x", vaddr);
DumpCrashReport(SIGSEGV);
}
return 0;
}
}
u16 MemoryRead16(u32 vaddr) override {
return MemoryRead16(vaddr, true);
}
u32 MemoryRead32(u32 vaddr, bool trace) {
u32 value = 0;
if (read_guest_memory_with_permissions(
vaddr, &value, sizeof(value),
PROT_READ)) {
//printf("MemoryRead32[%s->%s:%d]: vaddr=0x%x, value=0x%x\n", __FILE__, __func__, __LINE__, vaddr, dest[0]);
#if TRACE_RW
if (trace)
printf("Trace: read32(0x%04x) = 0x%04x\n", vaddr, value);
#endif
return value;
} else {
fprintf(stderr, "MemoryRead32[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
// trace = tolerance bad mem access, else crash
if(trace) {
HandleBadMemoryAccess("MemoryRead32", vaddr);
} else {
SetPendingGuestCrashMessage(
"MemoryRead32 at guest address 0x%08x", vaddr);
DumpCrashReport(SIGSEGV);
}
return 0;
}
}
u32 MemoryRead32(u32 vaddr) override {
return MemoryRead32(vaddr, true);
}
u64 MemoryRead64(u32 vaddr) override {
u64 value = 0;
if (read_guest_memory_with_permissions(
vaddr, &value, sizeof(value),
PROT_READ)) {
#if TRACE_RW
printf("Trace: read64(0x%04x) = 0x%08llx\n", vaddr, value);
#endif
return value;
} else {
fprintf(stderr, "MemoryRead64[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryRead64", vaddr);
return 0;
}
}
void MemoryWrite8(u32 vaddr, u8 value) override {
if (write_guest_memory_with_permissions(
vaddr, &value, sizeof(value),
PROT_WRITE)) {
#if TRACE_RW
printf("Trace: write08(0x%04x) = 0x%01x\n", vaddr, value);
#endif
} else {
fprintf(stderr, "MemoryWrite8[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryWrite8", vaddr);
}
}
void MemoryWrite16(u32 vaddr, u16 value) override {
if (write_guest_memory_with_permissions(
vaddr, &value, sizeof(value),
PROT_WRITE)) {
#if TRACE_RW
printf("Trace: write16(0x%04x) = 0x%02x\n", vaddr, value);
#endif
} else {
fprintf(stderr, "MemoryWrite16[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryWrite16", vaddr);
}
}
void MemoryWrite32(u32 vaddr, u32 value) override {
if (write_guest_memory_with_permissions(
vaddr, &value, sizeof(value),
PROT_WRITE)) {
#if TRACE_RW
printf("Trace: write32(0x%04x) = 0x%04x\n", vaddr, value);
#endif
} else {
fprintf(stderr, "MemoryWrite32[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryWrite32", vaddr);
}
}
void MemoryWrite64(u32 vaddr, u64 value) override {
if (write_guest_memory_with_permissions(
vaddr, &value, sizeof(value),
PROT_WRITE)) {
#if TRACE_RW
printf("Trace: write64(0x%04x) = 0x%08llx\n", vaddr, value);
#endif
} else {
fprintf(stderr, "MemoryWrite64[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryWrite64", vaddr);
}
}
bool MemoryWriteExclusive8(u32 vaddr, u8 value, u8 expected) override {
const ExclusiveGuestWriteResult result =
compare_exchange_guest_memory_with_permissions(
vaddr, value, expected);
if (result == ExclusiveGuestWriteResult::Fault) {
fprintf(stderr, "MemoryWriteExclusive8[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryWriteExclusive8", vaddr);
}
return result ==
ExclusiveGuestWriteResult::Committed;
}
bool MemoryWriteExclusive16(u32 vaddr, u16 value, u16 expected) override {
const ExclusiveGuestWriteResult result =
compare_exchange_guest_memory_with_permissions(
vaddr, value, expected);
if (result == ExclusiveGuestWriteResult::Fault) {
fprintf(stderr, "MemoryWriteExclusive16[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryWriteExclusive16", vaddr);
}
return result ==
ExclusiveGuestWriteResult::Committed;
}
bool MemoryWriteExclusive32(u32 vaddr, u32 value, u32 expected) override {
const ExclusiveGuestWriteResult result =
compare_exchange_guest_memory_with_permissions(
vaddr, value, expected);
if (result == ExclusiveGuestWriteResult::Fault) {
fprintf(stderr, "MemoryWriteExclusive32[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryWriteExclusive32", vaddr);
}
return result ==
ExclusiveGuestWriteResult::Committed;
}
bool MemoryWriteExclusive64(u32 vaddr, u64 value, u64 expected) override {
const ExclusiveGuestWriteResult result =
compare_exchange_guest_memory_with_permissions(
vaddr, value, expected);
if (result == ExclusiveGuestWriteResult::Fault) {
fprintf(stderr, "MemoryWriteExclusive64[%s->%s:%d]: vaddr=0x%x\n", __FILE__, __func__, __LINE__, vaddr);
HandleBadMemoryAccess("MemoryWriteExclusive64", vaddr);
}
return result ==
ExclusiveGuestWriteResult::Committed;
}
void InterpreterFallback(u32 pc, std::size_t num_instructions) override {
cpu->HaltExecution();
std::optional<std::uint32_t> code = MemoryReadCode(pc);
SetPendingGuestCrashMessage(
"Interpreter fallback at 0x%08x for %zu instruction(s)%s0x%08x",
pc, num_instructions, code ? ", instruction=" : ", unreadable instruction ",
code.value_or(0));
if(code) {
fprintf(stderr, "Unicorn fallback @ 0x%x for %lu instructions (instr = 0x%08X)", pc, num_instructions, *(cpsr->isThumb() ? MemoryReadThumbCode(pc) : MemoryReadCode(pc)));
}
cpu->Regs()[Reg::PC] = pc;
DumpCrashReport(SIGILL);
}
void ExceptionRaised(u32 pc, Dynarmic::A32::Exception exception) override {
const bool isBkpt =
exception == Dynarmic::A32::Exception::Breakpoint;
if (isBkpt && ConsumeGuestSoftwareTracepoint(pc, cpu)) {
return;
}
const bool isDebuggerBreakpoint =
isBkpt && Dynarmic_debugger_has_breakpoint(pc);
const bool inspectInstruction =
isBkpt ||
exception == Dynarmic::A32::Exception::UndefinedInstruction ||
exception == Dynarmic::A32::Exception::UnpredictableInstruction ||
exception == Dynarmic::A32::Exception::DecodeError;
u32 code = 0;
if (inspectInstruction) {
code = cpsr->isThumb() ? MemoryReadThumbCode(pc)
: MemoryReadCode(pc).value_or(0);
}
int signal = SIGABRT;
bool replayInstruction = false;
switch (exception) {
case Dynarmic::A32::Exception::Breakpoint:
signal = SIGTRAP;
break;
case Dynarmic::A32::Exception::UndefinedInstruction:
case Dynarmic::A32::Exception::UnpredictableInstruction:
case Dynarmic::A32::Exception::DecodeError:
signal = SIGILL;
replayInstruction = true;
break;
case Dynarmic::A32::Exception::NoExecuteFault:
signal = SIGSEGV;
replayInstruction = true;
break;
default:
break;
}
// LLVM uses UDF #0xDEFE for an explicit trap. It is a bad-instruction
// fault, not a debugger breakpoint.
if ((code & 0xFFFF) == 0xDEFE) {
signal = SIGILL;
replayInstruction = true;
}
/*
* Dynarmic has already advanced r15 when it invokes ExceptionRaised.
* Synchronous faults must replay the faulting instruction. A
* debugger-planted BKPT must also report the breakpoint's address so
* LLDB can match it and temporarily restore/step the original
* instruction. A BKPT that belongs to the guest itself keeps the
* architectural post-instruction PC.
*/
if (replayInstruction || isDebuggerBreakpoint) {
cpu->Regs()[Reg::PC] = pc;
}
if (isBkpt) {
if (guestDebuggerEnabled.load(std::memory_order_relaxed)) {
fprintf(stderr, "%s breakpoint at 0x%08x\n",
isDebuggerBreakpoint ? "Debugger-managed" : "Guest",
pc);
StopForDebugger(SIGTRAP, false);
} else {
printf("Breakpoint!\n");
SetPendingGuestCrashMessage(
"Guest breakpoint at 0x%08x", pc);
DumpCrashReport(SIGTRAP, false);
}
return;
}
if ((code & 0xFFFF) == 0xDEFE) {
SetPendingGuestCrashMessageIfEmpty(
"Guest trap at pc=0x%08x, exception=%d, instruction=0x%08x",
pc, static_cast<int>(exception), code);
printf("ExceptionRaised[%s->%s:%d]: pc=0x%x, exception=%d, code=TRAP\n", __FILE__, __func__, __LINE__, pc, exception);
DumpCrashReport(signal);
} else {
SetPendingGuestCrashMessageIfEmpty(
"Guest exception at pc=0x%08x, exception=%d, instruction=0x%08x",
pc, static_cast<int>(exception), code);
printf("ExceptionRaised[%s->%s:%d]: pc=0x%x, exception=%d, code=0x%08X\n", __FILE__, __func__, __LINE__, pc, exception, code);
DumpCrashReport(signal);
}
}
void DumpCrashReport(int signal = SIGABRT, bool pendingSignal = true) {
#ifdef LC32_GUEST_MEMORY_WATCH_ADDRESS
LogGuestMemoryWatchConsistency("crash");
#endif
if (guestDebuggerEnabled.load(std::memory_order_acquire)) {
pendingGuestAbortMetadata = {};
pendingGuestCrashMessage.clear();
StopForDebugger(signal, pendingSignal);
return;
}
const GuestAbortMetadata &metadata =
pendingGuestAbortMetadata;
const char *fallbackError = !metadata.reason.empty()
? metadata.reason.c_str()
: (!pendingGuestCrashMessage.empty()
? pendingGuestCrashMessage.c_str()
: "(no guest error text)");
const auto registers = cpu->Regs();
char fallbackReason[LC32_OS_REASON_STRING_MAX + 1];
snprintf(fallbackReason, sizeof(fallbackReason),
"LiveExec32 guest %s (%d); crash report construction failed\n"
"Error: %.*s\n"
"Registers: r0=%08x r1=%08x r2=%08x r3=%08x "
"r4=%08x r5=%08x r6=%08x r7=%08x "
"r8=%08x r9=%08x r10=%08x r11=%08x r12=%08x "
"sp=%08x lr=%08x pc=%08x cpsr=%08x",
GuestSignalName(signal), signal,
static_cast<int>(LC32_GUEST_ERROR_IN_COMPACT_REASON_MAX),
fallbackError,
registers[0], registers[1], registers[2], registers[3],
registers[4], registers[5], registers[6], registers[7],
registers[8], registers[9], registers[10], registers[11],
registers[12], registers[13], registers[14], registers[15],
cpu->Cpsr());
const uint32_t fallbackNamespace =
GuestAbortReasonNamespace(metadata);
const uint64_t fallbackCode =
GuestAbortReasonCode(metadata);
try {
DumpBacktrace(true, signal, pendingSignal);
} catch (const GuestCrashExceptionPayload &crash) {
dumpingBacktrace = false;
LC32ThrowGuestCrashException(
crash.report.data(), crash.report.size(),
crash.fallbackNamespace, crash.fallbackCode,
crash.fallbackReason.c_str());
} catch (const std::exception &exception) {
dumpingBacktrace = false;
HaltAllGuestJits(LC32HaltReasonTrap);
fprintf(stderr,
"LiveExec32 failed to construct guest crash report: %s\n%s\n",
exception.what(), fallbackReason);
fflush(stderr);
abort_with_reason(fallbackNamespace, fallbackCode,
fallbackReason, 0);
} catch (...) {
dumpingBacktrace = false;
HaltAllGuestJits(LC32HaltReasonTrap);
fprintf(stderr,
"LiveExec32 failed to construct guest crash report\n%s\n",
fallbackReason);
fflush(stderr);
abort_with_reason(fallbackNamespace, fallbackCode,
fallbackReason, 0);
}
}
void DumpBacktrace(bool crash,
int signal = SIGABRT,
bool pendingSignal = true) {
if (dumpingBacktrace) {
fprintf(stderr, "Caught error while dumping call stack\n");
if (crash) {
HaltAllGuestJits(LC32HaltReasonTrap);
}
return;
}
if (crash) {
CommitGuestStopSignal(signal, pendingSignal);
HaltAllGuestJits(LC32HaltReasonTrap);
if (guestCrashTerminationStarted.exchange(
true, std::memory_order_acq_rel)) {
return;
}
}
dumpingBacktrace = true;
GuestAbortMetadata abortMetadata;
std::string crashMessage;
if (crash) {
abortMetadata = std::move(pendingGuestAbortMetadata);
pendingGuestAbortMetadata = {};
crashMessage = std::move(pendingGuestCrashMessage);
pendingGuestCrashMessage.clear();
}
const auto registers = cpu->Regs();
const u32 cpsrValue = cpu->Cpsr();
const std::vector<GuestImageSnapshot> images =
SnapshotGuestImages();
const std::vector<GuestCrashAnnotation> annotations =
CollectGuestCrashAnnotations(images);
std::array<symbolicated_call, 0x100> callStack{};
int callStackLength = 0;
const auto appendAddress = [&](u32 address) {
if (address == 0 || callStackLength >=
static_cast<int>(callStack.size())) {
return;
}
callStack[callStackLength++].address = address & ~1u;
};
const auto appendReturnAddress = [&](u32 returnAddress) {
if (returnAddress == 0) {
return;
}
const u32 instructionSize =
(returnAddress & 1u) != 0 ? 2u : 4u;
const u32 normalizedAddress = returnAddress & ~1u;
appendAddress(normalizedAddress >= instructionSize
? normalizedAddress - instructionSize
: normalizedAddress);
};
// The register dump should agree with frame zero: PC is the current
// architectural location, while LR and frame-chain entries are
// return addresses and need to be moved back to their ARM/Thumb call.
appendAddress(registers[Reg::PC]);
appendReturnAddress(registers[Reg::LR]);
u32 framePointer = registers[7];
std::unordered_set<u32> visitedFramePointers;
std::string unwindMessage;
while (framePointer != 0 &&
callStackLength < static_cast<int>(callStack.size())) {
if ((framePointer & 3) != 0 ||
framePointer > UINT32_MAX - 8) {
AppendCrashReportFormat(unwindMessage,
"unwind stopped at invalid frame pointer 0x%08x",
framePointer);
break;
}
if (!visitedFramePointers.insert(framePointer).second) {
AppendCrashReportFormat(unwindMessage,
"unwind stopped at cyclic frame pointer 0x%08x",
framePointer);
break;
}
u32 nextFramePointer = 0;
u32 returnAddress = 0;
if (!read_guest_memory_with_permissions(
framePointer, &nextFramePointer,
sizeof(nextFramePointer), PROT_READ) ||
!read_guest_memory_with_permissions(
framePointer + 4, &returnAddress,
sizeof(returnAddress), PROT_READ)) {
AppendCrashReportFormat(unwindMessage,
"unwind stopped at unreadable frame pointer 0x%08x",
framePointer);
break;
}
appendReturnAddress(returnAddress);
framePointer = nextFramePointer;
}
if (framePointer != 0 &&
callStackLength == static_cast<int>(callStack.size()) &&
unwindMessage.empty()) {
unwindMessage = "unwind stopped at the 256-frame limit";
}
symbolicate_call_stack(
callStack.data(), callStackLength, images);
std::string report;
AppendCrashReportFormat(report,
"LiveExec32 guest %s report\n"
"Signal: %s (%d)\n",
crash ? "crash" : "branch",
GuestSignalName(signal), signal);
if (abortMetadata.valid) {
AppendCrashReportFormat(report,
"Guest abort: namespace=%u, code=0x%llx, "
"payload_size=0x%x, flags=0x%llx\n",
abortMetadata.reasonNamespace,
static_cast<unsigned long long>(
abortMetadata.reasonCode),
abortMetadata.payloadSize,
static_cast<unsigned long long>(
abortMetadata.reasonFlags));
if (!abortMetadata.reason.empty()) {
AppendCrashReportFormat(report,
"Guest error: %s\n",
abortMetadata.reason.c_str());
}
}
if (!crashMessage.empty()) {
AppendCrashReportFormat(report,
"Emulator error: %s\n", crashMessage.c_str());
}
AppendCrashReportFormat(report,
"Registers:\n"
" r0 0x%08x r1 0x%08x r2 0x%08x r3 0x%08x\n"
" r4 0x%08x r5 0x%08x r6 0x%08x r7 0x%08x\n"
" r8 0x%08x r9 0x%08x r10 0x%08x r11 0x%08x\n"
"r12 0x%08x sp 0x%08x lr 0x%08x pc 0x%08x\n"
"CPSR: 0x%08x thumb(%d) N(%d) Z(%d) C(%d) V(%d)\n",
registers[0], registers[1], registers[2], registers[3],
registers[4], registers[5], registers[6], registers[7],
registers[8], registers[9], registers[10], registers[11],
registers[12], registers[13], registers[14], registers[15],
cpsrValue, threadHandle.cpsr->isThumb(),
threadHandle.cpsr->isNegative(), threadHandle.cpsr->isZero(),
threadHandle.cpsr->hasCarry(), threadHandle.cpsr->isOverflow());
AppendCrashReportText(report, "Call stack:\n");
for (int index = 0; index < callStackLength; ++index) {
const symbolicated_call &call = callStack[index];
AppendCrashReportFormat(report,
"%3d: 0x%08x", index, call.address);
if (!call.imageName.empty()) {
const char *symbolName = call.symbolName.c_str();
if (symbolName[0] == '_') {
++symbolName;
}
AppendCrashReportFormat(report,
" %s`%s + 0x%x",
call.imageName.c_str(),
call.symbolName.empty()
? "(unknown symbol)"
: symbolName,
call.symbolOffset);
}
AppendCrashReportText(report, "\n");
}
if (!unwindMessage.empty()) {
AppendCrashReportFormat(report,
" [%s]\n", unwindMessage.c_str());
}
AppendCrashReportText(report, "Binary images:\n");
for (size_t index = 0; index < images.size(); ++index) {
AppendCrashReportFormat(report,
"%3zu: 0x%08x-0x%08x %s\n",
index, images[index].start, images[index].end,
images[index].name.c_str());
}
for (const GuestCrashAnnotation &annotation : annotations) {
if (annotation.message == abortMetadata.reason) {
continue;
}
AppendCrashReportFormat(report,
"Crash message from %s: %s (cause: 0x%llx)\n",
annotation.imageName.c_str(),
annotation.message.c_str(),
static_cast<unsigned long long>(annotation.abortCause));
}
if (!crash) {
fwrite(report.data(), 1, report.size(), stderr);
fflush(stderr);
dumpingBacktrace = false;
return;
}
std::string compactError;
if (!abortMetadata.reason.empty()) {
compactError = abortMetadata.reason;
} else if (!annotations.empty()) {
compactError = annotations.front().message;
if (!crashMessage.empty() &&
crashMessage != compactError) {
compactError += " | Emulator: ";
compactError += crashMessage;
}
} else if (!crashMessage.empty()) {
compactError = crashMessage;
}
std::string compactReason;
AppendCrashReportFormat(compactReason,
"LiveExec32 guest %s (%d)",
GuestSignalName(signal), signal);
if (abortMetadata.valid) {
AppendCrashReportFormat(compactReason,
"; abort ns=%u code=0x%llx",
abortMetadata.reasonNamespace,
static_cast<unsigned long long>(
abortMetadata.reasonCode));
}
compactReason += '\n';
if (!compactError.empty()) {
compactReason += "Error: ";
compactReason += SanitizeCompactCrashText(
compactError,
LC32_GUEST_ERROR_IN_COMPACT_REASON_MAX);
compactReason += '\n';
}
AppendCrashReportFormat(compactReason,
"Registers: r0=%08x r1=%08x r2=%08x r3=%08x "
"r4=%08x r5=%08x r6=%08x r7=%08x\n"
"r8=%08x r9=%08x r10=%08x r11=%08x r12=%08x "
"sp=%08x lr=%08x pc=%08x cpsr=%08x\n",
registers[0], registers[1], registers[2], registers[3],
registers[4], registers[5], registers[6], registers[7],
registers[8], registers[9], registers[10], registers[11],
registers[12], registers[13], registers[14], registers[15],
cpsrValue);
std::string compactFrames = "Call stack:";
for (int index = 0; index < callStackLength; ++index) {
std::string entry;
AppendCrashReportFormat(entry, " %d=%08x", index,
callStack[index].address);
if (!callStack[index].imageName.empty()) {
entry += '@';
entry += SanitizeCompactCrashText(
GuestImageBasename(callStack[index].imageName), 40);
}
if (compactFrames.size() + entry.size() > 180) {
compactFrames += " ...";
break;
}
compactFrames += entry;
}
compactReason += compactFrames;
compactReason += '\n';
std::string compactImages = "Binary images:";
std::unordered_set<std::string> emittedImageNames;
const auto appendCompactImage = [&](
const GuestImageSnapshot &image) {
if (emittedImageNames.count(image.name) != 0) {
return true;
}
std::string entry;
const std::string imageName = SanitizeCompactCrashText(
GuestImageBasename(image.name), 48);
AppendCrashReportFormat(entry,
" %08x-%08x=%s", image.start, image.end,
imageName.c_str());
if (compactImages.size() + entry.size() > 130) {
return false;
}
emittedImageNames.insert(image.name);
compactImages += entry;
return true;
};
bool imageSpaceAvailable = true;
if (!images.empty()) {
imageSpaceAvailable = appendCompactImage(images.front());
}
for (int frameIndex = 0;
frameIndex < callStackLength && imageSpaceAvailable;
++frameIndex) {
const u32 address = callStack[frameIndex].address;
for (const GuestImageSnapshot &image : images) {
if (address >= image.start && address < image.end) {
imageSpaceAvailable = appendCompactImage(image);
break;
}
}
}
if (!imageSpaceAvailable) {
compactImages += " ...";
}
compactReason += compactImages;
dumpingBacktrace = false;
ThrowGuestCrashExceptionPayload(
abortMetadata, std::move(report), std::move(compactReason));
}
void CallSVC(u32 swi) override {
int NR = cpu->Regs()[12];
if (swi == 0 && cpu->Regs()[5] == POST_CALLBACK_SYSCALL_NUMBER && cpu->Regs()[7] == 0) { // postCallback
int number = cpu->Regs()[4];
/*
Svc svc = svcMemory.getSvc(number);
if (svc != null) {
svc.handlePostCallback(emulator);
return;
}
backend.emu_stop();
*/
printf("svc number: %d\n", number);
SetPendingGuestCrashMessage(
"Unhandled post-callback SVC number %d", number);
DumpCrashReport();
return;
}
if (swi == 0 && cpu->Regs()[5] == PRE_CALLBACK_SYSCALL_NUMBER && cpu->Regs()[7] == 0) { // preCallback
int number = cpu->Regs()[4];
/*
Svc svc = svcMemory.getSvc(number);
if (svc != null) {
svc.handlePreCallback(emulator);
return;
}
backend.emu_stop();
*/
printf("Unhandled svc number: %d\n", number);
SetPendingGuestCrashMessage(
"Unhandled pre-callback SVC number %d", number);
DumpCrashReport();
return;
}
if (swi != DARWIN_SWI_SYSCALL) {
if (swi == (cpsr->isThumb() ? 0xff : 0xffffff)) {
printf("LC32: throw: PopContextException\n");
SetPendingGuestCrashMessage(
"Unhandled PopContextException SVC 0x%x", swi);
DumpCrashReport();
return;
}
if (swi == (cpsr->isThumb() ? 0xff : 0xffffff) - 1) {
printf("LC32: throw: ThreadContextSwitchException\n");
SetPendingGuestCrashMessage(
"Unhandled ThreadContextSwitchException SVC 0x%x", swi);
DumpCrashReport();
return;
}
printf("Unhandled svc number: %d\n", swi);
SetPendingGuestCrashMessage(
"Unhandled non-Darwin SVC number %u (syscall r12=%d)",
swi, NR);
DumpCrashReport();
return;
/*
Svc svc = svcMemory.getSvc(swi);
if (svc != null) {
backend.reg_write(ArmConst.UC_ARM_REG_R0, (int) svc.handle(emulator));
return;
}
backend.emu_stop();
throw new IllegalStateException("svc number: " + swi + ", NR=" + NR);
*/
}
#if TRACE_SVC
printf("CallSVC(NR=%d)\n", NR);
#endif
cpsr->setCarry(false);
/*
BE CAREFUL WHEN MOVING SYSCALL. Checklist:
- Declared max args of the category
- Arg contains 64bit value? (must not)
- Exclude pointer-involved (guest_*)
*/
switch (NR) {
// direct calls with 0-4 arguments, returns 32bit value
case -91: // mk_timer_create
case -29: // host_self_trap
case -28: // task_self_trap
case -26: // mach_reply_port
case -21: // _kernelrpc_mach_port_insert_right_trap
case -19: // _kernelrpc_mach_port_mod_refs_trap
case SYS_getpid: // 20
case SYS_getuid: // 24
case SYS_geteuid: // 25
case SYS_getppid: // 39
case SYS_getegid: // 43
case SYS_getgid: // 47
case SYS_issetugid: // 327
cpu->Regs()[0] = syscallRetCarry(NR, cpu->Regs()[0], cpu->Regs()[1], cpu->Regs()[2], cpu->Regs()[3]);
cpsr->setCarry(false); // FIXME: mach_reply_port sets carry to true, idk why
break;
case -18: { // _kernelrpc_mach_port_deallocate_trap
const u64 result = syscallRetCarry(
(long)NR, cpu->Regs()[0], cpu->Regs()[1]);
cpu->Regs()[0] = (u32)result;
cpu->Regs()[1] = (u32)(result >> 32);
} break;
// direct call returning a 64-bit value
case -3: { // mach_absolute_time
const u64 result = mach_absolute_time();
cpu->Regs()[0] = (u32)result;
cpu->Regs()[1] = (u32)(result >> 32);
cpsr->setCarry(false);
} break;
// direct call with custom args
case SYS___pthread_canceled:
/*
* Guest pthread cancellation requests are not modeled yet.
* XNU accepts actions 1 and 2 (enable/disable) unconditionally;
* action 0 reports EINVAL when there is no pending enabled
* cancellation. Handle this at the guest ABI instead of
* mutating cancellation state on the emulator's host thread.
*/
if (cpu->Regs()[0] == 1 || cpu->Regs()[0] == 2) {
cpu->Regs()[0] =
return_with_carry_direct(0, false);
} else {
cpu->Regs()[0] =
return_with_carry_direct(EINVAL, true);
}
break;
case SYS___semwait_signal: