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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
|
//===-- NativeProcessDarwin.cpp ---------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "NativeProcessDarwin.h"
// C includes
#include <mach/mach_init.h>
#include <mach/mach_traps.h>
#include <sys/ptrace.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
// C++ includes
// LLDB includes
#include "lldb/Host/PseudoTerminal.h"
#include "lldb/Target/ProcessLaunchInfo.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/State.h"
#include "lldb/Utility/StreamString.h"
#include "CFBundle.h"
#include "CFString.h"
#include "DarwinProcessLauncher.h"
#include "MachException.h"
#include "llvm/Support/FileSystem.h"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_darwin;
using namespace lldb_private::darwin_process_launcher;
// Hidden Impl
namespace {
struct hack_task_dyld_info {
mach_vm_address_t all_image_info_addr;
mach_vm_size_t all_image_info_size;
};
}
// Public Static Methods
Status NativeProcessProtocol::Launch(
ProcessLaunchInfo &launch_info,
NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
NativeProcessProtocolSP &native_process_sp) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Status error;
// Verify the working directory is valid if one was specified.
FileSpec working_dir(launch_info.GetWorkingDirectory());
if (working_dir) {
FileInstance::Instance().Resolve(working_dir);
if (!FileSystem::Instance().IsDirectory(working_dir)) {
error.SetErrorStringWithFormat("No such file or directory: %s",
working_dir.GetCString());
return error;
}
}
// Launch the inferior.
int pty_master_fd = -1;
LaunchFlavor launch_flavor = LaunchFlavor::Default;
error = LaunchInferior(launch_info, &pty_master_fd, &launch_flavor);
// Handle launch failure.
if (!error.Success()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() failed to launch process: "
"%s",
__FUNCTION__, error.AsCString());
return error;
}
// Handle failure to return a pid.
if (launch_info.GetProcessID() == LLDB_INVALID_PROCESS_ID) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() launch succeeded but no "
"pid was returned! Aborting.",
__FUNCTION__);
return error;
}
// Create the Darwin native process impl.
std::shared_ptr<NativeProcessDarwin> np_darwin_sp(
new NativeProcessDarwin(launch_info.GetProcessID(), pty_master_fd));
if (!np_darwin_sp->RegisterNativeDelegate(native_delegate)) {
native_process_sp.reset();
error.SetErrorStringWithFormat("failed to register the native delegate");
return error;
}
// Finalize the processing needed to debug the launched process with a
// NativeProcessDarwin instance.
error = np_darwin_sp->FinalizeLaunch(launch_flavor, mainloop);
if (!error.Success()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() aborting, failed to finalize"
" the launching of the process: %s",
__FUNCTION__, error.AsCString());
return error;
}
// Return the process and process id to the caller through the launch args.
native_process_sp = np_darwin_sp;
return error;
}
Status NativeProcessProtocol::Attach(
lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "NativeProcessDarwin::%s(pid = %" PRIi64 ")", __FUNCTION__,
pid);
// Retrieve the architecture for the running process.
ArchSpec process_arch;
Status error = ResolveProcessArchitecture(pid, process_arch);
if (!error.Success())
return error;
// TODO get attach to return this value.
const int pty_master_fd = -1;
std::shared_ptr<NativeProcessDarwin> native_process_darwin_sp(
new NativeProcessDarwin(pid, pty_master_fd));
if (!native_process_darwin_sp->RegisterNativeDelegate(native_delegate)) {
error.SetErrorStringWithFormat("failed to register the native "
"delegate");
return error;
}
native_process_darwin_sp->AttachToInferior(mainloop, pid, error);
if (!error.Success())
return error;
native_process_sp = native_process_darwin_sp;
return error;
}
// ctor/dtor
NativeProcessDarwin::NativeProcessDarwin(lldb::pid_t pid, int pty_master_fd)
: NativeProcessProtocol(pid), m_task(TASK_NULL), m_did_exec(false),
m_cpu_type(0), m_exception_port(MACH_PORT_NULL), m_exc_port_info(),
m_exception_thread(nullptr), m_exception_messages_mutex(),
m_sent_interrupt_signo(0), m_auto_resume_signo(0), m_thread_list(),
m_thread_actions(), m_waitpid_pipe(), m_waitpid_thread(nullptr),
m_waitpid_reader_handle() {
// TODO add this to the NativeProcessProtocol constructor.
m_terminal_fd = pty_master_fd;
}
NativeProcessDarwin::~NativeProcessDarwin() {}
// Instance methods
Status NativeProcessDarwin::FinalizeLaunch(LaunchFlavor launch_flavor,
MainLoop &main_loop) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
error = StartExceptionThread();
if (!error.Success()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failure starting the "
"mach exception port monitor thread: %s",
__FUNCTION__, error.AsCString());
// Terminate the inferior process. There's nothing meaningful we can do if
// we can't receive signals and exceptions. Since we launched the process,
// it's fair game for us to kill it.
::ptrace(PT_KILL, m_pid, 0, 0);
SetState(eStateExited);
return error;
}
StartSTDIOThread();
if (launch_flavor == LaunchFlavor::PosixSpawn) {
SetState(eStateAttaching);
errno = 0;
int err = ::ptrace(PT_ATTACHEXC, m_pid, 0, 0);
if (err == 0) {
// m_flags |= eMachProcessFlagsAttached;
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): successfully spawned "
"process with pid %" PRIu64,
__FUNCTION__, m_pid);
} else {
error.SetErrorToErrno();
SetState(eStateExited);
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): error: failed to "
"attach to spawned pid %" PRIu64 " (error=%d (%s))",
__FUNCTION__, m_pid, (int)error.GetError(), error.AsCString());
return error;
}
}
LLDB_LOGF(log, "NativeProcessDarwin::%s(): new pid is %" PRIu64 "...",
__FUNCTION__, m_pid);
// Spawn a thread to reap our child inferior process...
error = StartWaitpidThread(main_loop);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to start waitpid() "
"thread: %s",
__FUNCTION__, error.AsCString());
kill(SIGKILL, static_cast<::pid_t>(m_pid));
return error;
}
if (TaskPortForProcessID(error) == TASK_NULL) {
// We failed to get the task for our process ID which is bad. Kill our
// process; otherwise, it will be stopped at the entry point and get
// reparented to someone else and never go away.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): could not get task port "
"for process, sending SIGKILL and exiting: %s",
__FUNCTION__, error.AsCString());
kill(SIGKILL, static_cast<::pid_t>(m_pid));
return error;
}
// Indicate that we're stopped, as we always launch suspended.
SetState(eStateStopped);
// Success.
return error;
}
Status NativeProcessDarwin::SaveExceptionPortInfo() {
return m_exc_port_info.Save(m_task);
}
bool NativeProcessDarwin::ProcessUsingSpringBoard() const {
// TODO implement flags
// return (m_flags & eMachProcessFlagsUsingSBS) != 0;
return false;
}
bool NativeProcessDarwin::ProcessUsingBackBoard() const {
// TODO implement flags
// return (m_flags & eMachProcessFlagsUsingBKS) != 0;
return false;
}
// Called by the exception thread when an exception has been received from our
// process. The exception message is completely filled and the exception data
// has already been copied.
void NativeProcessDarwin::ExceptionMessageReceived(
const MachException::Message &message) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex);
if (m_exception_messages.empty()) {
// Suspend the task the moment we receive our first exception message.
SuspendTask();
}
// Use a locker to automatically unlock our mutex in case of exceptions Add
// the exception to our internal exception stack
m_exception_messages.push_back(message);
LLDB_LOGF(log, "NativeProcessDarwin::%s(): new queued message count: %lu",
__FUNCTION__, m_exception_messages.size());
}
void *NativeProcessDarwin::ExceptionThread(void *arg) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
if (!arg) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): cannot run mach exception "
"thread, mandatory process arg was null",
__FUNCTION__);
return nullptr;
}
return reinterpret_cast<NativeProcessDarwin *>(arg)->DoExceptionThread();
}
void *NativeProcessDarwin::DoExceptionThread() {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
LLDB_LOGF(log, "NativeProcessDarwin::%s(arg=%p) starting thread...",
__FUNCTION__, this);
pthread_setname_np("exception monitoring thread");
// Ensure we don't get CPU starved.
MaybeRaiseThreadPriority();
// We keep a count of the number of consecutive exceptions received so we
// know to grab all exceptions without a timeout. We do this to get a bunch
// of related exceptions on our exception port so we can process then
// together. When we have multiple threads, we can get an exception per
// thread and they will come in consecutively. The main loop in this thread
// can stop periodically if needed to service things related to this process.
//
// [did we lose some words here?]
//
// flag set in the options, so we will wait forever for an exception on
// 0 our exception port. After we get one exception, we then will use the
// MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
// exceptions for our process. After we have received the last pending
// exception, we will get a timeout which enables us to then notify our main
// thread that we have an exception bundle available. We then wait for the
// main thread to tell this exception thread to start trying to get
// exceptions messages again and we start again with a mach_msg read with
// infinite timeout.
//
// We choose to park a thread on this, rather than polling, because the
// polling is expensive. On devices, we need to minimize overhead caused by
// the process monitor.
uint32_t num_exceptions_received = 0;
Status error;
task_t task = m_task;
mach_msg_timeout_t periodic_timeout = 0;
#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
mach_msg_timeout_t watchdog_elapsed = 0;
mach_msg_timeout_t watchdog_timeout = 60 * 1000;
::pid_t pid = (::pid_t)process->GetID();
CFReleaser<SBSWatchdogAssertionRef> watchdog;
if (process->ProcessUsingSpringBoard()) {
// Request a renewal for every 60 seconds if we attached using SpringBoard.
watchdog.reset(::SBSWatchdogAssertionCreateForPID(nullptr, pid, 60));
LLDB_LOGF(log,
"::SBSWatchdogAssertionCreateForPID(NULL, %4.4x, 60) "
"=> %p",
pid, watchdog.get());
if (watchdog.get()) {
::SBSWatchdogAssertionRenew(watchdog.get());
CFTimeInterval watchdogRenewalInterval =
::SBSWatchdogAssertionGetRenewalInterval(watchdog.get());
LLDB_LOGF(log,
"::SBSWatchdogAssertionGetRenewalInterval(%p) => "
"%g seconds",
watchdog.get(), watchdogRenewalInterval);
if (watchdogRenewalInterval > 0.0) {
watchdog_timeout = (mach_msg_timeout_t)watchdogRenewalInterval * 1000;
if (watchdog_timeout > 3000) {
// Give us a second to renew our timeout.
watchdog_timeout -= 1000;
} else if (watchdog_timeout > 1000) {
// Give us a quarter of a second to renew our timeout.
watchdog_timeout -= 250;
}
}
}
if (periodic_timeout == 0 || periodic_timeout > watchdog_timeout)
periodic_timeout = watchdog_timeout;
}
#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
#ifdef WITH_BKS
CFReleaser<BKSWatchdogAssertionRef> watchdog;
if (process->ProcessUsingBackBoard()) {
::pid_t pid = process->GetID();
CFAllocatorRef alloc = kCFAllocatorDefault;
watchdog.reset(::BKSWatchdogAssertionCreateForPID(alloc, pid));
}
#endif // #ifdef WITH_BKS
// Do we want to use a weak pointer to the NativeProcessDarwin here, in which
// case we can guarantee we don't whack the process monitor if we race
// between this thread and the main one on shutdown?
while (IsExceptionPortValid()) {
::pthread_testcancel();
MachException::Message exception_message;
if (num_exceptions_received > 0) {
// We don't want a timeout here, just receive as many exceptions as we
// can since we already have one. We want to get all currently available
// exceptions for this task at once.
error = exception_message.Receive(
GetExceptionPort(),
MACH_RCV_MSG | MACH_RCV_INTERRUPT | MACH_RCV_TIMEOUT, 0);
} else if (periodic_timeout > 0) {
// We need to stop periodically in this loop, so try and get a mach
// message with a valid timeout (ms).
error = exception_message.Receive(GetExceptionPort(),
MACH_RCV_MSG | MACH_RCV_INTERRUPT |
MACH_RCV_TIMEOUT,
periodic_timeout);
} else {
// We don't need to parse all current exceptions or stop periodically,
// just wait for an exception forever.
error = exception_message.Receive(GetExceptionPort(),
MACH_RCV_MSG | MACH_RCV_INTERRUPT, 0);
}
if (error.Success()) {
// We successfully received an exception.
if (exception_message.CatchExceptionRaise(task)) {
++num_exceptions_received;
ExceptionMessageReceived(exception_message);
}
} else {
if (error.GetError() == MACH_RCV_INTERRUPTED) {
// We were interrupted.
// If we have no task port we should exit this thread, as it implies
// the inferior went down.
if (!IsExceptionPortValid()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): the inferior "
"exception port is no longer valid, "
"canceling exception thread...",
__FUNCTION__);
// Should we be setting a process state here?
break;
}
// Make sure the inferior task is still valid.
if (IsTaskValid()) {
// Task is still ok.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): interrupted, but "
"the inferior task iss till valid, "
"continuing...",
__FUNCTION__);
continue;
} else {
// The inferior task is no longer valid. Time to exit as the process
// has gone away.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): the inferior task "
"has exited, and so will we...",
__FUNCTION__);
// Does this race at all with our waitpid()?
SetState(eStateExited);
break;
}
} else if (error.GetError() == MACH_RCV_TIMED_OUT) {
// We timed out when waiting for exceptions.
if (num_exceptions_received > 0) {
// We were receiving all current exceptions with a timeout of zero.
// It is time to go back to our normal looping mode.
num_exceptions_received = 0;
// Notify our main thread we have a complete exception message bundle
// available. Get the possibly updated task port back from the
// process in case we exec'ed and our task port changed.
task = ExceptionMessageBundleComplete();
// In case we use a timeout value when getting exceptions, make sure
// our task is still valid.
if (IsTaskValid(task)) {
// Task is still ok.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): got a timeout, "
"continuing...",
__FUNCTION__);
continue;
} else {
// The inferior task is no longer valid. Time to exit as the
// process has gone away.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): the inferior "
"task has exited, and so will we...",
__FUNCTION__);
// Does this race at all with our waitpid()?
SetState(eStateExited);
break;
}
}
#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
if (watchdog.get()) {
watchdog_elapsed += periodic_timeout;
if (watchdog_elapsed >= watchdog_timeout) {
LLDB_LOGF(log, "SBSWatchdogAssertionRenew(%p)", watchdog.get());
::SBSWatchdogAssertionRenew(watchdog.get());
watchdog_elapsed = 0;
}
}
#endif
} else {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): continuing after "
"receiving an unexpected error: %u (%s)",
__FUNCTION__, error.GetError(), error.AsCString());
// TODO: notify of error?
}
}
}
#if defined(WITH_SPRINGBOARD) && !defined(WITH_BKS)
if (watchdog.get()) {
// TODO: change SBSWatchdogAssertionRelease to SBSWatchdogAssertionCancel
// when we
// all are up and running on systems that support it. The SBS framework has
// a #define that will forward SBSWatchdogAssertionRelease to
// SBSWatchdogAssertionCancel for now so it should still build either way.
DNBLogThreadedIf(LOG_TASK, "::SBSWatchdogAssertionRelease(%p)",
watchdog.get());
::SBSWatchdogAssertionRelease(watchdog.get());
}
#endif // #if defined (WITH_SPRINGBOARD) && !defined (WITH_BKS)
LLDB_LOGF(log, "NativeProcessDarwin::%s(%p): thread exiting...", __FUNCTION__,
this);
return nullptr;
}
Status NativeProcessDarwin::StartExceptionThread() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "NativeProcessDarwin::%s() called", __FUNCTION__);
// Make sure we've looked up the inferior port.
TaskPortForProcessID(error);
// Ensure the inferior task is valid.
if (!IsTaskValid()) {
error.SetErrorStringWithFormat("cannot start exception thread: "
"task 0x%4.4x is not valid",
m_task);
return error;
}
// Get the mach port for the process monitor.
mach_port_t task_self = mach_task_self();
// Allocate an exception port that we will use to track our child process
auto mach_err = ::mach_port_allocate(task_self, MACH_PORT_RIGHT_RECEIVE,
&m_exception_port);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): mach_port_allocate("
"task_self=0x%4.4x, MACH_PORT_RIGHT_RECEIVE, "
"&m_exception_port) failed: %u (%s)",
__FUNCTION__, task_self, error.GetError(), error.AsCString());
return error;
}
// Add the ability to send messages on the new exception port
mach_err = ::mach_port_insert_right(
task_self, m_exception_port, m_exception_port, MACH_MSG_TYPE_MAKE_SEND);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): mach_port_insert_right("
"task_self=0x%4.4x, m_exception_port=0x%4.4x, "
"m_exception_port=0x%4.4x, MACH_MSG_TYPE_MAKE_SEND) "
"failed: %u (%s)",
__FUNCTION__, task_self, m_exception_port, m_exception_port,
error.GetError(), error.AsCString());
return error;
}
// Save the original state of the exception ports for our child process.
error = SaveExceptionPortInfo();
if (error.Fail() || (m_exc_port_info.mask == 0)) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): SaveExceptionPortInfo() "
"failed, cannot install exception handler: %s",
__FUNCTION__, error.AsCString());
return error;
}
// Set the ability to get all exceptions on this port.
mach_err = ::task_set_exception_ports(
m_task, m_exc_port_info.mask, m_exception_port,
EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Fail()) {
LLDB_LOGF(log,
"::task_set_exception_ports (task = 0x%4.4x, "
"exception_mask = 0x%8.8x, new_port = 0x%4.4x, "
"behavior = 0x%8.8x, new_flavor = 0x%8.8x) failed: "
"%u (%s)",
m_task, m_exc_port_info.mask, m_exception_port,
(EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES), THREAD_STATE_NONE,
error.GetError(), error.AsCString());
return error;
}
// Create the exception thread.
auto pthread_err =
::pthread_create(&m_exception_thread, nullptr, ExceptionThread, this);
error.SetError(pthread_err, eErrorTypePOSIX);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to create Mach "
"exception-handling thread: %u (%s)",
__FUNCTION__, error.GetError(), error.AsCString());
}
return error;
}
lldb::addr_t
NativeProcessDarwin::GetDYLDAllImageInfosAddress(Status &error) const {
error.Clear();
struct hack_task_dyld_info dyld_info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
// Make sure that COUNT isn't bigger than our hacked up struct
// hack_task_dyld_info. If it is, then make COUNT smaller to match.
if (count > (sizeof(struct hack_task_dyld_info) / sizeof(natural_t))) {
count = (sizeof(struct hack_task_dyld_info) / sizeof(natural_t));
}
TaskPortForProcessID(error);
if (error.Fail())
return LLDB_INVALID_ADDRESS;
auto mach_err =
::task_info(m_task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Success()) {
// We now have the address of the all image infos structure.
return dyld_info.all_image_info_addr;
}
// We don't have it.
return LLDB_INVALID_ADDRESS;
}
uint32_t NativeProcessDarwin::GetCPUTypeForLocalProcess(::pid_t pid) {
int mib[CTL_MAXNAME] = {
0,
};
size_t len = CTL_MAXNAME;
if (::sysctlnametomib("sysctl.proc_cputype", mib, &len))
return 0;
mib[len] = pid;
len++;
cpu_type_t cpu;
size_t cpu_len = sizeof(cpu);
if (::sysctl(mib, static_cast<u_int>(len), &cpu, &cpu_len, 0, 0))
cpu = 0;
return cpu;
}
uint32_t NativeProcessDarwin::GetCPUType() const {
if (m_cpu_type == 0 && m_pid != 0)
m_cpu_type = GetCPUTypeForLocalProcess(m_pid);
return m_cpu_type;
}
task_t NativeProcessDarwin::ExceptionMessageBundleComplete() {
// We have a complete bundle of exceptions for our child process.
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex);
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): processing %lu exception "
"messages.",
__FUNCTION__, m_exception_messages.size());
if (m_exception_messages.empty()) {
// Not particularly useful...
return m_task;
}
bool auto_resume = false;
m_did_exec = false;
// First check for any SIGTRAP and make sure we didn't exec
const task_t task = m_task;
size_t i;
if (m_pid != 0) {
bool received_interrupt = false;
uint32_t num_task_exceptions = 0;
for (i = 0; i < m_exception_messages.size(); ++i) {
if (m_exception_messages[i].state.task_port != task) {
// This is an exception that is not for our inferior, ignore.
continue;
}
// This is an exception for the inferior.
++num_task_exceptions;
const int signo = m_exception_messages[i].state.SoftSignal();
if (signo == SIGTRAP) {
// SIGTRAP could mean that we exec'ed. We need to check the
// dyld all_image_infos.infoArray to see if it is NULL and if so, say
// that we exec'ed.
const addr_t aii_addr = GetDYLDAllImageInfosAddress(error);
if (aii_addr == LLDB_INVALID_ADDRESS)
break;
const addr_t info_array_count_addr = aii_addr + 4;
uint32_t info_array_count = 0;
size_t bytes_read = 0;
Status read_error;
read_error = ReadMemory(info_array_count_addr, // source addr
&info_array_count, // dest addr
4, // byte count
bytes_read); // #bytes read
if (read_error.Success() && (bytes_read == 4)) {
if (info_array_count == 0) {
// We got the all infos address, and there are zero entries. We
// think we exec'd.
m_did_exec = true;
// Force the task port to update itself in case the task port
// changed after exec
const task_t old_task = m_task;
const bool force_update = true;
const task_t new_task = TaskPortForProcessID(error, force_update);
if (old_task != new_task) {
LLDB_LOGF(log,
"exec: inferior task port changed "
"from 0x%4.4x to 0x%4.4x",
old_task, new_task);
}
}
} else {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() warning: "
"failed to read all_image_infos."
"infoArrayCount from 0x%8.8llx",
__FUNCTION__, info_array_count_addr);
}
} else if ((m_sent_interrupt_signo != 0) &&
(signo == m_sent_interrupt_signo)) {
// We just received the interrupt that we sent to ourselves.
received_interrupt = true;
}
}
if (m_did_exec) {
cpu_type_t process_cpu_type = GetCPUTypeForLocalProcess(m_pid);
if (m_cpu_type != process_cpu_type) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): arch changed from "
"0x%8.8x to 0x%8.8x",
__FUNCTION__, m_cpu_type, process_cpu_type);
m_cpu_type = process_cpu_type;
// TODO figure out if we need to do something here.
// DNBArchProtocol::SetArchitecture (process_cpu_type);
}
m_thread_list.Clear();
// TODO hook up breakpoints.
// m_breakpoints.DisableAll();
}
if (m_sent_interrupt_signo != 0) {
if (received_interrupt) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): process "
"successfully interrupted with signal %i",
__FUNCTION__, m_sent_interrupt_signo);
// Mark that we received the interrupt signal
m_sent_interrupt_signo = 0;
// Now check if we had a case where:
// 1 - We called NativeProcessDarwin::Interrupt() but we stopped
// for another reason.
// 2 - We called NativeProcessDarwin::Resume() (but still
// haven't gotten the interrupt signal).
// 3 - We are now incorrectly stopped because we are handling
// the interrupt signal we missed.
// 4 - We might need to resume if we stopped only with the
// interrupt signal that we never handled.
if (m_auto_resume_signo != 0) {
// Only auto_resume if we stopped with _only_ the interrupt signal.
if (num_task_exceptions == 1) {
auto_resume = true;
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): auto "
"resuming due to unhandled interrupt "
"signal %i",
__FUNCTION__, m_auto_resume_signo);
}
m_auto_resume_signo = 0;
}
} else {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): didn't get signal "
"%i after MachProcess::Interrupt()",
__FUNCTION__, m_sent_interrupt_signo);
}
}
}
// Let all threads recover from stopping and do any clean up based on the
// previous thread state (if any).
m_thread_list.ProcessDidStop(*this);
// Let each thread know of any exceptions
for (i = 0; i < m_exception_messages.size(); ++i) {
// Let the thread list forward all exceptions on down to each thread.
if (m_exception_messages[i].state.task_port == task) {
// This exception is for our inferior.
m_thread_list.NotifyException(m_exception_messages[i].state);
}
if (log) {
StreamString stream;
m_exception_messages[i].Dump(stream);
stream.Flush();
log->PutCString(stream.GetString().c_str());
}
}
if (log) {
StreamString stream;
m_thread_list.Dump(stream);
stream.Flush();
log->PutCString(stream.GetString().c_str());
}
bool step_more = false;
if (m_thread_list.ShouldStop(step_more) && (auto_resume == false)) {
// TODO - need to hook up event system here. !!!!
#if 0
// Wait for the eEventProcessRunningStateChanged event to be reset
// before changing state to stopped to avoid race condition with very
// fast start/stops.
struct timespec timeout;
//DNBTimer::OffsetTimeOfDay(&timeout, 0, 250 * 1000); // Wait for 250 ms
DNBTimer::OffsetTimeOfDay(&timeout, 1, 0); // Wait for 250 ms
m_events.WaitForEventsToReset(eEventProcessRunningStateChanged,
&timeout);
#endif
SetState(eStateStopped);
} else {
// Resume without checking our current state.
PrivateResume();
}
return m_task;
}
void NativeProcessDarwin::StartSTDIOThread() {
// TODO implement
}
Status NativeProcessDarwin::StartWaitpidThread(MainLoop &main_loop) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
// Strategy: create a thread that sits on waitpid(), waiting for the inferior
// process to die, reaping it in the process. Arrange for the thread to have
// a pipe file descriptor that it can send a byte over when the waitpid
// completes. Have the main loop have a read object for the other side of
// the pipe, and have the callback for the read do the process termination
// message sending.
// Create a single-direction communication channel.
const bool child_inherits = false;
error = m_waitpid_pipe.CreateNew(child_inherits);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to create waitpid "
"communication pipe: %s",
__FUNCTION__, error.AsCString());
return error;
}
// Hook up the waitpid reader callback.
// TODO make PipePOSIX derive from IOObject. This is goofy here.
const bool transfer_ownership = false;
auto io_sp = IOObjectSP(new NativeFile(m_waitpid_pipe.GetReadFileDescriptor(),
transfer_ownership));
m_waitpid_reader_handle = main_loop.RegisterReadObject(
io_sp, [this](MainLoopBase &) { HandleWaitpidResult(); }, error);
// Create the thread.
auto pthread_err =
::pthread_create(&m_waitpid_thread, nullptr, WaitpidThread, this);
error.SetError(pthread_err, eErrorTypePOSIX);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to create waitpid "
"handling thread: %u (%s)",
__FUNCTION__, error.GetError(), error.AsCString());
return error;
}
return error;
}
void *NativeProcessDarwin::WaitpidThread(void *arg) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (!arg) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): cannot run waitpid "
"thread, mandatory process arg was null",
__FUNCTION__);
return nullptr;
}
return reinterpret_cast<NativeProcessDarwin *>(arg)->DoWaitpidThread();
}
void NativeProcessDarwin::MaybeRaiseThreadPriority() {
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
struct sched_param thread_param;
int thread_sched_policy;
if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
&thread_param) == 0) {
thread_param.sched_priority = 47;
pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
}
#endif
}
void *NativeProcessDarwin::DoWaitpidThread() {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (m_pid == LLDB_INVALID_PROCESS_ID) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): inferior process ID is "
"not set, cannot waitpid on it",
__FUNCTION__);
return nullptr;
}
// Name the thread.
pthread_setname_np("waitpid thread");
// Ensure we don't get CPU starved.
MaybeRaiseThreadPriority();
Status error;
int status = -1;
while (1) {
// Do a waitpid.
::pid_t child_pid = ::waitpid(m_pid, &status, 0);
if (child_pid < 0)
error.SetErrorToErrno();
if (error.Fail()) {
if (error.GetError() == EINTR) {
// This is okay, we can keep going.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): waitpid(pid = %" PRIu64
", &status, 0) interrupted, continuing",
__FUNCTION__, m_pid);
continue;
}
// This error is not okay, abort.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): waitpid(pid = %" PRIu64
", &status, 0) aborting due to error: %u (%s)",
__FUNCTION__, m_pid, error.GetError(), error.AsCString());
break;
}
// Log the successful result.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): waitpid(pid = %" PRIu64
", &status, 0) => %i, status = %i",
__FUNCTION__, m_pid, child_pid, status);
// Handle the result.
if (WIFSTOPPED(status)) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): waitpid(pid = %" PRIu64
") received a stop, continuing waitpid() loop",
__FUNCTION__, m_pid);
continue;
} else // if (WIFEXITED(status) || WIFSIGNALED(status))
{
LLDB_LOGF(log,
"NativeProcessDarwin::%s(pid = %" PRIu64 "): "
"waitpid thread is setting exit status for pid = "
"%i to %i",
__FUNCTION__, m_pid, child_pid, status);
error = SendInferiorExitStatusToMainLoop(child_pid, status);
return nullptr;
}
}
// We should never exit as long as our child process is alive. If we get
// here, something completely unexpected went wrong and we should exit.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): internal error: waitpid thread "
"exited out of its main loop in an unexpected way. pid = %" PRIu64
". Sending exit status of -1.",
__FUNCTION__, m_pid);
error = SendInferiorExitStatusToMainLoop((::pid_t)m_pid, -1);
return nullptr;
}
Status NativeProcessDarwin::SendInferiorExitStatusToMainLoop(::pid_t pid,
int status) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
size_t bytes_written = 0;
// Send the pid.
error = m_waitpid_pipe.Write(&pid, sizeof(pid), bytes_written);
if (error.Fail() || (bytes_written < sizeof(pid))) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() - failed to write "
"waitpid exiting pid to the pipe. Client will not "
"hear about inferior exit status!",
__FUNCTION__);
return error;
}
// Send the status.
bytes_written = 0;
error = m_waitpid_pipe.Write(&status, sizeof(status), bytes_written);
if (error.Fail() || (bytes_written < sizeof(status))) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() - failed to write "
"waitpid exit result to the pipe. Client will not "
"hear about inferior exit status!",
__FUNCTION__);
}
return error;
}
Status NativeProcessDarwin::HandleWaitpidResult() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
// Read the pid.
const bool notify_status = true;
::pid_t pid = -1;
size_t bytes_read = 0;
error = m_waitpid_pipe.Read(&pid, sizeof(pid), bytes_read);
if (error.Fail() || (bytes_read < sizeof(pid))) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() - failed to read "
"waitpid exiting pid from the pipe. Will notify "
"as if parent process died with exit status -1.",
__FUNCTION__);
SetExitStatus(WaitStatus(WaitStatus::Exit, -1), notify_status);
return error;
}
// Read the status.
int status = -1;
error = m_waitpid_pipe.Read(&status, sizeof(status), bytes_read);
if (error.Fail() || (bytes_read < sizeof(status))) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s() - failed to read "
"waitpid exit status from the pipe. Will notify "
"as if parent process died with exit status -1.",
__FUNCTION__);
SetExitStatus(WaitStatus(WaitStatus::Exit, -1), notify_status);
return error;
}
// Notify the monitor that our state has changed.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): main loop received waitpid "
"exit status info: pid=%i (%s), status=%i",
__FUNCTION__, pid,
(pid == m_pid) ? "the inferior" : "not the inferior", status);
SetExitStatus(WaitStatus::Decode(status), notify_status);
return error;
}
task_t NativeProcessDarwin::TaskPortForProcessID(Status &error,
bool force) const {
if ((m_task == TASK_NULL) || force) {
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (m_pid == LLDB_INVALID_PROCESS_ID) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): cannot get task due "
"to invalid pid",
__FUNCTION__);
return TASK_NULL;
}
const uint32_t num_retries = 10;
const uint32_t usec_interval = 10000;
mach_port_t task_self = mach_task_self();
task_t task = TASK_NULL;
for (uint32_t i = 0; i < num_retries; i++) {
kern_return_t err = ::task_for_pid(task_self, m_pid, &task);
if (err == 0) {
// Succeeded. Save and return it.
error.Clear();
m_task = task;
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): ::task_for_pid("
"stub_port = 0x%4.4x, pid = %llu, &task) "
"succeeded: inferior task port = 0x%4.4x",
__FUNCTION__, task_self, m_pid, m_task);
return m_task;
} else {
// Failed to get the task for the inferior process.
error.SetError(err, eErrorTypeMachKernel);
if (log) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): ::task_for_pid("
"stub_port = 0x%4.4x, pid = %llu, &task) "
"failed, err = 0x%8.8x (%s)",
__FUNCTION__, task_self, m_pid, err, error.AsCString());
}
}
// Sleep a bit and try again
::usleep(usec_interval);
}
// We failed to get the task for the inferior process. Ensure that it is
// cleared out.
m_task = TASK_NULL;
}
return m_task;
}
void NativeProcessDarwin::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
Status &error) {
error.SetErrorString("TODO: implement");
}
Status NativeProcessDarwin::PrivateResume() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex);
m_auto_resume_signo = m_sent_interrupt_signo;
if (log) {
if (m_auto_resume_signo)
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): task 0x%x resuming (with "
"unhandled interrupt signal %i)...",
__FUNCTION__, m_task, m_auto_resume_signo);
else
LLDB_LOGF(log, "NativeProcessDarwin::%s(): task 0x%x resuming...",
__FUNCTION__, m_task);
}
error = ReplyToAllExceptions();
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): aborting, failed to "
"reply to exceptions: %s",
__FUNCTION__, error.AsCString());
return error;
}
// bool stepOverBreakInstruction = step;
// Let the thread prepare to resume and see if any threads want us to step
// over a breakpoint instruction (ProcessWillResume will modify the value of
// stepOverBreakInstruction).
m_thread_list.ProcessWillResume(*this, m_thread_actions);
// Set our state accordingly
if (m_thread_actions.NumActionsWithState(eStateStepping))
SetState(eStateStepping);
else
SetState(eStateRunning);
// Now resume our task.
error = ResumeTask();
return error;
}
Status NativeProcessDarwin::ReplyToAllExceptions() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
TaskPortForProcessID(error);
if (error.Fail()) {
LLDB_LOGF(log, "NativeProcessDarwin::%s(): no task port, aborting",
__FUNCTION__);
return error;
}
std::lock_guard<std::recursive_mutex> locker(m_exception_messages_mutex);
if (m_exception_messages.empty()) {
// We're done.
return error;
}
size_t index = 0;
for (auto &message : m_exception_messages) {
if (log) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): replying to exception "
"%zu...",
__FUNCTION__, index++);
}
int thread_reply_signal = 0;
const tid_t tid =
m_thread_list.GetThreadIDByMachPortNumber(message.state.thread_port);
const ResumeAction *action = nullptr;
if (tid != LLDB_INVALID_THREAD_ID)
action = m_thread_actions.GetActionForThread(tid, false);
if (action) {
thread_reply_signal = action->signal;
if (thread_reply_signal)
m_thread_actions.SetSignalHandledForThread(tid);
}
error = message.Reply(m_pid, m_task, thread_reply_signal);
if (error.Fail() && log) {
// We log any error here, but we don't stop the exception response
// handling.
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to reply to "
"exception: %s",
__FUNCTION__, error.AsCString());
error.Clear();
}
}
// Erase all exception message as we should have used and replied to them all
// already.
m_exception_messages.clear();
return error;
}
Status NativeProcessDarwin::ResumeTask() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
TaskPortForProcessID(error);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to get task port "
"for process when attempting to resume: %s",
__FUNCTION__, error.AsCString());
return error;
}
if (m_task == TASK_NULL) {
error.SetErrorString("task port retrieval succeeded but task port is "
"null when attempting to resume the task");
return error;
}
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): requesting resume of task "
"0x%4.4x",
__FUNCTION__, m_task);
// Get the BasicInfo struct to verify that we're suspended before we try to
// resume the task.
struct task_basic_info task_info;
error = GetTaskBasicInfo(m_task, &task_info);
if (error.Fail()) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): failed to get task "
"BasicInfo when attempting to resume: %s",
__FUNCTION__, error.AsCString());
return error;
}
// task_resume isn't counted like task_suspend calls are, so if the task is
// not suspended, don't try and resume it since it is already running
if (task_info.suspend_count > 0) {
auto mach_err = ::task_resume(m_task);
error.SetError(mach_err, eErrorTypeMachKernel);
if (log) {
if (error.Success())
LLDB_LOGF(log, "::task_resume(target_task = 0x%4.4x): success", m_task);
else
LLDB_LOGF(log, "::task_resume(target_task = 0x%4.4x) error: %s", m_task,
error.AsCString());
}
} else {
LLDB_LOGF(log,
"::task_resume(target_task = 0x%4.4x): ignored, "
"already running",
m_task);
}
return error;
}
bool NativeProcessDarwin::IsTaskValid() const {
if (m_task == TASK_NULL)
return false;
struct task_basic_info task_info;
return GetTaskBasicInfo(m_task, &task_info).Success();
}
bool NativeProcessDarwin::IsTaskValid(task_t task) const {
if (task == TASK_NULL)
return false;
struct task_basic_info task_info;
return GetTaskBasicInfo(task, &task_info).Success();
}
mach_port_t NativeProcessDarwin::GetExceptionPort() const {
return m_exception_port;
}
bool NativeProcessDarwin::IsExceptionPortValid() const {
return MACH_PORT_VALID(m_exception_port);
}
Status
NativeProcessDarwin::GetTaskBasicInfo(task_t task,
struct task_basic_info *info) const {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
// Validate args.
if (info == NULL) {
error.SetErrorStringWithFormat("NativeProcessDarwin::%s(): mandatory "
"info arg is null",
__FUNCTION__);
return error;
}
// Grab the task if we don't already have it.
if (task == TASK_NULL) {
error.SetErrorStringWithFormat("NativeProcessDarwin::%s(): given task "
"is invalid",
__FUNCTION__);
}
mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;
auto err = ::task_info(m_task, TASK_BASIC_INFO, (task_info_t)info, &count);
error.SetError(err, eErrorTypeMachKernel);
if (error.Fail()) {
LLDB_LOGF(log,
"::task_info(target_task = 0x%4.4x, "
"flavor = TASK_BASIC_INFO, task_info_out => %p, "
"task_info_outCnt => %u) failed: %u (%s)",
m_task, info, count, error.GetError(), error.AsCString());
return error;
}
Log *verbose_log(
GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_VERBOSE));
if (verbose_log) {
float user = (float)info->user_time.seconds +
(float)info->user_time.microseconds / 1000000.0f;
float system = (float)info->user_time.seconds +
(float)info->user_time.microseconds / 1000000.0f;
verbose_LLDB_LOGF(log,
"task_basic_info = { suspend_count = %i, "
"virtual_size = 0x%8.8llx, resident_size = "
"0x%8.8llx, user_time = %f, system_time = %f }",
info->suspend_count, (uint64_t)info->virtual_size,
(uint64_t)info->resident_size, user, system);
}
return error;
}
Status NativeProcessDarwin::SuspendTask() {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
if (m_task == TASK_NULL) {
error.SetErrorString("task port is null, cannot suspend task");
LLDB_LOGF(log, "NativeProcessDarwin::%s() failed: %s", __FUNCTION__,
error.AsCString());
return error;
}
auto mach_err = ::task_suspend(m_task);
error.SetError(mach_err, eErrorTypeMachKernel);
if (error.Fail() && log)
LLDB_LOGF(log, "::task_suspend(target_task = 0x%4.4x)", m_task);
return error;
}
Status NativeProcessDarwin::Resume(const ResumeActionList &resume_actions) {
Status error;
Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "NativeProcessDarwin::%s() called", __FUNCTION__);
if (CanResume()) {
m_thread_actions = resume_actions;
error = PrivateResume();
return error;
}
auto state = GetState();
if (state == eStateRunning) {
LLDB_LOGF(log,
"NativeProcessDarwin::%s(): task 0x%x is already "
"running, ignoring...",
__FUNCTION__, TaskPortForProcessID(error));
return error;
}
// We can't resume from this state.
error.SetErrorStringWithFormat("task 0x%x has state %s, can't resume",
TaskPortForProcessID(error),
StateAsCString(state));
return error;
}
Status NativeProcessDarwin::Halt() {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::Detach() {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::Signal(int signo) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::Interrupt() {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::Kill() {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::GetMemoryRegionInfo(lldb::addr_t load_addr,
MemoryRegionInfo &range_info) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::ReadMemory(lldb::addr_t addr, void *buf,
size_t size, size_t &bytes_read) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
size_t size,
size_t &bytes_read) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::WriteMemory(lldb::addr_t addr, const void *buf,
size_t size, size_t &bytes_written) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::AllocateMemory(size_t size, uint32_t permissions,
lldb::addr_t &addr) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::DeallocateMemory(lldb::addr_t addr) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
lldb::addr_t NativeProcessDarwin::GetSharedLibraryInfoAddress() {
return LLDB_INVALID_ADDRESS;
}
size_t NativeProcessDarwin::UpdateThreads() { return 0; }
bool NativeProcessDarwin::GetArchitecture(ArchSpec &arch) const {
return false;
}
Status NativeProcessDarwin::SetBreakpoint(lldb::addr_t addr, uint32_t size,
bool hardware) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
void NativeProcessDarwin::DoStopIDBumped(uint32_t newBumpId) {}
Status NativeProcessDarwin::GetLoadedModuleFileSpec(const char *module_path,
FileSpec &file_spec) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
Status NativeProcessDarwin::GetFileLoadAddress(const llvm::StringRef &file_name,
lldb::addr_t &load_addr) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
// NativeProcessProtocol protected interface
Status NativeProcessDarwin::GetSoftwareBreakpointTrapOpcode(
size_t trap_opcode_size_hint, size_t &actual_opcode_size,
const uint8_t *&trap_opcode_bytes) {
Status error;
error.SetErrorString("TODO: implement");
return error;
}
|