-
Notifications
You must be signed in to change notification settings - Fork 432
/
FBIDBServiceHandler.mm
1700 lines (1566 loc) · 74.1 KB
/
FBIDBServiceHandler.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <string>
#import <idbGRPC/idb.grpc.pb.h>
#import <idbGRPC/idb.pb.h>
#import <grpcpp/grpcpp.h>
#import <FBSimulatorControl/FBSimulatorControl.h>
#import "FBCodeCoverageRequest.h"
#import "FBDataDownloadInput.h"
#import "FBIDBCommandExecutor.h"
#import "FBIDBError.h"
#import "FBIDBPortsConfiguration.h"
#import "FBIDBServiceHandler.h"
#import "FBIDBStorageManager.h"
#import "FBIDBTestOperation.h"
#import "FBIDBXCTestReporter.h"
#import "FBXCTestRunRequest.h"
#import <FBControlCore/FBFuture.h>
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
#pragma mark Private Functions
static NSString *nsstring_from_c_string(const ::std::string& string)
{
return [NSString stringWithUTF8String:string.c_str()];
}
static int BufferOutputSize = 16384; // # 16Kb
static FBCompressionFormat read_compression_format(const idb::Payload_Compression comp)
{
switch (comp) {
case idb::Payload_Compression::Payload_Compression_GZIP:
return FBCompressionFormatGZIP;
case idb::Payload_Compression::Payload_Compression_ZSTD:
return FBCompressionFormatZSTD;
default:
return FBCompressionFormatGZIP;
}
}
template <class T>
static FBFuture<NSNull *> * resolve_next_read(grpc::internal::ReaderInterface<T> *reader)
{
FBMutableFuture<NSNull *> *future = FBMutableFuture.future;
dispatch_queue_t queue = dispatch_queue_create("com.facebook.idb.grpc.reader_wait", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
T stop;
reader->Read(&stop);
[future resolveWithResult:NSNull.null];
});
return future;
}
template <class T>
static id<FBDataConsumer> drain_consumer(grpc::internal::WriterInterface<T> *writer, FBFuture<NSNull *> *done)
{
return [FBBlockDataConsumer asynchronousDataConsumerWithBlock:^(NSData *data) {
if (done.hasCompleted) {
return;
}
T response;
idb::Payload *payload = response.mutable_payload();
payload->set_data(data.bytes, data.length);
writer->Write(response);
}];
}
template <class Write, class Read>
static id<FBDataConsumer> consumer_from_request(grpc::ServerReaderWriter<Write, Read> *stream, Read& request, FBFuture<NSNull *> *done, NSError **error)
{
Read initial;
stream->Read(&initial);
request = initial;
const std::string requestedFilePath = initial.start().file_path();
if (requestedFilePath.length() > 0) {
return [FBFileWriter syncWriterForFilePath:nsstring_from_c_string(requestedFilePath.c_str()) error:error];
}
return drain_consumer(stream, done);
}
template <class T>
static Status drain_writer(FBFuture<FBProcess<NSNull *, NSInputStream *, id> *> *taskFuture, grpc::internal::WriterInterface<T> *stream)
{
NSError *error = nil;
FBProcess<NSNull *, NSInputStream *, id> *task = [taskFuture block:&error];
if (!task) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
NSInputStream *inputStream = task.stdOut;
[inputStream open];
while (true) {
uintptr_t buffer[BufferOutputSize];
NSInteger size = [inputStream read:(uint8_t *)buffer maxLength:BufferOutputSize];
if (size == 0) {
break;
}
if (size < 0) {
return Status::OK;
}
T response;
idb::Payload *payload = response.mutable_payload();
payload->set_data(reinterpret_cast<void *>(buffer), size);
stream->Write(response);
}
[inputStream close];
NSNumber *exitCode = [task.exitCode block:&error];
if (exitCode.integerValue != 0) {
NSString *errorString = [NSString stringWithFormat:@"Draining operation failed with exit code %ld", (long)exitCode.integerValue];
return Status(grpc::StatusCode::INTERNAL, errorString.UTF8String);
}
return Status::OK;
}
template <class T>
static Status respond_file_path(NSURL *source, NSString *destination, grpc::internal::WriterInterface<T> *stream)
{
if (source) {
NSError *error = nil;
if (![NSFileManager.defaultManager moveItemAtPath:source.path toPath:destination error:&error]) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
}
T response;
idb::Payload payload = response.payload();
payload.set_file_path(destination.UTF8String);
stream->Write(response);
return Status::OK;
}
template <class T>
static FBProcessInput<NSOutputStream *> *pipe_to_input(const idb::Payload initial, grpc::ServerReader<T> *reader)
{
const std::string initialData = initial.data();
FBProcessInput<NSOutputStream *> *input = [FBProcessInput inputFromStream];
NSOutputStream *stream = input.contents;
dispatch_queue_t queue = dispatch_queue_create("com.facebook.idb.processinput", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
T request;
[stream open];
[stream write:(const uint8_t *)initialData.c_str() maxLength:initialData.length()];
while (reader->Read(&request)) {
const auto tarData = request.payload().data();
[stream write:(const uint8_t *)tarData.c_str() maxLength:tarData.length()];
}
[stream close];
});
return input;
}
static FBProcessInput<NSOutputStream *> *pipe_to_input_output(const idb::Payload initial, grpc::ServerReaderWriter<idb::InstallResponse, idb::InstallRequest> *stream)
{
const std::string initialData = initial.data();
FBProcessInput<NSOutputStream *> *input = [FBProcessInput inputFromStream];
NSOutputStream *appStream = input.contents;
dispatch_queue_t queue = dispatch_queue_create("com.facebook.idb.processinput", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
idb::InstallRequest request;
[appStream open];
[appStream write:(const uint8_t *)initialData.c_str() maxLength:initialData.length()];
while (stream->Read(&request)) {
const auto tarData = request.payload().data();
[appStream write:(const uint8_t *)tarData.c_str() maxLength:tarData.length()];
}
[appStream close];
});
return input;
}
static id<FBDataConsumer, FBDataConsumerLifecycle> pipe_output(const idb::ProcessOutput_Interface interface, dispatch_queue_t queue, grpc::ServerReaderWriter<idb::LaunchResponse, idb::LaunchRequest> *stream)
{
id<FBDataConsumer, FBDataConsumerLifecycle> consumer = [FBBlockDataConsumer asynchronousDataConsumerOnQueue:queue consumer:^(NSData *data) {
idb::LaunchResponse response;
idb::ProcessOutput *output = response.mutable_output();
output->set_data(data.bytes, data.length);
output->set_interface(interface);
stream->Write(response);
}];
return consumer;
}
template <class T>
static FBFuture<NSArray<NSURL *> *> *filepaths_from_stream(const idb::Payload initial, grpc::ServerReader<T> *reader)
{
NSMutableArray<NSURL *> *filePaths = NSMutableArray.array;
FBMutableFuture<NSArray<NSURL *> *> *future = FBMutableFuture.future;
dispatch_queue_t queue = dispatch_queue_create("com.facebook.idb.processinput", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
T request;
[filePaths addObject:[NSURL fileURLWithPath:nsstring_from_c_string(initial.file_path())]];
while (reader->Read(&request)) {
[filePaths addObject:[NSURL fileURLWithPath:nsstring_from_c_string(request.payload().file_path())]];
}
[future resolveWithResult:filePaths];
});
return future;
}
static FBFutureContext<NSArray<NSURL *> *> *filepaths_from_tar(FBTemporaryDirectory *temporaryDirectory, FBProcessInput<NSOutputStream *> *input, bool extract_from_subdir, FBCompressionFormat compression, id<FBControlCoreLogger> logger)
{
dispatch_queue_t queue = dispatch_queue_create("com.facebook.idb.processinput", DISPATCH_QUEUE_SERIAL);
FBFutureContext<NSURL *> *tarContext = [temporaryDirectory withArchiveExtractedFromStream:input compression:compression];
if (extract_from_subdir) {
// Extract from subdirectories
return [temporaryDirectory filesFromSubdirs:tarContext];
} else {
// Extract from the top level
return [tarContext onQueue:queue pend:^FBFuture<NSArray<NSURL *> *> *(NSURL *extractionDir) {
NSError *error;
NSArray<NSURL *> *paths = [NSFileManager.defaultManager contentsOfDirectoryAtURL:extractionDir includingPropertiesForKeys:@[NSURLIsDirectoryKey] options:0 error:&error];
if (!paths) {
return [FBFuture futureWithError:error];
}
return [FBFuture futureWithResult:paths];
}];
}
}
template<class T>
static FBFutureContext<NSArray<NSURL *> *> *filepaths_from_reader(FBTemporaryDirectory *temporaryDirectory, grpc::ServerReader<T> *reader, bool extract_from_subdir, id<FBControlCoreLogger> logger)
{
T request;
reader->Read(&request);
idb::Payload firstPayload = request.payload();
// The first item in the payload stream may be the compression format, if it's not assume the default.
FBCompressionFormat compression = FBCompressionFormatGZIP;
if (firstPayload.source_case() == idb::Payload::kCompression) {
compression = read_compression_format(firstPayload.compression());
reader->Read(&request);
firstPayload = request.payload();
}
switch (firstPayload.source_case()) {
case idb::Payload::kData: {
FBProcessInput<NSOutputStream *> *input = pipe_to_input(firstPayload, reader);
return filepaths_from_tar(temporaryDirectory, input, extract_from_subdir, compression, logger);
}
case idb::Payload::kFilePath: {
return [FBFutureContext futureContextWithFuture:filepaths_from_stream(firstPayload, reader)];
}
default: {
return [FBFutureContext futureContextWithError:[FBControlCoreError errorForFormat:@"Unrecognised initial payload type %u", firstPayload.source_case()]];
}
}
}
static NSDictionary<NSString *, NSString *> *extract_str_dict(const ::google::protobuf::Map<::std::string, ::std::string >& iterator)
{
NSMutableDictionary<NSString *, NSString *> *environment = NSMutableDictionary.dictionary;
for (auto item : iterator) {
environment[nsstring_from_c_string(item.first)] = nsstring_from_c_string(item.second);
}
return environment;
}
template <class T>
static NSArray<NSString *> *extract_string_array(T &input)
{
NSMutableArray<NSString *> *arguments = NSMutableArray.array;
for (auto value : input) {
[arguments addObject:nsstring_from_c_string(value)];
}
return arguments;
}
static FBCodeCoverageRequest *extract_code_coverage(const idb::XctestRunRequest *request) {
if (request->has_code_coverage()) {
const idb::XctestRunRequest::CodeCoverage codeCoverage = request->code_coverage();
FBCodeCoverageFormat format = FBCodeCoverageExported;
switch (codeCoverage.format()) {
case idb::XctestRunRequest_CodeCoverage_Format::XctestRunRequest_CodeCoverage_Format_RAW:
format = FBCodeCoverageRaw;
break;
case idb::XctestRunRequest_CodeCoverage_Format::XctestRunRequest_CodeCoverage_Format_EXPORTED:
default:
format = FBCodeCoverageExported;
break;
}
return [[FBCodeCoverageRequest alloc] initWithCollect:codeCoverage.collect() format:format];
} else {
// fallback to deprecated request field for backwards compatibility
return [[FBCodeCoverageRequest alloc] initWithCollect:request->collect_coverage() format:FBCodeCoverageExported];
}
}
static FBXCTestRunRequest *convert_xctest_request(const idb::XctestRunRequest *request)
{
NSNumber *testTimeout = @(request->timeout());
NSArray<NSString *> *arguments = extract_string_array(request->arguments());
NSDictionary<NSString *, NSString *> *environment = extract_str_dict(request->environment());
NSMutableSet<NSString *> *testsToRun = nil;
NSMutableSet<NSString *> *testsToSkip = NSMutableSet.set;
NSString *testBundleID = nsstring_from_c_string(request->test_bundle_id());
BOOL reportActivities = request->report_activities();
BOOL collectLogs = request->collect_logs();
BOOL waitForDebugger = request->wait_for_debugger();
BOOL reportAttachments = request->report_attachments();
FBCodeCoverageRequest *coverage = extract_code_coverage(request);
if (request->tests_to_run_size() > 0) {
testsToRun = NSMutableSet.set;
for (int i = 0; i < request->tests_to_run_size(); i++) {
const std::string value = request->tests_to_run(i);
[testsToRun addObject:nsstring_from_c_string(value)];
}
}
for (int i = 0; i < request->tests_to_skip_size(); i++) {
const std::string value = request->tests_to_skip(i);
[testsToSkip addObject:nsstring_from_c_string(value)];
}
switch (request->mode().mode_case()) {
case idb::XctestRunRequest_Mode::kLogic: {
return [FBXCTestRunRequest logicTestWithTestBundleID:testBundleID environment:environment arguments:arguments testsToRun:testsToRun testsToSkip:testsToSkip testTimeout:testTimeout reportActivities:reportActivities reportAttachments:reportAttachments coverageRequest:coverage collectLogs:collectLogs waitForDebugger:waitForDebugger];
}
case idb::XctestRunRequest_Mode::kApplication: {
const idb::XctestRunRequest::Application application = request->mode().application();
NSString *appBundleID = nsstring_from_c_string(application.app_bundle_id());
return [FBXCTestRunRequest applicationTestWithTestBundleID:testBundleID appBundleID:appBundleID environment:environment arguments:arguments testsToRun:testsToRun testsToSkip:testsToSkip testTimeout:testTimeout reportActivities:reportActivities reportAttachments:reportAttachments coverageRequest:coverage collectLogs:collectLogs waitForDebugger:waitForDebugger];
}
case idb::XctestRunRequest_Mode::kUi: {
const idb::XctestRunRequest::UI ui = request->mode().ui();
NSString *appBundleID = nsstring_from_c_string(ui.app_bundle_id());
NSString *testHostAppBundleID = nsstring_from_c_string(ui.test_host_app_bundle_id());
return [FBXCTestRunRequest uiTestWithTestBundleID:testBundleID appBundleID:appBundleID testHostAppBundleID:testHostAppBundleID environment:environment arguments:arguments testsToRun:testsToRun testsToSkip:testsToSkip testTimeout:testTimeout reportActivities:reportActivities reportAttachments:reportAttachments coverageRequest:coverage collectLogs:collectLogs];
}
default:
return nil;
}
}
static NSPredicate *nspredicate_from_crash_log_query(const idb::CrashLogQuery *request)
{
NSMutableArray<NSPredicate *> *subpredicates = [NSMutableArray array];
if (request->since()) {
[subpredicates addObject:[FBCrashLogInfo predicateNewerThanDate:[NSDate dateWithTimeIntervalSince1970:request->since()]]];
}
if (request->before()) {
[subpredicates addObject:[FBCrashLogInfo predicateOlderThanDate:[NSDate dateWithTimeIntervalSince1970:request->before()]]];
}
NSString *bundle_id = nsstring_from_c_string(request->bundle_id());
if (bundle_id.length) {
[subpredicates addObject:[FBCrashLogInfo predicateForIdentifier:bundle_id]];
}
NSString *name = nsstring_from_c_string(request->name());
if (name.length) {
[subpredicates addObject:[FBCrashLogInfo predicateForName:name]];
}
if (subpredicates.count == 0) {
return [NSPredicate predicateWithValue:YES];
}
return [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
}
static void fill_crash_log_info(idb::CrashLogInfo *info, const FBCrashLogInfo *crash)
{
info->set_name(crash.name.UTF8String);
info->set_process_name(crash.processName.UTF8String);
info->set_parent_process_name(crash.parentProcessName.UTF8String);
info->set_process_identifier(crash.processIdentifier);
info->set_parent_process_identifier(crash.parentProcessIdentifier);
info->set_timestamp(crash.date.timeIntervalSince1970);
}
static void fill_crash_log_response(idb::CrashLogResponse *response, const NSArray<FBCrashLogInfo *> *crashes)
{
for (FBCrashLogInfo *crash in crashes) {
idb::CrashLogInfo *info = response->add_list();
fill_crash_log_info(info, crash);
}
}
static FBSimulatorHIDEvent *translate_event(idb::HIDEvent &event, NSError **error)
{
if (event.has_press()) {
idb::HIDEvent_HIDDirection direction = event.press().direction();
idb::HIDEvent_HIDPressAction action = event.press().action();
if (action.has_key()) {
int keycode = (int)action.key().keycode();
if (direction == idb::HIDEvent_HIDDirection_DOWN) {
return [FBSimulatorHIDEvent keyDown:keycode];
} else if (direction == idb::HIDEvent_HIDDirection_UP) {
return [FBSimulatorHIDEvent keyUp:keycode];
}
} else if (action.has_button()) {
// Need to convert between the objc enum that starts at 1 and the grpc enum that starts at 0
FBSimulatorHIDButton button = (FBSimulatorHIDButton)(action.button().button() + 1);
if (direction == idb::HIDEvent_HIDDirection_DOWN) {
return [FBSimulatorHIDEvent buttonDown:button];
} else if (direction == idb::HIDEvent_HIDDirection_UP) {
return [FBSimulatorHIDEvent buttonUp:button];
}
} else if (action.has_touch()) {
int x = action.touch().point().x();
int y = action.touch().point().y();
if (direction == idb::HIDEvent_HIDDirection_DOWN) {
return [FBSimulatorHIDEvent touchDownAtX:x y:y];
} else if (direction == idb::HIDEvent_HIDDirection_UP) {
return [FBSimulatorHIDEvent touchUpAtX:x y:y];
}
}
} else if (event.has_swipe()) {
return [FBSimulatorHIDEvent swipe:event.swipe().start().x() yStart:event.swipe().start().y() xEnd:event.swipe().end().x() yEnd:event.swipe().end().y() delta:event.swipe().delta() duration:event.swipe().duration()];
} else if (event.has_delay()) {
return [FBSimulatorHIDEvent delay:event.delay().duration()];
}
if (error) {
*error = [FBControlCoreError errorForDescription:@"Can't decode event"];
}
return nil;
}
static FBInstrumentsConfiguration *translate_instruments_configuration(idb::InstrumentsRunRequest_Start request, FBIDBStorageManager *storageManager)
{
return [FBInstrumentsConfiguration
configurationWithTemplateName:nsstring_from_c_string(request.template_name())
targetApplication:nsstring_from_c_string(request.app_bundle_id())
appEnvironment:extract_str_dict(request.environment())
appArguments:extract_string_array(request.arguments())
toolArguments:[storageManager interpolateArgumentReplacements:extract_string_array(request.tool_arguments())]
timings:[FBInstrumentsTimings
timingsWithTerminateTimeout:request.timings().terminate_timeout() ?: DefaultInstrumentsTerminateTimeout
launchRetryTimeout:request.timings().launch_retry_timeout() ?: DefaultInstrumentsLaunchRetryTimeout
launchErrorTimeout:request.timings().launch_error_timeout() ?: DefaultInstrumentsLaunchErrorTimeout
operationDuration:request.timings().operation_duration() ?: DefaultInstrumentsOperationDuration
]
];
}
static FBXCTraceRecordConfiguration *translate_xctrace_record_configuration(idb::XctraceRecordRequest_Start request)
{
return [FBXCTraceRecordConfiguration
RecordWithTemplateName:nsstring_from_c_string(request.template_name())
timeLimit:request.time_limit() ?: DefaultXCTraceRecordOperationTimeLimit
package:nsstring_from_c_string(request.package())
allProcesses:request.target().all_processes()
processToAttach:nsstring_from_c_string(request.target().process_to_attach())
processToLaunch:nsstring_from_c_string(request.target().launch_process().process_to_launch())
launchArgs:extract_string_array(request.target().launch_process().launch_args())
targetStdin:nsstring_from_c_string(request.target().launch_process().target_stdin())
targetStdout:nsstring_from_c_string(request.target().launch_process().target_stdout())
processEnv:extract_str_dict(request.target().launch_process().process_env())
shim:nil
];
}
static idb::DebugServerResponse translate_debugserver_status(id<FBDebugServer> debugServer)
{
idb::DebugServerResponse response;
idb::DebugServerResponse::Status *status = response.mutable_status();
if (debugServer) {
for (NSString *command in debugServer.lldbBootstrapCommands) {
status->add_lldb_bootstrap_commands(command.UTF8String);
}
}
return response;
}
static NSString *file_container(idb::FileContainer container)
{
switch (container.kind()) {
case idb::FileContainer_Kind_ROOT:
return FBFileContainerKindRoot;
case idb::FileContainer_Kind_MEDIA:
return FBFileContainerKindMedia;
case idb::FileContainer_Kind_CRASHES:
return FBFileContainerKindCrashes;
case idb::FileContainer_Kind_PROVISIONING_PROFILES:
return FBFileContainerKindProvisioningProfiles;
case idb::FileContainer_Kind_MDM_PROFILES:
return FBFileContainerKindMDMProfiles;
case idb::FileContainer_Kind_SPRINGBOARD_ICONS:
return FBFileContainerKindSpringboardIcons;
case idb::FileContainer_Kind_WALLPAPER:
return FBFileContainerKindWallpaper;
case idb::FileContainer_Kind_DISK_IMAGES:
return FBFileContainerKindDiskImages;
case idb::FileContainer_Kind_GROUP_CONTAINER:
return FBFileContainerKindGroup;
case idb::FileContainer_Kind_APPLICATION_CONTAINER:
return FBFileContainerKindApplication;
case idb::FileContainer_Kind_AUXILLARY:
return FBFileContainerKindAuxillary;
case idb::FileContainer_Kind_XCTEST:
return FBFileContainerKindXctest;
case idb::FileContainer_Kind_DYLIB:
return FBFileContainerKindDylib;
case idb::FileContainer_Kind_DSYM:
return FBFileContainerKindDsym;
case idb::FileContainer_Kind_FRAMEWORK:
return FBFileContainerKindFramework;
case idb::FileContainer_Kind_SYMBOLS:
return FBFileContainerKindSymbols;
case idb::FileContainer_Kind_APPLICATION:
default:
return nsstring_from_c_string(container.bundle_id());
}
}
static void populate_companion_info(idb::CompanionInfo *info, id<FBEventReporter> reporter, id<FBiOSTarget> target)
{
info->set_udid(target.udid.UTF8String);
NSDictionary<NSString *, NSString *> *metadata = reporter.metadata ?: @{};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:metadata options:0 error:&error];
if (data) {
info->set_metadata(data.bytes, data.length);
}
}
#pragma mark Constructors
FBIDBServiceHandler::FBIDBServiceHandler(FBIDBCommandExecutor *commandExecutor, id<FBiOSTarget> target, id<FBEventReporter> eventReporter)
{
_commandExecutor = commandExecutor;
_target = target;
_eventReporter = eventReporter;
}
FBIDBServiceHandler::FBIDBServiceHandler(const FBIDBServiceHandler &c)
{
_commandExecutor = c._commandExecutor;
_target = c._target;
_eventReporter = c._eventReporter;
}
#pragma mark Handled Methods
FBFuture<FBInstalledArtifact *> *FBIDBServiceHandler::install_future(const idb::InstallRequest_Destination destination, grpc::ServerReaderWriter<idb::InstallResponse, idb::InstallRequest> *stream)
{@autoreleasepool{
// Read the initial request
idb::InstallRequest request;
stream->Read(&request);
// The name hint may be provided, if it is not then default to some UUID, then advance the stream.
NSString *name = NSUUID.UUID.UUIDString;
if (request.value_case() == idb::InstallRequest::ValueCase::kNameHint) {
name = nsstring_from_c_string(request.name_hint());
stream->Read(&request);
}
// A debuggable flag may be provided, if it is, then obtain that value, then advance that stream.
BOOL makeDebuggable = NO;
if (request.value_case() == idb::InstallRequest::ValueCase::kMakeDebuggable) {
makeDebuggable = (request.make_debuggable() == true);
stream->Read(&request);
}
// A bundle id might be provided, if it is, then obtain the installed app if exists, then advance that stream.
// It can be used to determine where debug symbols should be linked
NSString *bundleID = nil;
if (request.value_case() == idb::InstallRequest::ValueCase::kBundleId) {
bundleID = nsstring_from_c_string(request.bundle_id());
stream->Read(&request);
}
// Now that we've read the header, the next item in the stream must be the payload.
if (request.value_case() != idb::InstallRequest::ValueCase::kPayload) {
return [[FBIDBError
describeFormat:@"Expected the next item in the stream to be a payload"]
failFuture];
}
// The first item in the payload stream may be the compression format, if it's not assume the default.
FBCompressionFormat compression = FBCompressionFormatGZIP;
idb::Payload payload = request.payload();
if (payload.source_case() == idb::Payload::kCompression) {
compression = read_compression_format(payload.compression());
stream->Read(&request);
payload = request.payload();
}
switch (payload.source_case()) {
case idb::Payload::kData: {
FBProcessInput<NSOutputStream *> *dataStream = pipe_to_input_output(payload, stream);
switch (destination) {
case idb::InstallRequest_Destination::InstallRequest_Destination_APP:
return [_commandExecutor install_app_stream:dataStream compression:compression make_debuggable:makeDebuggable];
case idb::InstallRequest_Destination::InstallRequest_Destination_XCTEST:
return [_commandExecutor install_xctest_app_stream:dataStream];
case idb::InstallRequest_Destination::InstallRequest_Destination_DSYM:
return [_commandExecutor install_dsym_stream:dataStream linkToApp:bundleID];
case idb::InstallRequest_Destination::InstallRequest_Destination_DYLIB:
return [_commandExecutor install_dylib_stream:dataStream name:name];
case idb::InstallRequest_Destination::InstallRequest_Destination_FRAMEWORK:
return [_commandExecutor install_framework_stream:dataStream];
default:
return nil;
}
}
case idb::Payload::kUrl: {
NSURL *url = [NSURL URLWithString:[NSString stringWithCString:payload.url().c_str() encoding:NSUTF8StringEncoding]];
FBDataDownloadInput *download = [FBDataDownloadInput dataDownloadWithURL:url logger:_target.logger];
switch (destination) {
case idb::InstallRequest_Destination::InstallRequest_Destination_APP:
return [_commandExecutor install_app_stream:download.input compression:compression make_debuggable:makeDebuggable];
case idb::InstallRequest_Destination::InstallRequest_Destination_XCTEST:
return [_commandExecutor install_xctest_app_stream:download.input];
case idb::InstallRequest_Destination::InstallRequest_Destination_DSYM:
return [_commandExecutor install_dsym_stream:download.input linkToApp:bundleID];
case idb::InstallRequest_Destination::InstallRequest_Destination_DYLIB:
return [_commandExecutor install_dylib_stream:download.input name:name];
case idb::InstallRequest_Destination::InstallRequest_Destination_FRAMEWORK:
return [_commandExecutor install_framework_stream:download.input];
default:
return nil;
}
}
case idb::Payload::kFilePath: {
NSString *filePath = nsstring_from_c_string(payload.file_path());
switch (destination) {
case idb::InstallRequest_Destination::InstallRequest_Destination_APP:
return [_commandExecutor install_app_file_path:filePath make_debuggable:makeDebuggable];
case idb::InstallRequest_Destination::InstallRequest_Destination_XCTEST:
return [_commandExecutor install_xctest_app_file_path:filePath];
case idb::InstallRequest_Destination::InstallRequest_Destination_DSYM:
return [_commandExecutor install_dsym_file_path:filePath linkToApp:bundleID];
case idb::InstallRequest_Destination::InstallRequest_Destination_DYLIB:
return [_commandExecutor install_dylib_file_path:filePath];
case idb::InstallRequest_Destination::InstallRequest_Destination_FRAMEWORK:
return [_commandExecutor install_framework_file_path:filePath];
default:
return nil;
}
}
default:
return nil;
}
}}
Status FBIDBServiceHandler::list_apps(ServerContext *context, const idb::ListAppsRequest *request, idb::ListAppsResponse *response)
{@autoreleasepool{
NSError *error = nil;
NSSet<NSString *> *persistedBundleIDs = _commandExecutor.storageManager.application.persistedBundleIDs;
BOOL fetchAppProcessState = request->suppress_process_state() == false;
NSDictionary<FBInstalledApplication *, id> *apps = [[_commandExecutor list_apps:fetchAppProcessState] block:&error];
for (FBInstalledApplication *app in apps.allKeys) {
idb::InstalledAppInfo *appInfo = response->add_apps();
appInfo->set_bundle_id(app.bundle.identifier.UTF8String ?: "");
appInfo->set_name(app.bundle.name.UTF8String ?: "");
appInfo->set_install_type(app.installTypeString.UTF8String);
for (NSString *architecture in app.bundle.binary.architectures) {
appInfo->add_architectures(architecture.UTF8String);
}
id processState = apps[app];
if ([processState isKindOfClass:NSNumber.class]) {
appInfo->set_process_state(idb::InstalledAppInfo_AppProcessState_RUNNING);
appInfo->set_process_identifier([processState unsignedIntegerValue]);
} else {
appInfo->set_process_state(idb::InstalledAppInfo_AppProcessState_UNKNOWN);
}
appInfo->set_debuggable(app.installType == FBApplicationInstallTypeUserDevelopment && [persistedBundleIDs containsObject:app.bundle.identifier]);
}
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}}
Status FBIDBServiceHandler::open_url(ServerContext *context, const idb::OpenUrlRequest *request, idb::OpenUrlRequest *response)
{@autoreleasepool{
NSError *error = nil;
[[_commandExecutor open_url:nsstring_from_c_string(request->url())] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, [error.localizedDescription UTF8String]);
}
return Status::OK;
}}
Status FBIDBServiceHandler::install(ServerContext *context, grpc::ServerReaderWriter<idb::InstallResponse, idb::InstallRequest> *stream)
{@autoreleasepool{
idb::InstallRequest request;
stream->Read(&request);
idb::InstallRequest_Destination destination = request.destination();
NSError *error = nil;
FBInstalledArtifact *artifact = [install_future(destination, stream) block:&error];
if (!artifact) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String ?: "An internal error occured when installing");
}
idb::InstallResponse response;
response.set_name(artifact.name.UTF8String);
response.set_uuid(artifact.uuid.UUIDString.UTF8String ?: "");
stream->Write(response);
return Status::OK;
}}
Status FBIDBServiceHandler::screenshot(ServerContext *context, const idb::ScreenshotRequest *request, idb::ScreenshotResponse *response)
{@autoreleasepool{
NSError *error = nil;
NSData *screenshot = [[_commandExecutor take_screenshot:FBScreenshotFormatPNG] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
response->set_image_data(screenshot.bytes, screenshot.length);
return Status::OK;
}}
Status FBIDBServiceHandler::focus(ServerContext *context, const idb::FocusRequest *request, idb::FocusResponse *response)
{@autoreleasepool{
NSError *error = nil;
[[_commandExecutor focus] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, [error.localizedDescription UTF8String]);
}
return Status::OK;
}}
Status FBIDBServiceHandler::accessibility_info(ServerContext *context, const idb::AccessibilityInfoRequest *request, idb::AccessibilityInfoResponse *response)
{@autoreleasepool{
NSError *error = nil;
NSValue *point = nil;
if (request->has_point()) {
point = [NSValue valueWithPoint:CGPointMake(request->point().x(), request->point().y())];
}
BOOL nestedFormat = request->format() == idb::AccessibilityInfoRequest_Format::AccessibilityInfoRequest_Format_NESTED;
NSArray<NSDictionary<NSString *, id> *> *info = [[_commandExecutor accessibility_info_at_point:point nestedFormat:nestedFormat] block:&error];
if (!info) {
return Status(grpc::StatusCode::INTERNAL, [error.localizedDescription UTF8String]);
}
NSData *data = [NSJSONSerialization dataWithJSONObject:info options:0 error:&error];
if (!data) {
return Status(grpc::StatusCode::INTERNAL, [error.localizedDescription UTF8String]);
}
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
response->set_json([json UTF8String]);
return Status::OK;
}}
Status FBIDBServiceHandler::uninstall(ServerContext *context, const idb::UninstallRequest *request, idb::UninstallResponse *response)
{@autoreleasepool{
NSError *error = nil;
[[_commandExecutor uninstall_application:nsstring_from_c_string(request->bundle_id())] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, [error.localizedDescription UTF8String]);
}
return Status::OK;
}}
Status FBIDBServiceHandler::mkdir(grpc::ServerContext *context, const idb::MkdirRequest *request, idb::MkdirResponse *response)
{@autoreleasepool{
NSError *error = nil;
[[_commandExecutor create_directory:nsstring_from_c_string(request->path()) containerType:file_container(request->container())] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}}
Status FBIDBServiceHandler::mv(grpc::ServerContext *context, const idb::MvRequest *request, idb::MvResponse *response)
{@autoreleasepool{
NSError *error = nil;
NSMutableArray<NSString *> *originalPaths = NSMutableArray.array;
for (int j = 0; j < request->src_paths_size(); j++) {
[originalPaths addObject:nsstring_from_c_string(request->src_paths(j))];
}
[[_commandExecutor move_paths:originalPaths to_path:nsstring_from_c_string(request->dst_path()) containerType:file_container(request->container())] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}}
Status FBIDBServiceHandler::rm(grpc::ServerContext *context, const idb::RmRequest *request, idb::RmResponse *response)
{@autoreleasepool{
NSError *error = nil;
NSMutableArray<NSString *> *paths = NSMutableArray.array;
for (int j = 0; j < request->paths_size(); j++) {
[paths addObject:nsstring_from_c_string(request->paths(j))];
}
[[_commandExecutor remove_paths:paths containerType:file_container(request->container())] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}}
Status FBIDBServiceHandler::ls(grpc::ServerContext *context, const idb::LsRequest *request, idb::LsResponse *response)
{@autoreleasepool{
NSError *error = nil;
if (request->paths_size() > 0) {
NSArray<NSString *> *inputPaths = extract_string_array(request->paths());
NSDictionary<NSString *, NSArray<NSString *> *> *pathsToPaths = [[_commandExecutor list_paths:inputPaths containerType:file_container(request->container())] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
for (NSString *containerPath in pathsToPaths.allKeys) {
NSArray<NSString *> *paths = pathsToPaths[containerPath];
idb::FileListing *listing = response->add_listings();
idb::FileInfo *parent = listing->mutable_parent();
parent->set_path(containerPath.UTF8String);
for (NSString *path in paths) {
idb::FileInfo *info = listing->add_files();
info->set_path(path.UTF8String);
}
}
} else {
// Back-compat with single paths
NSArray<NSString *> *paths = [[_commandExecutor list_path:nsstring_from_c_string(request->path()) containerType:file_container(request->container())] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
for (NSString *path in paths) {
idb::FileInfo *info = response->add_files();
info->set_path(path.UTF8String);
}
}
return Status::OK;
}}
Status FBIDBServiceHandler::approve(ServerContext *context, const idb::ApproveRequest *request, idb::ApproveResponse *response)
{@autoreleasepool{
NSError *error = nil;
NSDictionary<NSNumber *, FBSettingsApprovalService> *mapping = @{
@((int)idb::ApproveRequest_Permission::ApproveRequest_Permission_PHOTOS): FBSettingsApprovalServicePhotos,
@((int)idb::ApproveRequest_Permission::ApproveRequest_Permission_CAMERA): FBSettingsApprovalServiceCamera,
@((int)idb::ApproveRequest_Permission::ApproveRequest_Permission_CONTACTS): FBSettingsApprovalServiceContacts,
@((int)idb::ApproveRequest_Permission::ApproveRequest_Permission_URL): FBSettingsApprovalServiceUrl,
@((int)idb::ApproveRequest_Permission::ApproveRequest_Permission_LOCATION): FBSettingsApprovalServiceLocation,
@((int)idb::ApproveRequest_Permission::ApproveRequest_Permission_NOTIFICATION): FBSettingsApprovalServiceNotification,
};
NSMutableSet<FBSettingsApprovalService> *services = NSMutableSet.set;
for (int j = 0; j < request->permissions_size(); j++) {
idb::ApproveRequest_Permission permission = request->permissions(j);
[services addObject:mapping[@(permission)]];
}
if ([services containsObject:FBSettingsApprovalServiceUrl]) {
[services removeObject:FBSettingsApprovalServiceUrl];
[[_commandExecutor approve_deeplink:nsstring_from_c_string(request->scheme())
for_application:nsstring_from_c_string(request->bundle_id())] block:&error];
}
if ([services count] > 0 && !error) {
[[_commandExecutor approve:services for_application:nsstring_from_c_string(request->bundle_id())] block:&error];
}
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}}
Status FBIDBServiceHandler::clear_keychain(ServerContext *context, const idb::ClearKeychainRequest *request, idb::ClearKeychainResponse *response)
{@autoreleasepool{
NSError *error = nil;
[[_commandExecutor clear_keychain] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, [error.localizedDescription UTF8String]);
}
return Status::OK;
}}
Status FBIDBServiceHandler::terminate(ServerContext *context, const idb::TerminateRequest *request, idb::TerminateResponse *response)
{@autoreleasepool{
NSError *error = nil;
[[_commandExecutor kill_application:nsstring_from_c_string(request->bundle_id())] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}}
Status FBIDBServiceHandler::hid(grpc::ServerContext *context, grpc::ServerReader<idb::HIDEvent> *reader, idb::HIDResponse *response)
{@autoreleasepool{
NSError *error = nil;
idb::HIDEvent grpcEvent;
while (reader->Read(&grpcEvent)) {
FBSimulatorHIDEvent *event = translate_event(grpcEvent, &error);
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
[[_commandExecutor hid:event] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
}
return Status::OK;
}}
Status FBIDBServiceHandler::set_location(ServerContext *context, const idb::SetLocationRequest *request, idb::SetLocationResponse *response)
{@autoreleasepool{
NSError *error = nil;
[[_commandExecutor set_location:request->location().latitude() longitude:request->location().longitude()] block:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, [error.localizedDescription UTF8String]);
}
return Status::OK;
}}
Status FBIDBServiceHandler::setting(ServerContext* context, const idb::SettingRequest* request, idb::SettingResponse* response)
{@autoreleasepool{
switch (request->setting_case()) {
case idb::SettingRequest::SettingCase::kHardwareKeyboard: {
NSError *error = nil;
NSNull *result = [[_commandExecutor set_hardware_keyboard_enabled:request->hardwarekeyboard().enabled()] await:&error];
if (!result) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}
case idb::SettingRequest::SettingCase::kStringSetting: {
idb::SettingRequest::StringSetting stringSetting = request->stringsetting();
switch (stringSetting.setting()) {
case idb::Setting::LOCALE: {
NSError *error = nil;
NSNull *result = [[_commandExecutor set_locale_with_identifier:nsstring_from_c_string(stringSetting.value().c_str())] await:&error];
if (!result) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}
case idb::Setting::ANY: {
NSError *error = nil;
NSString *name = nsstring_from_c_string(stringSetting.name().c_str());
NSString *value = nsstring_from_c_string(stringSetting.value().c_str());
NSString *domain = nil;
if (stringSetting.domain().length() > 0) {
domain = nsstring_from_c_string(stringSetting.domain().c_str());
}
NSNull *result = [[_commandExecutor set_preference:name value:value domain:domain] await:&error];
if (!result) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
return Status::OK;
}
default:
return Status(grpc::StatusCode::INTERNAL, "Unknown setting case");
}
}
default:
return Status(grpc::StatusCode::INTERNAL, "Unknown setting case");
}
}}
Status FBIDBServiceHandler::get_setting(ServerContext* context, const idb::GetSettingRequest* request, idb::GetSettingResponse* response)
{@autoreleasepool{
switch (request->setting()) {
case idb::Setting::LOCALE: {
NSError *error = nil;
NSString *localeIdentifier = [[_commandExecutor get_current_locale_identifier] await:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
response->set_value(localeIdentifier.UTF8String);
return Status::OK;
}
case idb::Setting::ANY: {
NSError *error = nil;
NSString *name = nsstring_from_c_string(request->name().c_str());
NSString *domain = nil;
if (request->domain().length() > 0) {
domain = nsstring_from_c_string(request->domain().c_str());
}
NSString *value = [[_commandExecutor get_preference:name domain:domain] await:&error];
if (error) {
return Status(grpc::StatusCode::INTERNAL, error.localizedDescription.UTF8String);
}
response->set_value(value.UTF8String);
return Status::OK;
}
default:
return Status(grpc::StatusCode::INTERNAL, "Unknown setting case");
}
}}
Status FBIDBServiceHandler::list_settings(ServerContext* context, const idb::ListSettingRequest* request, idb::ListSettingResponse* response)
{@autoreleasepool{
switch (request->setting()) {
case idb::Setting::LOCALE: {
NSArray<NSString *> *localeIdentifiers = _commandExecutor.list_locale_identifiers;
auto values = response->mutable_values();
for (NSString *localeIdentifier in localeIdentifiers) {
values->Add(localeIdentifier.UTF8String);
}
return Status::OK;
}
default:
return Status(grpc::StatusCode::INTERNAL, "Unknown setting case");
}
}}
Status FBIDBServiceHandler::contacts_update(ServerContext *context, const idb::ContactsUpdateRequest *request, idb::ContactsUpdateResponse *response)
{@autoreleasepool{
NSError *error = nil;