-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
Copy pathMachProcess.mm
4392 lines (3882 loc) · 160 KB
/
MachProcess.mm
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
//===-- MachProcess.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
//
//===----------------------------------------------------------------------===//
//
// Created by Greg Clayton on 6/15/07.
//
//===----------------------------------------------------------------------===//
#include "DNB.h"
#include "MacOSX/CFUtils.h"
#include "SysSignal.h"
#include <dlfcn.h>
#include <inttypes.h>
#include <mach-o/loader.h>
#include <mach/mach.h>
#include <mach/task.h>
#include <pthread.h>
#include <signal.h>
#include <spawn.h>
#include <sys/fcntl.h>
#include <sys/ptrace.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <uuid/uuid.h>
#include <algorithm>
#include <chrono>
#include <map>
#include <TargetConditionals.h>
#import <Foundation/Foundation.h>
#include "DNBDataRef.h"
#include "DNBLog.h"
#include "DNBThreadResumeActions.h"
#include "DNBTimer.h"
#include "MachProcess.h"
#include "PseudoTerminal.h"
#include "CFBundle.h"
#include "CFString.h"
#ifndef PLATFORM_BRIDGEOS
#define PLATFORM_BRIDGEOS 5
#endif
#ifndef PLATFORM_MACCATALYST
#define PLATFORM_MACCATALYST 6
#endif
#ifndef PLATFORM_IOSSIMULATOR
#define PLATFORM_IOSSIMULATOR 7
#endif
#ifndef PLATFORM_TVOSSIMULATOR
#define PLATFORM_TVOSSIMULATOR 8
#endif
#ifndef PLATFORM_WATCHOSSIMULATOR
#define PLATFORM_WATCHOSSIMULATOR 9
#endif
#ifndef PLATFORM_DRIVERKIT
#define PLATFORM_DRIVERKIT 10
#endif
#ifdef WITH_SPRINGBOARD
#include <CoreFoundation/CoreFoundation.h>
#include <SpringBoardServices/SBSWatchdogAssertion.h>
#include <SpringBoardServices/SpringBoardServer.h>
#endif // WITH_SPRINGBOARD
#if WITH_CAROUSEL
// For definition of CSLSOpenApplicationOptionForClockKit.
#include <CarouselServices/CSLSOpenApplicationOptions.h>
#endif // WITH_CAROUSEL
#if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS)
// This returns a CFRetained pointer to the Bundle ID for app_bundle_path,
// or NULL if there was some problem getting the bundle id.
static CFStringRef CopyBundleIDForPath(const char *app_bundle_path,
DNBError &err_str);
#endif
#if defined(WITH_BKS) || defined(WITH_FBS)
#import <Foundation/Foundation.h>
static const int OPEN_APPLICATION_TIMEOUT_ERROR = 111;
typedef void (*SetErrorFunction)(NSInteger, std::string, DNBError &);
typedef bool (*CallOpenApplicationFunction)(NSString *bundleIDNSStr,
NSDictionary *options,
DNBError &error, pid_t *return_pid);
// This function runs the BKSSystemService (or FBSSystemService) method
// openApplication:options:clientPort:withResult,
// messaging the app passed in bundleIDNSStr.
// The function should be run inside of an NSAutoReleasePool.
//
// It will use the "options" dictionary passed in, and fill the error passed in
// if there is an error.
// If return_pid is not NULL, we'll fetch the pid that was made for the
// bundleID.
// If bundleIDNSStr is NULL, then the system application will be messaged.
template <typename OpenFlavor, typename ErrorFlavor,
ErrorFlavor no_error_enum_value, SetErrorFunction error_function>
static bool CallBoardSystemServiceOpenApplication(NSString *bundleIDNSStr,
NSDictionary *options,
DNBError &error,
pid_t *return_pid) {
// Now make our systemService:
OpenFlavor *system_service = [[OpenFlavor alloc] init];
if (bundleIDNSStr == nil) {
bundleIDNSStr = [system_service systemApplicationBundleIdentifier];
if (bundleIDNSStr == nil) {
// Okay, no system app...
error.SetErrorString("No system application to message.");
return false;
}
}
mach_port_t client_port = [system_service createClientPort];
__block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block ErrorFlavor open_app_error = no_error_enum_value;
__block std::string open_app_error_string;
bool wants_pid = (return_pid != NULL);
__block pid_t pid_in_block;
const char *cstr = [bundleIDNSStr UTF8String];
if (!cstr)
cstr = "<Unknown Bundle ID>";
NSString *description = [options description];
DNBLog("[LaunchAttach] START (%d) templated *Board launcher: app lunch "
"request for "
"'%s' - options:\n%s",
getpid(), cstr, [description UTF8String]);
[system_service
openApplication:bundleIDNSStr
options:options
clientPort:client_port
withResult:^(NSError *bks_error) {
// The system service will cleanup the client port we created for
// us.
if (bks_error)
open_app_error = (ErrorFlavor)[bks_error code];
if (open_app_error == no_error_enum_value) {
if (wants_pid) {
pid_in_block =
[system_service pidForApplication:bundleIDNSStr];
DNBLog("[LaunchAttach] In completion handler, got pid for "
"bundle id "
"'%s', pid: %d.",
cstr, pid_in_block);
} else {
DNBLog("[LaunchAttach] In completion handler, launch was "
"successful, "
"debugserver did not ask for the pid");
}
} else {
const char *error_str =
[(NSString *)[bks_error localizedDescription] UTF8String];
if (error_str) {
open_app_error_string = error_str;
DNBLogError(
"[LaunchAttach] END (%d) In app launch attempt, got error "
"localizedDescription '%s'.",
getpid(), error_str);
const char *obj_desc =
[NSString stringWithFormat:@"%@", bks_error].UTF8String;
DNBLogError(
"[LaunchAttach] END (%d) In app launch attempt, got error "
"NSError object description: '%s'.",
getpid(), obj_desc);
}
DNBLogThreadedIf(LOG_PROCESS,
"In completion handler for send "
"event, got error \"%s\"(%ld).",
error_str ? error_str : "<unknown error>",
(long)open_app_error);
}
[system_service release];
dispatch_semaphore_signal(semaphore);
}
];
const uint32_t timeout_secs = 30;
dispatch_time_t timeout =
dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC);
long success = dispatch_semaphore_wait(semaphore, timeout) == 0;
dispatch_release(semaphore);
DNBLog("[LaunchAttach] END (%d) templated *Board launcher finished app lunch "
"request for "
"'%s'",
getpid(), cstr);
if (!success) {
DNBLogError("[LaunchAttach] END (%d) timed out trying to send "
"openApplication to %s.",
getpid(), cstr);
error.SetError(OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic);
error.SetErrorString("timed out trying to launch app");
} else if (open_app_error != no_error_enum_value) {
error_function(open_app_error, open_app_error_string, error);
DNBLogError("[LaunchAttach] END (%d) unable to launch the application with "
"CFBundleIdentifier '%s' "
"bks_error = %ld",
getpid(), cstr, (long)open_app_error);
success = false;
} else if (wants_pid) {
*return_pid = pid_in_block;
DNBLogThreadedIf(
LOG_PROCESS,
"Out of completion handler, pid from block %d and passing out: %d",
pid_in_block, *return_pid);
}
return success;
}
#endif
#if defined(WITH_BKS) || defined(WITH_FBS)
static void SplitEventData(const char *data, std::vector<std::string> &elements)
{
elements.clear();
if (!data)
return;
const char *start = data;
while (*start != '\0') {
const char *token = strchr(start, ':');
if (!token) {
elements.push_back(std::string(start));
return;
}
if (token != start)
elements.push_back(std::string(start, token - start));
start = ++token;
}
}
#endif
#ifdef WITH_BKS
#import <Foundation/Foundation.h>
extern "C" {
#import <BackBoardServices/BKSOpenApplicationConstants_Private.h>
#import <BackBoardServices/BKSSystemService_LaunchServices.h>
#import <BackBoardServices/BackBoardServices.h>
}
static bool IsBKSProcess(nub_process_t pid) {
BKSApplicationStateMonitor *state_monitor =
[[BKSApplicationStateMonitor alloc] init];
BKSApplicationState app_state =
[state_monitor mostElevatedApplicationStateForPID:pid];
return app_state != BKSApplicationStateUnknown;
}
static void SetBKSError(NSInteger error_code,
std::string error_description,
DNBError &error) {
error.SetError(error_code, DNBError::BackBoard);
NSString *err_nsstr = ::BKSOpenApplicationErrorCodeToString(
(BKSOpenApplicationErrorCode)error_code);
std::string err_str = "unknown BKS error";
if (error_description.empty() == false) {
err_str = error_description;
} else if (err_nsstr != nullptr) {
err_str = [err_nsstr UTF8String];
}
error.SetErrorString(err_str.c_str());
}
static bool BKSAddEventDataToOptions(NSMutableDictionary *options,
const char *event_data,
DNBError &option_error) {
std::vector<std::string> values;
SplitEventData(event_data, values);
bool found_one = false;
for (std::string value : values)
{
if (value.compare("BackgroundContentFetching") == 0) {
DNBLog("Setting ActivateForEvent key in options dictionary.");
NSDictionary *event_details = [NSDictionary dictionary];
NSDictionary *event_dictionary = [NSDictionary
dictionaryWithObject:event_details
forKey:
BKSActivateForEventOptionTypeBackgroundContentFetching];
[options setObject:event_dictionary
forKey:BKSOpenApplicationOptionKeyActivateForEvent];
found_one = true;
} else if (value.compare("ActivateSuspended") == 0) {
DNBLog("Setting ActivateSuspended key in options dictionary.");
[options setObject:@YES forKey: BKSOpenApplicationOptionKeyActivateSuspended];
found_one = true;
} else {
DNBLogError("Unrecognized event type: %s. Ignoring.", value.c_str());
option_error.SetErrorString("Unrecognized event data");
}
}
return found_one;
}
static NSMutableDictionary *BKSCreateOptionsDictionary(
const char *app_bundle_path, NSMutableArray *launch_argv,
NSMutableDictionary *launch_envp, NSString *stdio_path, bool disable_aslr,
const char *event_data) {
NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];
if (launch_argv != nil)
[debug_options setObject:launch_argv forKey:BKSDebugOptionKeyArguments];
if (launch_envp != nil)
[debug_options setObject:launch_envp forKey:BKSDebugOptionKeyEnvironment];
[debug_options setObject:stdio_path forKey:BKSDebugOptionKeyStandardOutPath];
[debug_options setObject:stdio_path
forKey:BKSDebugOptionKeyStandardErrorPath];
[debug_options setObject:[NSNumber numberWithBool:YES]
forKey:BKSDebugOptionKeyWaitForDebugger];
if (disable_aslr)
[debug_options setObject:[NSNumber numberWithBool:YES]
forKey:BKSDebugOptionKeyDisableASLR];
// That will go in the overall dictionary:
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:debug_options
forKey:BKSOpenApplicationOptionKeyDebuggingOptions];
// And there are some other options at the top level in this dictionary:
[options setObject:[NSNumber numberWithBool:YES]
forKey:BKSOpenApplicationOptionKeyUnlockDevice];
DNBError error;
BKSAddEventDataToOptions(options, event_data, error);
return options;
}
static CallOpenApplicationFunction BKSCallOpenApplicationFunction =
CallBoardSystemServiceOpenApplication<
BKSSystemService, BKSOpenApplicationErrorCode,
BKSOpenApplicationErrorCodeNone, SetBKSError>;
#endif // WITH_BKS
#ifdef WITH_FBS
#import <Foundation/Foundation.h>
extern "C" {
#import <FrontBoardServices/FBSOpenApplicationConstants_Private.h>
#import <FrontBoardServices/FBSSystemService_LaunchServices.h>
#import <FrontBoardServices/FrontBoardServices.h>
#import <MobileCoreServices/LSResourceProxy.h>
#import <MobileCoreServices/MobileCoreServices.h>
}
#ifdef WITH_BKS
static bool IsFBSProcess(nub_process_t pid) {
BKSApplicationStateMonitor *state_monitor =
[[BKSApplicationStateMonitor alloc] init];
BKSApplicationState app_state =
[state_monitor mostElevatedApplicationStateForPID:pid];
return app_state != BKSApplicationStateUnknown;
}
#else
static bool IsFBSProcess(nub_process_t pid) {
// FIXME: What is the FBS equivalent of BKSApplicationStateMonitor
return false;
}
#endif
static void SetFBSError(NSInteger error_code,
std::string error_description,
DNBError &error) {
error.SetError((DNBError::ValueType)error_code, DNBError::FrontBoard);
NSString *err_nsstr = ::FBSOpenApplicationErrorCodeToString(
(FBSOpenApplicationErrorCode)error_code);
std::string err_str = "unknown FBS error";
if (error_description.empty() == false) {
err_str = error_description;
} else if (err_nsstr != nullptr) {
err_str = [err_nsstr UTF8String];
}
error.SetErrorString(err_str.c_str());
}
static bool FBSAddEventDataToOptions(NSMutableDictionary *options,
const char *event_data,
DNBError &option_error) {
std::vector<std::string> values;
SplitEventData(event_data, values);
bool found_one = false;
for (std::string value : values)
{
if (value.compare("BackgroundContentFetching") == 0) {
DNBLog("Setting ActivateForEvent key in options dictionary.");
NSDictionary *event_details = [NSDictionary dictionary];
NSDictionary *event_dictionary = [NSDictionary
dictionaryWithObject:event_details
forKey:
FBSActivateForEventOptionTypeBackgroundContentFetching];
[options setObject:event_dictionary
forKey:FBSOpenApplicationOptionKeyActivateForEvent];
found_one = true;
} else if (value.compare("ActivateSuspended") == 0) {
DNBLog("Setting ActivateSuspended key in options dictionary.");
[options setObject:@YES forKey: FBSOpenApplicationOptionKeyActivateSuspended];
found_one = true;
#if WITH_CAROUSEL
} else if (value.compare("WatchComplicationLaunch") == 0) {
DNBLog("Setting FBSOpenApplicationOptionKeyActivateSuspended key in options dictionary.");
[options setObject:@YES forKey: CSLSOpenApplicationOptionForClockKit];
found_one = true;
#endif // WITH_CAROUSEL
} else {
DNBLogError("Unrecognized event type: %s. Ignoring.", value.c_str());
option_error.SetErrorString("Unrecognized event data.");
}
}
return found_one;
}
static NSMutableDictionary *
FBSCreateOptionsDictionary(const char *app_bundle_path,
NSMutableArray *launch_argv,
NSDictionary *launch_envp, NSString *stdio_path,
bool disable_aslr, const char *event_data) {
NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];
if (launch_argv != nil)
[debug_options setObject:launch_argv forKey:FBSDebugOptionKeyArguments];
if (launch_envp != nil)
[debug_options setObject:launch_envp forKey:FBSDebugOptionKeyEnvironment];
[debug_options setObject:stdio_path forKey:FBSDebugOptionKeyStandardOutPath];
[debug_options setObject:stdio_path
forKey:FBSDebugOptionKeyStandardErrorPath];
[debug_options setObject:[NSNumber numberWithBool:YES]
forKey:FBSDebugOptionKeyWaitForDebugger];
if (disable_aslr)
[debug_options setObject:[NSNumber numberWithBool:YES]
forKey:FBSDebugOptionKeyDisableASLR];
// That will go in the overall dictionary:
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:debug_options
forKey:FBSOpenApplicationOptionKeyDebuggingOptions];
// And there are some other options at the top level in this dictionary:
[options setObject:[NSNumber numberWithBool:YES]
forKey:FBSOpenApplicationOptionKeyUnlockDevice];
// We have to get the "sequence ID & UUID" for this app bundle path and send
// them to FBS:
NSURL *app_bundle_url =
[NSURL fileURLWithPath:[NSString stringWithUTF8String:app_bundle_path]
isDirectory:YES];
LSApplicationProxy *app_proxy =
[LSApplicationProxy applicationProxyForBundleURL:app_bundle_url];
if (app_proxy) {
DNBLog("Sending AppProxy info: sequence no: %lu, GUID: %s.",
app_proxy.sequenceNumber,
[app_proxy.cacheGUID.UUIDString UTF8String]);
[options
setObject:[NSNumber numberWithUnsignedInteger:app_proxy.sequenceNumber]
forKey:FBSOpenApplicationOptionKeyLSSequenceNumber];
[options setObject:app_proxy.cacheGUID.UUIDString
forKey:FBSOpenApplicationOptionKeyLSCacheGUID];
}
DNBError error;
FBSAddEventDataToOptions(options, event_data, error);
return options;
}
static CallOpenApplicationFunction FBSCallOpenApplicationFunction =
CallBoardSystemServiceOpenApplication<
FBSSystemService, FBSOpenApplicationErrorCode,
FBSOpenApplicationErrorCodeNone, SetFBSError>;
#endif // WITH_FBS
#if 0
#define DEBUG_LOG(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define DEBUG_LOG(fmt, ...)
#endif
#ifndef MACH_PROCESS_USE_POSIX_SPAWN
#define MACH_PROCESS_USE_POSIX_SPAWN 1
#endif
#ifndef _POSIX_SPAWN_DISABLE_ASLR
#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
#endif
MachProcess::MachProcess()
: m_pid(0), m_cpu_type(0), m_child_stdin(-1), m_child_stdout(-1),
m_child_stderr(-1), m_path(), m_args(), m_task(this),
m_flags(eMachProcessFlagsNone), m_stdio_thread(0),
m_stdio_mutex(PTHREAD_MUTEX_RECURSIVE), m_stdout_data(),
m_profile_enabled(false), m_profile_interval_usec(0), m_profile_thread(0),
m_profile_data_mutex(PTHREAD_MUTEX_RECURSIVE), m_profile_data(),
m_profile_events(0, eMachProcessProfileCancel), m_thread_actions(),
m_exception_messages(),
m_exception_messages_mutex(PTHREAD_MUTEX_RECURSIVE), m_thread_list(),
m_activities(), m_state(eStateUnloaded),
m_state_mutex(PTHREAD_MUTEX_RECURSIVE), m_events(0, kAllEventsMask),
m_private_events(0, kAllEventsMask), m_breakpoints(), m_watchpoints(),
m_name_to_addr_callback(NULL), m_name_to_addr_baton(NULL),
m_image_infos_callback(NULL), m_image_infos_baton(NULL),
m_sent_interrupt_signo(0), m_auto_resume_signo(0), m_did_exec(false),
m_dyld_process_info_create(nullptr),
m_dyld_process_info_for_each_image(nullptr),
m_dyld_process_info_release(nullptr),
m_dyld_process_info_get_cache(nullptr),
m_dyld_process_info_get_state(nullptr) {
m_dyld_process_info_create =
(void *(*)(task_t task, uint64_t timestamp, kern_return_t * kernelError))
dlsym(RTLD_DEFAULT, "_dyld_process_info_create");
m_dyld_process_info_for_each_image =
(void (*)(void *info, void (^)(uint64_t machHeaderAddress,
const uuid_t uuid, const char *path)))
dlsym(RTLD_DEFAULT, "_dyld_process_info_for_each_image");
m_dyld_process_info_release =
(void (*)(void *info))dlsym(RTLD_DEFAULT, "_dyld_process_info_release");
m_dyld_process_info_get_cache = (void (*)(void *info, void *cacheInfo))dlsym(
RTLD_DEFAULT, "_dyld_process_info_get_cache");
m_dyld_process_info_get_platform = (uint32_t (*)(void *info))dlsym(
RTLD_DEFAULT, "_dyld_process_info_get_platform");
m_dyld_process_info_get_state = (void (*)(void *info, void *stateInfo))dlsym(
RTLD_DEFAULT, "_dyld_process_info_get_state");
DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
}
MachProcess::~MachProcess() {
DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
Clear();
}
pid_t MachProcess::SetProcessID(pid_t pid) {
// Free any previous process specific data or resources
Clear();
// Set the current PID appropriately
if (pid == 0)
m_pid = ::getpid();
else
m_pid = pid;
return m_pid; // Return actually PID in case a zero pid was passed in
}
nub_state_t MachProcess::GetState() {
// If any other threads access this we will need a mutex for it
PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
return m_state;
}
const char *MachProcess::ThreadGetName(nub_thread_t tid) {
return m_thread_list.GetName(tid);
}
nub_state_t MachProcess::ThreadGetState(nub_thread_t tid) {
return m_thread_list.GetState(tid);
}
nub_size_t MachProcess::GetNumThreads() const {
return m_thread_list.NumThreads();
}
nub_thread_t MachProcess::GetThreadAtIndex(nub_size_t thread_idx) const {
return m_thread_list.ThreadIDAtIndex(thread_idx);
}
nub_thread_t
MachProcess::GetThreadIDForMachPortNumber(thread_t mach_port_number) const {
return m_thread_list.GetThreadIDByMachPortNumber(mach_port_number);
}
nub_bool_t MachProcess::SyncThreadState(nub_thread_t tid) {
MachThreadSP thread_sp(m_thread_list.GetThreadByID(tid));
if (!thread_sp)
return false;
kern_return_t kret = ::thread_abort_safely(thread_sp->MachPortNumber());
DNBLogThreadedIf(LOG_THREAD, "thread = 0x%8.8" PRIx32
" calling thread_abort_safely (tid) => %u "
"(GetGPRState() for stop_count = %u)",
thread_sp->MachPortNumber(), kret,
thread_sp->Process()->StopCount());
if (kret == KERN_SUCCESS)
return true;
else
return false;
}
ThreadInfo::QoS MachProcess::GetRequestedQoS(nub_thread_t tid, nub_addr_t tsd,
uint64_t dti_qos_class_index) {
return m_thread_list.GetRequestedQoS(tid, tsd, dti_qos_class_index);
}
nub_addr_t MachProcess::GetPThreadT(nub_thread_t tid) {
return m_thread_list.GetPThreadT(tid);
}
nub_addr_t MachProcess::GetDispatchQueueT(nub_thread_t tid) {
return m_thread_list.GetDispatchQueueT(tid);
}
nub_addr_t MachProcess::GetTSDAddressForThread(
nub_thread_t tid, uint64_t plo_pthread_tsd_base_address_offset,
uint64_t plo_pthread_tsd_base_offset, uint64_t plo_pthread_tsd_entry_size) {
return m_thread_list.GetTSDAddressForThread(
tid, plo_pthread_tsd_base_address_offset, plo_pthread_tsd_base_offset,
plo_pthread_tsd_entry_size);
}
MachProcess::DeploymentInfo
MachProcess::GetDeploymentInfo(const struct load_command &lc,
uint64_t load_command_address,
bool is_executable) {
DeploymentInfo info;
uint32_t cmd = lc.cmd & ~LC_REQ_DYLD;
// Handle the older LC_VERSION load commands, which don't
// distinguish between simulator and real hardware.
auto handle_version_min = [&](char platform) {
struct version_min_command vers_cmd;
if (ReadMemory(load_command_address, sizeof(struct version_min_command),
&vers_cmd) != sizeof(struct version_min_command))
return;
info.platform = platform;
info.major_version = vers_cmd.version >> 16;
info.minor_version = (vers_cmd.version >> 8) & 0xffu;
info.patch_version = vers_cmd.version & 0xffu;
// Disambiguate legacy simulator platforms.
#if (defined(__x86_64__) || defined(__i386__))
// If we are running on Intel macOS, it is safe to assume this is
// really a back-deploying simulator binary.
switch (info.platform) {
case PLATFORM_IOS:
info.platform = PLATFORM_IOSSIMULATOR;
break;
case PLATFORM_TVOS:
info.platform = PLATFORM_TVOSSIMULATOR;
break;
case PLATFORM_WATCHOS:
info.platform = PLATFORM_WATCHOSSIMULATOR;
break;
}
#else
// On an Apple Silicon macOS host, there is no ambiguity. The only
// binaries that use legacy load commands are back-deploying
// native iOS binaries. All simulator binaries use the newer,
// unambiguous LC_BUILD_VERSION load commands.
#endif
};
switch (cmd) {
case LC_VERSION_MIN_IPHONEOS:
handle_version_min(PLATFORM_IOS);
break;
case LC_VERSION_MIN_MACOSX:
handle_version_min(PLATFORM_MACOS);
break;
case LC_VERSION_MIN_TVOS:
handle_version_min(PLATFORM_TVOS);
break;
case LC_VERSION_MIN_WATCHOS:
handle_version_min(PLATFORM_WATCHOS);
break;
#if defined(LC_BUILD_VERSION)
case LC_BUILD_VERSION: {
struct build_version_command build_vers;
if (ReadMemory(load_command_address, sizeof(struct build_version_command),
&build_vers) != sizeof(struct build_version_command))
break;
info.platform = build_vers.platform;
info.major_version = build_vers.minos >> 16;
info.minor_version = (build_vers.minos >> 8) & 0xffu;
info.patch_version = build_vers.minos & 0xffu;
break;
}
#endif
}
// The xctest binary is a pure macOS binary but is launched with
// DYLD_FORCE_PLATFORM=6. In that case, force the platform to
// macCatalyst and use the macCatalyst version of the host OS
// instead of the macOS deployment target.
if (is_executable && GetPlatform() == PLATFORM_MACCATALYST) {
info.platform = PLATFORM_MACCATALYST;
std::string catalyst_version = GetMacCatalystVersionString();
const char *major = catalyst_version.c_str();
char *minor = nullptr;
char *patch = nullptr;
info.major_version = std::strtoul(major, &minor, 10);
info.minor_version = 0;
info.patch_version = 0;
if (minor && *minor == '.') {
info.minor_version = std::strtoul(++minor, &patch, 10);
if (patch && *patch == '.')
info.patch_version = std::strtoul(++patch, nullptr, 10);
}
}
return info;
}
std::optional<std::string>
MachProcess::GetPlatformString(unsigned char platform) {
switch (platform) {
case PLATFORM_MACOS:
return "macosx";
case PLATFORM_MACCATALYST:
return "maccatalyst";
case PLATFORM_IOS:
return "ios";
case PLATFORM_IOSSIMULATOR:
return "iossimulator";
case PLATFORM_TVOS:
return "tvos";
case PLATFORM_TVOSSIMULATOR:
return "tvossimulator";
case PLATFORM_WATCHOS:
return "watchos";
case PLATFORM_WATCHOSSIMULATOR:
return "watchossimulator";
case PLATFORM_BRIDGEOS:
return "bridgeos";
case PLATFORM_DRIVERKIT:
return "driverkit";
default:
DNBLogError("Unknown platform %u found for one binary", platform);
return std::nullopt;
}
}
static bool mach_header_validity_test(uint32_t magic, uint32_t cputype) {
if (magic != MH_MAGIC && magic != MH_CIGAM && magic != MH_MAGIC_64 &&
magic != MH_CIGAM_64)
return false;
if (cputype != CPU_TYPE_I386 && cputype != CPU_TYPE_X86_64 &&
cputype != CPU_TYPE_ARM && cputype != CPU_TYPE_ARM64 &&
cputype != CPU_TYPE_ARM64_32)
return false;
return true;
}
// Given an address, read the mach-o header and load commands out of memory to
// fill in
// the mach_o_information "inf" object.
//
// Returns false if there was an error in reading this mach-o file header/load
// commands.
bool MachProcess::GetMachOInformationFromMemory(
uint32_t dyld_platform, nub_addr_t mach_o_header_addr, int wordsize,
struct mach_o_information &inf) {
uint64_t load_cmds_p;
if (wordsize == 4) {
struct mach_header header;
if (ReadMemory(mach_o_header_addr, sizeof(struct mach_header), &header) !=
sizeof(struct mach_header)) {
return false;
}
if (!mach_header_validity_test(header.magic, header.cputype))
return false;
load_cmds_p = mach_o_header_addr + sizeof(struct mach_header);
inf.mach_header.magic = header.magic;
inf.mach_header.cputype = header.cputype;
// high byte of cpusubtype is used for "capability bits", v.
// CPU_SUBTYPE_MASK, CPU_SUBTYPE_LIB64 in machine.h
inf.mach_header.cpusubtype = header.cpusubtype & 0x00ffffff;
inf.mach_header.filetype = header.filetype;
inf.mach_header.ncmds = header.ncmds;
inf.mach_header.sizeofcmds = header.sizeofcmds;
inf.mach_header.flags = header.flags;
} else {
struct mach_header_64 header;
if (ReadMemory(mach_o_header_addr, sizeof(struct mach_header_64),
&header) != sizeof(struct mach_header_64)) {
return false;
}
if (!mach_header_validity_test(header.magic, header.cputype))
return false;
load_cmds_p = mach_o_header_addr + sizeof(struct mach_header_64);
inf.mach_header.magic = header.magic;
inf.mach_header.cputype = header.cputype;
// high byte of cpusubtype is used for "capability bits", v.
// CPU_SUBTYPE_MASK, CPU_SUBTYPE_LIB64 in machine.h
inf.mach_header.cpusubtype = header.cpusubtype & 0x00ffffff;
inf.mach_header.filetype = header.filetype;
inf.mach_header.ncmds = header.ncmds;
inf.mach_header.sizeofcmds = header.sizeofcmds;
inf.mach_header.flags = header.flags;
}
for (uint32_t j = 0; j < inf.mach_header.ncmds; j++) {
struct load_command lc;
if (ReadMemory(load_cmds_p, sizeof(struct load_command), &lc) !=
sizeof(struct load_command)) {
return false;
}
if (lc.cmd == LC_SEGMENT) {
struct segment_command seg;
if (ReadMemory(load_cmds_p, sizeof(struct segment_command), &seg) !=
sizeof(struct segment_command)) {
return false;
}
struct mach_o_segment this_seg;
char name[17];
::memset(name, 0, sizeof(name));
memcpy(name, seg.segname, sizeof(seg.segname));
this_seg.name = name;
this_seg.vmaddr = seg.vmaddr;
this_seg.vmsize = seg.vmsize;
this_seg.fileoff = seg.fileoff;
this_seg.filesize = seg.filesize;
this_seg.maxprot = seg.maxprot;
this_seg.initprot = seg.initprot;
this_seg.nsects = seg.nsects;
this_seg.flags = seg.flags;
inf.segments.push_back(this_seg);
if (this_seg.name == "ExecExtraSuspend")
m_task.TaskWillExecProcessesSuspended();
}
if (lc.cmd == LC_SEGMENT_64) {
struct segment_command_64 seg;
if (ReadMemory(load_cmds_p, sizeof(struct segment_command_64), &seg) !=
sizeof(struct segment_command_64)) {
return false;
}
struct mach_o_segment this_seg;
char name[17];
::memset(name, 0, sizeof(name));
memcpy(name, seg.segname, sizeof(seg.segname));
this_seg.name = name;
this_seg.vmaddr = seg.vmaddr;
this_seg.vmsize = seg.vmsize;
this_seg.fileoff = seg.fileoff;
this_seg.filesize = seg.filesize;
this_seg.maxprot = seg.maxprot;
this_seg.initprot = seg.initprot;
this_seg.nsects = seg.nsects;
this_seg.flags = seg.flags;
inf.segments.push_back(this_seg);
if (this_seg.name == "ExecExtraSuspend")
m_task.TaskWillExecProcessesSuspended();
}
if (lc.cmd == LC_UUID) {
struct uuid_command uuidcmd;
if (ReadMemory(load_cmds_p, sizeof(struct uuid_command), &uuidcmd) ==
sizeof(struct uuid_command))
uuid_copy(inf.uuid, uuidcmd.uuid);
}
if (DeploymentInfo deployment_info = GetDeploymentInfo(
lc, load_cmds_p, inf.mach_header.filetype == MH_EXECUTE)) {
std::optional<std::string> lc_platform =
GetPlatformString(deployment_info.platform);
if (dyld_platform != PLATFORM_MACCATALYST &&
inf.min_version_os_name == "macosx") {
// macCatalyst support.
//
// This the special case of "zippered" frameworks that have both
// a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.
//
// When we are in this block, this is a binary with both
// PLATFORM_MACOS and PLATFORM_MACCATALYST load commands and
// the process is not running as PLATFORM_MACCATALYST. Stick
// with the "macosx" load command that we've already
// processed, ignore this one, which is presumed to be a
// PLATFORM_MACCATALYST one.
} else {
inf.min_version_os_name = lc_platform.value_or("");
inf.min_version_os_version = "";
inf.min_version_os_version +=
std::to_string(deployment_info.major_version);
inf.min_version_os_version += ".";
inf.min_version_os_version +=
std::to_string(deployment_info.minor_version);
if (deployment_info.patch_version != 0) {
inf.min_version_os_version += ".";
inf.min_version_os_version +=
std::to_string(deployment_info.patch_version);
}
}
}
load_cmds_p += lc.cmdsize;
}
return true;
}
// Given completely filled in array of binary_image_information structures,
// create a JSONGenerator object
// with all the details we want to send to lldb.
JSONGenerator::ObjectSP MachProcess::FormatDynamicLibrariesIntoJSON(
const std::vector<struct binary_image_information> &image_infos,
bool report_load_commands) {
JSONGenerator::ArraySP image_infos_array_sp(new JSONGenerator::Array());
const size_t image_count = image_infos.size();
for (size_t i = 0; i < image_count; i++) {
// If we should report the Mach-O header and load commands,
// and those were unreadable, don't report anything about this
// binary.
if (report_load_commands && !image_infos[i].is_valid_mach_header)
continue;
JSONGenerator::DictionarySP image_info_dict_sp(
new JSONGenerator::Dictionary());
image_info_dict_sp->AddIntegerItem("load_address",
image_infos[i].load_address);
// TODO: lldb currently rejects a response without this, but it
// is always zero from dyld. It can be removed once we've had time
// for lldb's that require it to be present are obsolete.
image_info_dict_sp->AddIntegerItem("mod_date", 0);
image_info_dict_sp->AddStringItem("pathname", image_infos[i].filename);
if (!report_load_commands) {
image_infos_array_sp->AddItem(image_info_dict_sp);
continue;
}
uuid_string_t uuidstr;
uuid_unparse_upper(image_infos[i].macho_info.uuid, uuidstr);
image_info_dict_sp->AddStringItem("uuid", uuidstr);
if (!image_infos[i].macho_info.min_version_os_name.empty() &&
!image_infos[i].macho_info.min_version_os_version.empty()) {
image_info_dict_sp->AddStringItem(
"min_version_os_name", image_infos[i].macho_info.min_version_os_name);
image_info_dict_sp->AddStringItem(
"min_version_os_sdk",
image_infos[i].macho_info.min_version_os_version);
}
JSONGenerator::DictionarySP mach_header_dict_sp(
new JSONGenerator::Dictionary());
mach_header_dict_sp->AddIntegerItem(
"magic", image_infos[i].macho_info.mach_header.magic);
mach_header_dict_sp->AddIntegerItem(
"cputype", (uint32_t)image_infos[i].macho_info.mach_header.cputype);
mach_header_dict_sp->AddIntegerItem(
"cpusubtype",
(uint32_t)image_infos[i].macho_info.mach_header.cpusubtype);
mach_header_dict_sp->AddIntegerItem(
"filetype", image_infos[i].macho_info.mach_header.filetype);
mach_header_dict_sp->AddIntegerItem ("flags",
image_infos[i].macho_info.mach_header.flags);
// DynamicLoaderMacOSX doesn't currently need these fields, so
// don't send them.
// mach_header_dict_sp->AddIntegerItem ("ncmds",
// image_infos[i].macho_info.mach_header.ncmds);
// mach_header_dict_sp->AddIntegerItem ("sizeofcmds",
// image_infos[i].macho_info.mach_header.sizeofcmds);
image_info_dict_sp->AddItem("mach_header", mach_header_dict_sp);
JSONGenerator::ArraySP segments_sp(new JSONGenerator::Array());
for (size_t j = 0; j < image_infos[i].macho_info.segments.size(); j++) {
JSONGenerator::DictionarySP segment_sp(new JSONGenerator::Dictionary());
segment_sp->AddStringItem("name",
image_infos[i].macho_info.segments[j].name);
segment_sp->AddIntegerItem("vmaddr",
image_infos[i].macho_info.segments[j].vmaddr);
segment_sp->AddIntegerItem("vmsize",
image_infos[i].macho_info.segments[j].vmsize);
segment_sp->AddIntegerItem("fileoff",
image_infos[i].macho_info.segments[j].fileoff);
segment_sp->AddIntegerItem(
"filesize", image_infos[i].macho_info.segments[j].filesize);
segment_sp->AddIntegerItem("maxprot",
image_infos[i].macho_info.segments[j].maxprot);
// DynamicLoaderMacOSX doesn't currently need these fields,
// so don't send them.
// segment_sp->AddIntegerItem ("initprot",
// image_infos[i].macho_info.segments[j].initprot);
// segment_sp->AddIntegerItem ("nsects",
// image_infos[i].macho_info.segments[j].nsects);
// segment_sp->AddIntegerItem ("flags",