forked from ios-control/ios-deploy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathios-deploy.m
2002 lines (1706 loc) · 72.2 KB
/
ios-deploy.m
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
#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <signal.h>
#include <getopt.h>
#include <pwd.h>
#include <dlfcn.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <curl/curl.h>
#include "MobileDevice.h"
#import "errors.h"
#import "device_db.h"
NSMutableString * custom_commands = nil;
const char* output_path = NULL;
const char* error_path = NULL;
typedef struct am_device * AMDeviceRef;
mach_error_t AMDeviceSecureStartService(AMDeviceRef device, CFStringRef service_name, unsigned int *unknown, ServiceConnRef * handle);
mach_error_t AMDeviceCreateHouseArrestService(AMDeviceRef device, CFStringRef identifier, CFDictionaryRef options, AFCConnectionRef * handle);
CFSocketNativeHandle AMDServiceConnectionGetSocket(ServiceConnRef con);
void AMDServiceConnectionInvalidate(ServiceConnRef con);
bool AMDeviceIsAtLeastVersionOnPlatform(AMDeviceRef device, CFDictionaryRef vers);
int AMDeviceSecureTransferPath(int zero, AMDeviceRef device, CFURLRef url, CFDictionaryRef options, void *callback, int cbarg);
int AMDeviceSecureInstallApplication(int zero, AMDeviceRef device, CFURLRef url, CFDictionaryRef options, void *callback, int cbarg);
int AMDeviceSecureInstallApplicationBundle(AMDeviceRef device, CFURLRef url, CFDictionaryRef options, void *callback, int cbarg);
int AMDeviceMountImage(AMDeviceRef device, CFStringRef image, CFDictionaryRef options, void *callback, int cbarg);
mach_error_t AMDeviceLookupApplications(AMDeviceRef device, CFDictionaryRef options, CFDictionaryRef *result);
int AMDeviceGetInterfaceType(AMDeviceRef device);
int AMDServiceConnectionSend(ServiceConnRef con, const void * data, size_t size);
int AMDServiceConnectionReceive(ServiceConnRef con, void * data, size_t size);
bool found_device = false, verbose = false, unbuffered = false, nostart = false, detect_only = false, install = true, uninstall = false, no_wifi = false;
bool command_only = false;
char *command = NULL;
const char *target_props = NULL;
char const*target_filename = NULL;
char const*upload_pathname = NULL;
char *bundle_id = NULL;
bool justlaunch = false;
bool file_system = false;
bool non_recursively = false;
char *app_path = NULL;
char *app_deltas = NULL;
char *device_id = NULL;
char *args = NULL;
char *envs = NULL;
char *list_root = NULL;
const char * custom_script_path = NULL;
int _timeout = 0;
int _detectDeadlockTimeout = 0;
bool _json_output = false;
NSMutableArray *_file_meta_info = nil;
int port = 0; // 0 means "dynamically assigned"
CFStringRef last_path = NULL;
ServiceConnRef dbgServiceConnection = NULL;
pid_t parent = 0;
// PID of child process running lldb
pid_t child = 0;
NSString* tmpUUID;
struct am_device_notification *notify;
CFRunLoopSourceRef lldb_socket_runloop;
CFRunLoopSourceRef server_socket_runloop;
CFRunLoopSourceRef fdvendor_runloop;
// Error codes we report on different failures, so scripts can distinguish between user app exit
// codes and our exit codes. For non app errors we use codes in reserved 128-255 range.
const int exitcode_timeout = 252;
const int exitcode_error = 253;
const int exitcode_app_crash = 254;
const char *notify_endpoint = 0;
// Checks for MobileDevice.framework errors, tries to print them and exits.
#define check_error(call) \
do { \
unsigned int err = (unsigned int)call; \
if (err != 0) \
{ \
const char* msg = get_error_message(err); \
NSString *description = msg ? [NSString stringWithUTF8String:msg] : @"unknown."; \
NSLogJSON(@{@"Event": @"Error", @"Code": @(err), @"Status": description}); \
on_error(@"Error 0x%x: %@ " #call, err, description); \
} \
} while (false);
void disable_ssl(ServiceConnRef con)
{
// MobileDevice links with SSL, so function will be available;
typedef void (*SSL_free_t)(void*);
static SSL_free_t SSL_free = NULL;
if (SSL_free == NULL)
{
SSL_free = (SSL_free_t)dlsym(RTLD_DEFAULT, "SSL_free");
}
SSL_free(con->sslContext);
con->sslContext = NULL;
}
void on_error(NSString* format, ...)
{
va_list valist;
va_start(valist, format);
NSString* str = [[[NSString alloc] initWithFormat:format arguments:valist] autorelease];
va_end(valist);
if (!_json_output) {
NSLog(@"[ !! ] %@", str);
}
exit(exitcode_error);
}
// Print error message getting last errno and exit
void on_sys_error(NSString* format, ...) {
const char* errstr = strerror(errno);
va_list valist;
va_start(valist, format);
NSString* str = [[[NSString alloc] initWithFormat:format arguments:valist] autorelease];
va_end(valist);
on_error(@"%@ : %@", str, [NSString stringWithUTF8String:errstr]);
}
void __NSLogOut(NSString* format, va_list valist) {
NSString* str = [[[NSString alloc] initWithFormat:format arguments:valist] autorelease];
[[str stringByAppendingString:@"\n"] writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];
}
void NSLogOut(NSString* format, ...) {
if (!_json_output) {
va_list valist;
va_start(valist, format);
__NSLogOut(format, valist);
va_end(valist);
}
}
void NSLogVerbose(NSString* format, ...) {
if (verbose && !_json_output) {
va_list valist;
va_start(valist, format);
__NSLogOut(format, valist);
va_end(valist);
}
}
void NSLogJSON(NSDictionary* jsonDict) {
if (_json_output) {
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted
error:&error];
if (data) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[jsonString writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];
[jsonString release];
} else {
[@"{\"JSONError\": \"JSON error\"}" writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];
}
}
}
BOOL mkdirp(NSString* path) {
NSError* error = nil;
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:YES
attributes:nil
error:&error];
return success;
}
Boolean path_exists(CFTypeRef path) {
if (CFGetTypeID(path) == CFStringGetTypeID()) {
CFURLRef url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, true);
Boolean result = CFURLResourceIsReachable(url, NULL);
CFRelease(url);
return result;
} else if (CFGetTypeID(path) == CFURLGetTypeID()) {
return CFURLResourceIsReachable(path, NULL);
} else {
return false;
}
}
CFStringRef copy_find_path(CFStringRef rootPath, CFStringRef namePattern) {
FILE *fpipe = NULL;
CFStringRef cf_command;
if( !path_exists(rootPath) )
return NULL;
if (CFStringFind(namePattern, CFSTR("*"), 0).location == kCFNotFound) {
//No wildcards. Let's speed up the search
CFStringRef path = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@/%@"), rootPath, namePattern);
if( path_exists(path) )
return path;
CFRelease(path);
return NULL;
}
if (CFStringFind(namePattern, CFSTR("/"), 0).location == kCFNotFound) {
cf_command = CFStringCreateWithFormat(NULL, NULL, CFSTR("find '%@' -name '%@' -maxdepth 1 2>/dev/null | sort | tail -n 1"), rootPath, namePattern);
} else {
cf_command = CFStringCreateWithFormat(NULL, NULL, CFSTR("find '%@' -path '%@/%@' 2>/dev/null | sort | tail -n 1"), rootPath, rootPath, namePattern);
}
char command[1024] = { '\0' };
CFStringGetCString(cf_command, command, sizeof(command), kCFStringEncodingUTF8);
CFRelease(cf_command);
if (!(fpipe = (FILE *)popen(command, "r")))
on_sys_error(@"Error encountered while opening pipe");
char buffer[256] = { '\0' };
fgets(buffer, sizeof(buffer), fpipe);
pclose(fpipe);
strtok(buffer, "\n");
CFStringRef path = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingUTF8);
if( CFStringGetLength(path) > 0 && path_exists(path) )
return path;
CFRelease(path);
return NULL;
}
CFStringRef copy_xcode_dev_path() {
static char xcode_dev_path[256] = { '\0' };
if (strlen(xcode_dev_path) == 0) {
FILE *fpipe = NULL;
char *command = "xcode-select -print-path";
if (!(fpipe = (FILE *)popen(command, "r")))
on_sys_error(@"Error encountered while opening pipe");
char buffer[256] = { '\0' };
fgets(buffer, sizeof(buffer), fpipe);
pclose(fpipe);
strtok(buffer, "\n");
strcpy(xcode_dev_path, buffer);
}
return CFStringCreateWithCString(NULL, xcode_dev_path, kCFStringEncodingUTF8);
}
const char *get_home() {
const char* home = getenv("HOME");
if (!home) {
struct passwd *pwd = getpwuid(getuid());
home = pwd->pw_dir;
}
return home;
}
CFStringRef copy_xcode_path_for_impl(CFStringRef rootPath, CFStringRef subPath, CFStringRef search) {
CFStringRef searchPath = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@/%@"), rootPath, subPath );
CFStringRef res = copy_find_path(searchPath, search);
CFRelease(searchPath);
return res;
}
CFStringRef copy_xcode_path_for(CFStringRef subPath, CFStringRef search) {
CFStringRef xcodeDevPath = copy_xcode_dev_path();
CFStringRef defaultXcodeDevPath = CFSTR("/Applications/Xcode.app/Contents/Developer");
CFStringRef path = NULL;
const char* home = get_home();
// Try using xcode-select --print-path
path = copy_xcode_path_for_impl(xcodeDevPath, subPath, search);
// If not look in the default xcode location (xcode-select is sometimes wrong)
if (path == NULL && CFStringCompare(xcodeDevPath, defaultXcodeDevPath, 0) != kCFCompareEqualTo )
path = copy_xcode_path_for_impl(defaultXcodeDevPath, subPath, search);
// If not look in the users home directory, Xcode can store device support stuff there
if (path == NULL) {
CFRelease(xcodeDevPath);
xcodeDevPath = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s/Library/Developer/Xcode"), home );
path = copy_xcode_path_for_impl(xcodeDevPath, subPath, search);
}
CFRelease(xcodeDevPath);
return path;
}
device_desc get_device_desc(CFStringRef model) {
if (model != NULL) {
size_t sz = sizeof(device_db) / sizeof(device_desc);
for (size_t i = 0; i < sz; i ++) {
if (CFStringCompare(model, device_db[i].model, kCFCompareNonliteral | kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
return device_db[i];
}
}
}
device_desc res = device_db[UNKNOWN_DEVICE_IDX];
res.model = model;
res.name = model;
return res;
}
CFStringRef get_device_full_name(const AMDeviceRef device) {
CFStringRef full_name = NULL,
device_udid = AMDeviceCopyDeviceIdentifier(device),
device_name = NULL,
model_name = NULL,
sdk_name = NULL,
arch_name = NULL,
product_version = NULL,
build_version = NULL;
AMDeviceConnect(device);
device_name = AMDeviceCopyValue(device, 0, CFSTR("DeviceName"));
// Please ensure that device is connected or the name will be unknown
CFStringRef model = AMDeviceCopyValue(device, 0, CFSTR("HardwareModel"));
device_desc dev;
if (model != NULL) {
dev = get_device_desc(model);
} else {
dev= device_db[UNKNOWN_DEVICE_IDX];
model = dev.model;
}
model_name = dev.name;
sdk_name = dev.sdk;
arch_name = dev.arch;
product_version = AMDeviceCopyValue(device, 0, CFSTR("ProductVersion"));
build_version = AMDeviceCopyValue(device, 0, CFSTR("BuildVersion"));
NSLogVerbose(@"Hardware Model: %@", model);
NSLogVerbose(@"Device Name: %@", device_name);
NSLogVerbose(@"Model Name: %@", model_name);
NSLogVerbose(@"SDK Name: %@", sdk_name);
NSLogVerbose(@"Architecture Name: %@", arch_name);
NSLogVerbose(@"Product Version: %@", product_version);
NSLogVerbose(@"Build Version: %@", build_version);
if (device_name != NULL) {
full_name = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%@, %@, %@, %@) a.k.a. '%@'"), device_udid, model, model_name, sdk_name, arch_name, device_name);
} else {
full_name = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%@, %@, %@, %@)"), device_udid, model, model_name, sdk_name, arch_name);
}
AMDeviceDisconnect(device);
if(device_udid != NULL)
CFRelease(device_udid);
if(device_name != NULL)
CFRelease(device_name);
if(model != NULL)
CFRelease(model);
if(model_name != NULL)
CFRelease(model_name);
if(product_version)
CFRelease(product_version);
if(build_version)
CFRelease(build_version);
return CFAutorelease(full_name);
}
NSDictionary* get_device_json_dict(const AMDeviceRef device, CFStringRef connect_method) {
NSMutableDictionary *json_dict = [NSMutableDictionary new];
[json_dict setValue:(__bridge NSString *) connect_method forKey:@"connectMethod"];
AMDeviceConnect(device);
CFStringRef device_udid = AMDeviceCopyDeviceIdentifier(device);
if (device_udid) {
[json_dict setValue:(__bridge NSString *)device_udid forKey:@"DeviceIdentifier"];
CFRelease(device_udid);
}
CFStringRef device_hardware_model = AMDeviceCopyValue(device, 0, CFSTR("HardwareModel"));
if (device_hardware_model) {
[json_dict setValue:(NSString*)device_hardware_model forKey:@"HardwareModel"];
size_t device_db_length = sizeof(device_db) / sizeof(device_desc);
for (size_t i = 0; i < device_db_length; i ++) {
if (CFStringCompare(device_hardware_model, device_db[i].model, kCFCompareNonliteral | kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
device_desc dev = device_db[i];
[json_dict setValue:(__bridge NSString *)dev.name forKey:@"modelName"];
[json_dict setValue:(__bridge NSString *)dev.sdk forKey:@"modelSDK"];
[json_dict setValue:(__bridge NSString *)dev.arch forKey:@"modelArch"];
break;
}
}
CFRelease(device_hardware_model);
}
for (NSString *deviceValue in @[@"DeviceName",
@"BuildVersion",
@"DeviceClass",
@"ProductType",
@"ProductVersion"]) {
CFStringRef cf_value = AMDeviceCopyValue(device, 0, (__bridge CFStringRef)deviceValue);
if (cf_value) {
[json_dict setValue:(__bridge NSString *)cf_value forKey:deviceValue];
CFRelease(cf_value);
}
}
AMDeviceDisconnect(device);
return CFAutorelease(json_dict);
}
CFStringRef get_device_interface_name(const AMDeviceRef device) {
// AMDeviceGetInterfaceType(device) 0=Unknown, 1 = Direct/USB, 2 = Indirect/WIFI
switch(AMDeviceGetInterfaceType(device)) {
case 1:
return CFSTR("USB");
case 2:
return CFSTR("WIFI");
default:
return CFSTR("Unknown Connection");
}
}
CFMutableArrayRef copy_device_product_version_parts(AMDeviceRef device) {
CFStringRef version = AMDeviceCopyValue(device, 0, CFSTR("ProductVersion"));
CFArrayRef parts = CFStringCreateArrayBySeparatingStrings(NULL, version, CFSTR("."));
CFMutableArrayRef result = CFArrayCreateMutableCopy(NULL, CFArrayGetCount(parts), parts);
CFRelease(version);
CFRelease(parts);
return result;
}
CFStringRef copy_device_support_path(AMDeviceRef device, CFStringRef suffix) {
time_t startTime, endTime;
time( &startTime );
CFStringRef version = NULL;
CFStringRef build = AMDeviceCopyValue(device, 0, CFSTR("BuildVersion"));
CFStringRef deviceClass = AMDeviceCopyValue(device, 0, CFSTR("DeviceClass"));
CFStringRef deviceModel = AMDeviceCopyValue(device, 0, CFSTR("HardwareModel"));
CFStringRef deviceArch = NULL;
CFStringRef path = NULL;
device_desc dev;
if (deviceModel != NULL) {
dev = get_device_desc(deviceModel);
deviceArch = dev.arch;
}
CFMutableArrayRef version_parts = copy_device_product_version_parts(device);
NSLogVerbose(@"Device Class: %@", deviceClass);
NSLogVerbose(@"build: %@", build);
CFStringRef deviceClassPath[2];
if (CFStringCompare(CFSTR("AppleTV"), deviceClass, 0) == kCFCompareEqualTo) {
deviceClassPath[0] = CFSTR("Platforms/AppleTVOS.platform/DeviceSupport");
deviceClassPath[1] = CFSTR("tvOS DeviceSupport");
} else {
deviceClassPath[0] = CFSTR("Platforms/iPhoneOS.platform/DeviceSupport");
deviceClassPath[1] = CFSTR("iOS DeviceSupport");
}
while (CFArrayGetCount(version_parts) > 0) {
version = CFStringCreateByCombiningStrings(NULL, version_parts, CFSTR("."));
NSLogVerbose(@"version: %@", version);
for( int i = 0; i < 2; ++i ) {
if (path == NULL) {
CFStringRef search = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%@) %@/%@"), version, build, deviceArch, suffix);
path = copy_xcode_path_for(deviceClassPath[i], search);
CFRelease(search);
}
if (path == NULL) {
CFStringRef search = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (%@)/%@"), version, build, suffix);
path = copy_xcode_path_for(deviceClassPath[i], search);
CFRelease(search);
}
if (path == NULL) {
CFStringRef search = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ (*)/%@"), version, suffix);
path = copy_xcode_path_for(deviceClassPath[i], search);
CFRelease(search);
}
if (path == NULL) {
CFStringRef search = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@/%@"), version, suffix);
path = copy_xcode_path_for(deviceClassPath[i], search);
CFRelease(search);
}
if (path == NULL) {
CFStringRef search = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@.*/%@"), version, suffix);
path = copy_xcode_path_for(deviceClassPath[i], search);
CFRelease(search);
}
}
CFRelease(version);
if (path != NULL) {
break;
}
CFArrayRemoveValueAtIndex(version_parts, CFArrayGetCount(version_parts) - 1);
}
for( int i = 0; i < 2; ++i ) {
if (path == NULL) {
CFStringRef search = CFStringCreateWithFormat(NULL, NULL, CFSTR("Latest/%@"), suffix);
path = copy_xcode_path_for(deviceClassPath[i], search);
CFRelease(search);
}
}
CFRelease(version_parts);
CFRelease(build);
CFRelease(deviceClass);
if (deviceModel != NULL) {
CFRelease(deviceModel);
}
if (path == NULL) {
NSString *msg = [NSString stringWithFormat:@"Unable to locate DeviceSupport directory with suffix '%@'. This probably means you don't have Xcode installed, you will need to launch the app manually and logging output will not be shown!", suffix];
NSLogJSON(@{
@"Event": @"DeviceSupportError",
@"Status": msg,
});
on_error(msg);
}
time( &endTime );
NSLogVerbose(@"DeviceSupport directory '%@' was located. It took %.2f seconds", path, difftime(endTime,startTime));
return path;
}
void mount_callback(CFDictionaryRef dict, int arg) {
CFStringRef status = CFDictionaryGetValue(dict, CFSTR("Status"));
if (CFEqual(status, CFSTR("LookingUpImage"))) {
NSLogOut(@"[ 0%%] Looking up developer disk image");
} else if (CFEqual(status, CFSTR("CopyingImage"))) {
NSLogOut(@"[ 30%%] Copying DeveloperDiskImage.dmg to device");
} else if (CFEqual(status, CFSTR("MountingImage"))) {
NSLogOut(@"[ 90%%] Mounting developer disk image");
}
}
void mount_developer_image(AMDeviceRef device) {
CFStringRef image_path = copy_device_support_path(device, CFSTR("DeveloperDiskImage.dmg"));
CFStringRef sig_path = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@.signature"), image_path);
NSLogVerbose(@"Developer disk image: %@", image_path);
FILE* sig = fopen(CFStringGetCStringPtr(sig_path, kCFStringEncodingMacRoman), "rb");
size_t buf_size = 128;
void *sig_buf = malloc(buf_size);
size_t bytes_read = fread(sig_buf, 1, buf_size, sig);
if (bytes_read != buf_size) {
on_sys_error(@"fread read %d bytes but expected %d bytes.", bytes_read, buf_size);
}
fclose(sig);
CFDataRef sig_data = CFDataCreateWithBytesNoCopy(NULL, sig_buf, buf_size, NULL);
CFRelease(sig_path);
CFTypeRef keys[] = { CFSTR("ImageSignature"), CFSTR("ImageType") };
CFTypeRef values[] = { sig_data, CFSTR("Developer") };
CFDictionaryRef options = CFDictionaryCreate(NULL, (const void **)&keys, (const void **)&values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFRelease(sig_data);
unsigned int result = (unsigned int)AMDeviceMountImage(device, image_path, options, &mount_callback, 0);
if (result == 0) {
NSLogOut(@"[ 95%%] Developer disk image mounted successfully");
} else if (result == 0xe8000076 /* already mounted */) {
NSLogOut(@"[ 95%%] Developer disk image already mounted");
} else {
if (result != 0) {
const char* msg = get_error_message(result);
NSString *description = @"unknown.";
if (msg) {
description = [NSString stringWithUTF8String:msg];
NSLogOut(@"Error: %@", description);
}
NSLogJSON(@{@"Event": @"Error",
@"Code": @(result),
@"Status": description});
}
on_error(@"Unable to mount developer disk image. (%x)", result);
}
CFStringRef symbols_path = copy_device_support_path(device, CFSTR("Symbols"));
if (symbols_path != NULL)
{
NSLogOut(@"Symbol Path: %@", symbols_path);
NSLogJSON(@{@"Event": @"MountDeveloperImage",
@"SymbolsPath": (__bridge NSString *)symbols_path
}); CFRelease(symbols_path);
}
CFRelease(image_path);
CFRelease(options);
}
mach_error_t transfer_callback(CFDictionaryRef dict, int arg) {
if (CFDictionaryGetValue(dict, CFSTR("Error"))) {
return 0;
}
int percent;
CFStringRef status = CFDictionaryGetValue(dict, CFSTR("Status"));
CFNumberGetValue(CFDictionaryGetValue(dict, CFSTR("PercentComplete")), kCFNumberSInt32Type, &percent);
if (CFEqual(status, CFSTR("CopyingFile"))) {
CFStringRef path = CFDictionaryGetValue(dict, CFSTR("Path"));
if ((last_path == NULL || !CFEqual(path, last_path)) && !CFStringHasSuffix(path, CFSTR(".ipa"))) {
int overall_percent = percent / 2;
NSLogOut(@"[%3d%%] Copying %@ to device", overall_percent, path);
NSLogJSON(@{@"Event": @"BundleCopy",
@"OverallPercent": @(overall_percent),
@"Percent": @(percent),
@"Path": (__bridge NSString *)path
});
}
if (last_path != NULL) {
CFRelease(last_path);
}
last_path = CFStringCreateCopy(NULL, path);
}
return 0;
}
mach_error_t install_callback(CFDictionaryRef dict, int arg) {
if (CFDictionaryGetValue(dict, CFSTR("Error"))) {
return 0;
}
int percent;
CFStringRef status = CFDictionaryGetValue(dict, CFSTR("Status"));
CFNumberGetValue(CFDictionaryGetValue(dict, CFSTR("PercentComplete")), kCFNumberSInt32Type, &percent);
int overall_percent = (percent / 2) + 50;
NSLogOut(@"[%3d%%] %@", overall_percent, status);
NSLogJSON(@{@"Event": @"BundleInstall",
@"OverallPercent": @(overall_percent),
@"Percent": @(percent),
@"Status": (__bridge NSString *)status
});
return 0;
}
// During standard installation transferring and installation takes place
// in distinct function that can be passed distinct callbacks. Incremental
// installation performs both transfer and installation in a single function so
// use this callback to determine which step is occuring and call the proper
// callback.
mach_error_t incremental_install_callback(CFDictionaryRef dict, int arg) {
if (CFDictionaryGetValue(dict, CFSTR("Error"))) {
return 0;
}
CFStringRef status = CFDictionaryGetValue(dict, CFSTR("Status"));
if (CFEqual(status, CFSTR("TransferringPackage"))) {
int percent;
CFNumberGetValue(CFDictionaryGetValue(dict, CFSTR("PercentComplete")), kCFNumberSInt32Type, &percent);
int overall_percent = (percent / 2);
NSLogOut(@"[%3d%%] %@", overall_percent, status);
NSLogJSON(@{@"Event": @"TransferringPackage",
@"OverallPercent": @(overall_percent),
});
return 0;
} else if (CFEqual(status, CFSTR("CopyingFile"))) {
return transfer_callback(dict, arg);
} else {
return install_callback(dict, arg);
}
}
CFURLRef copy_device_app_url(AMDeviceRef device, CFStringRef identifier) {
CFDictionaryRef result = nil;
NSArray *a = [NSArray arrayWithObjects:
@"CFBundleIdentifier", // absolute must
@"ApplicationDSID",
@"ApplicationType",
@"CFBundleExecutable",
@"CFBundleDisplayName",
@"CFBundleIconFile",
@"CFBundleName",
@"CFBundleShortVersionString",
@"CFBundleSupportedPlatforms",
@"CFBundleURLTypes",
@"CodeInfoIdentifier",
@"Container",
@"Entitlements",
@"HasSettingsBundle",
@"IsUpgradeable",
@"MinimumOSVersion",
@"Path",
@"SignerIdentity",
@"UIDeviceFamily",
@"UIFileSharingEnabled",
@"UIStatusBarHidden",
@"UISupportedInterfaceOrientations",
nil];
NSDictionary *optionsDict = [NSDictionary dictionaryWithObject:a forKey:@"ReturnAttributes"];
CFDictionaryRef options = (CFDictionaryRef)optionsDict;
check_error(AMDeviceLookupApplications(device, options, &result));
CFDictionaryRef app_dict = CFDictionaryGetValue(result, identifier);
assert(app_dict != NULL);
CFStringRef app_path = CFDictionaryGetValue(app_dict, CFSTR("Path"));
assert(app_path != NULL);
CFURLRef url = CFURLCreateWithFileSystemPath(NULL, app_path, kCFURLPOSIXPathStyle, true);
CFRelease(result);
return url;
}
CFStringRef copy_disk_app_identifier(CFURLRef disk_app_url) {
CFURLRef plist_url = CFURLCreateCopyAppendingPathComponent(NULL, disk_app_url, CFSTR("Info.plist"), false);
CFReadStreamRef plist_stream = CFReadStreamCreateWithFile(NULL, plist_url);
if (!CFReadStreamOpen(plist_stream)) {
on_error(@"Cannot read Info.plist file: %@", plist_url);
}
CFPropertyListRef plist = CFPropertyListCreateWithStream(NULL, plist_stream, 0, kCFPropertyListImmutable, NULL, NULL);
CFStringRef bundle_identifier = CFRetain(CFDictionaryGetValue(plist, CFSTR("CFBundleIdentifier")));
CFReadStreamClose(plist_stream);
CFRelease(plist_url);
CFRelease(plist_stream);
CFRelease(plist);
return bundle_identifier;
}
CFStringRef copy_modules_search_paths_pairs(CFStringRef symbols_path, CFStringRef disk_container, CFStringRef device_container_private, CFStringRef device_container_noprivate )
{
CFMutableStringRef res = CFStringCreateMutable(kCFAllocatorDefault, 0);
CFStringAppendFormat(res, NULL, CFSTR("/usr \"%@/usr\""), symbols_path);
CFStringAppendFormat(res, NULL, CFSTR(" /System \"%@/System\""), symbols_path);
CFStringAppendFormat(res, NULL, CFSTR(" \"%@\" \"%@\""), device_container_private, disk_container);
CFStringAppendFormat(res, NULL, CFSTR(" \"%@\" \"%@\""), device_container_noprivate, disk_container);
CFStringAppendFormat(res, NULL, CFSTR(" /Developer \"%@/Developer\""), symbols_path);
return res;
}
CFSocketRef server_socket;
CFWriteStreamRef serverWriteStream = NULL;
int kill_ptree(pid_t root, int signum);
void connect_and_start_session(AMDeviceRef device) {
AMDeviceConnect(device);
assert(AMDeviceIsPaired(device));
check_error(AMDeviceValidatePairing(device));
check_error(AMDeviceStartSession(device));
}
void kill_ptree_inner(pid_t root, int signum, struct kinfo_proc *kp, int kp_len) {
int i;
for (i = 0; i < kp_len; i++) {
if (kp[i].kp_eproc.e_ppid == root) {
kill_ptree_inner(kp[i].kp_proc.p_pid, signum, kp, kp_len);
}
}
if (root != getpid()) {
kill(root, signum);
}
}
int kill_ptree(pid_t root, int signum) {
int mib[3];
size_t len;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_ALL;
if (sysctl(mib, 3, NULL, &len, NULL, 0) == -1) {
return -1;
}
struct kinfo_proc *kp = calloc(1, len);
if (!kp) {
return -1;
}
if (sysctl(mib, 3, kp, &len, NULL, 0) == -1) {
free(kp);
return -1;
}
kill_ptree_inner(root, signum, kp, (int)(len / sizeof(struct kinfo_proc)));
free(kp);
return 0;
}
void killed(int signum) {
// SIGKILL needed to kill lldb, probably a better way to do this.
kill(0, SIGKILL);
_exit(0);
}
void lldb_finished_handler(int signum)
{
int status = 0;
if (waitpid(child, &status, 0) == -1)
perror("waitpid failed");
_exit(WEXITSTATUS(status));
}
pid_t bring_process_to_foreground() {
pid_t fgpid = tcgetpgrp(STDIN_FILENO);
if (setpgid(0, 0) == -1)
perror("setpgid failed");
signal(SIGTTOU, SIG_IGN);
if (tcsetpgrp(STDIN_FILENO, getpid()) == -1)
perror("tcsetpgrp failed");
signal(SIGTTOU, SIG_DFL);
return fgpid;
}
void setup_dummy_pipe_on_stdin(int pfd[2]) {
if (pipe(pfd) == -1)
perror("pipe failed");
if (dup2(pfd[0], STDIN_FILENO) == -1)
perror("dup2 failed");
}
CFStringRef copy_bundle_id(CFURLRef app_url)
{
if (app_url == NULL)
return NULL;
CFURLRef url = CFURLCreateCopyAppendingPathComponent(NULL, app_url, CFSTR("Info.plist"), false);
if (url == NULL)
return NULL;
CFReadStreamRef stream = CFReadStreamCreateWithFile(NULL, url);
CFRelease(url);
if (stream == NULL)
return NULL;
CFPropertyListRef plist = NULL;
if (CFReadStreamOpen(stream) == TRUE) {
plist = CFPropertyListCreateWithStream(NULL, stream, 0,
kCFPropertyListImmutable, NULL, NULL);
}
CFReadStreamClose(stream);
CFRelease(stream);
if (plist == NULL)
return NULL;
const void *value = CFDictionaryGetValue(plist, CFSTR("CFBundleIdentifier"));
CFStringRef bundle_id = NULL;
if (value != NULL)
bundle_id = CFRetain(value);
CFRelease(plist);
return bundle_id;
}
typedef enum { READ_DIR_FILE, READ_DIR_BEFORE_DIR, READ_DIR_AFTER_DIR } read_dir_cb_reason;
void read_dir(AFCConnectionRef afc_conn_p, const char* dir,
void(*callback)(AFCConnectionRef conn, const char *dir, read_dir_cb_reason reason))
{
char *dir_ent;
afc_dictionary* afc_dict_p;
char *key, *val;
int not_dir = 0;
unsigned int code = AFCFileInfoOpen(afc_conn_p, dir, &afc_dict_p);
if (code != 0) {
// there was a problem reading or opening the file to get info on it, abort
return;
}
long long mtime = -1;
long long birthtime = -1;
long size = -1;
long blocks = -1;
long nlink = -1;
NSString * ifmt = nil;
while((AFCKeyValueRead(afc_dict_p,&key,&val) == 0) && key && val) {
if (strcmp(key,"st_ifmt")==0) {
not_dir = strcmp(val,"S_IFDIR");
if (_json_output) {
ifmt = [NSString stringWithUTF8String:val];
} else {
break;
}
} else if (strcmp(key, "st_size") == 0) {
size = atol(val);
} else if (strcmp(key, "st_mtime") == 0) {
mtime = atoll(val);
} else if (strcmp(key, "st_birthtime") == 0) {
birthtime = atoll(val);
} else if (strcmp(key, "st_nlink") == 0) {
nlink = atol(val);
} else if (strcmp(key, "st_blocks") == 0) {
nlink = atol(val);
}
}
AFCKeyValueClose(afc_dict_p);
if (_json_output) {
if (_file_meta_info == nil) {
_file_meta_info = [[NSMutableArray alloc] init];
}
[_file_meta_info addObject: @{@"full_path": [NSString stringWithUTF8String:dir],
@"st_ifmt": ifmt,
@"st_nlink": @(nlink),
@"st_size": @(size),
@"st_blocks": @(blocks),
@"st_mtime": @(mtime),
@"st_birthtime": @(birthtime)}];
}
if (not_dir) {
if (callback) (*callback)(afc_conn_p, dir, READ_DIR_FILE);
return;
}
afc_directory* afc_dir_p;
afc_error_t err = AFCDirectoryOpen(afc_conn_p, dir, &afc_dir_p);
if (err != 0) {
// Couldn't open dir - was probably a file
return;
}
// Call the callback on the directory before processing its
// contents. This is used by copy file callback, which needs to
// create the directory on the host before attempting to copy
// files into it.
if (callback) (*callback)(afc_conn_p, dir, READ_DIR_BEFORE_DIR);
while(true) {
err = AFCDirectoryRead(afc_conn_p, afc_dir_p, &dir_ent);
if (err != 0 || !dir_ent)
break;
if (strcmp(dir_ent, ".") == 0 || strcmp(dir_ent, "..") == 0)
continue;
char* dir_joined = malloc(strlen(dir) + strlen(dir_ent) + 2);
strcpy(dir_joined, dir);
if (dir_joined[strlen(dir)-1] != '/')
strcat(dir_joined, "/");
strcat(dir_joined, dir_ent);
if (!(non_recursively && strcmp(list_root, dir) != 0)) {
read_dir(afc_conn_p, dir_joined, callback);
}
free(dir_joined);
}
AFCDirectoryClose(afc_conn_p, afc_dir_p);
// Call the callback on the directory after processing its
// contents. This is used by the rmtree callback because it needs
// to delete the directory's contents before the directory itself
if (callback) (*callback)(afc_conn_p, dir, READ_DIR_AFTER_DIR);
}