-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathFPRNSURLSessionInstrument.m
718 lines (668 loc) · 34.6 KB
/
FPRNSURLSessionInstrument.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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** NSURLSession is a class cluster and the type of class you get back from the various
* initialization methods might not actually be NSURLSession. Inside those methods, this class
* keeps track of seen NSURLSession subclasses and lazily swizzles them if they've not been seen.
* Consequently, swizzling needs to occur on a serial queue for thread safety.
*/
#import "FirebasePerformance/Sources/Instrumentation/Network/FPRNSURLSessionInstrument.h"
#import "FirebasePerformance/Sources/Instrumentation/Network/FPRNSURLSessionInstrument_Private.h"
#import "FirebasePerformance/Sources/Common/FPRDiagnostics.h"
#import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
#import "FirebasePerformance/Sources/ISASwizzler/FPRObjectSwizzler.h"
#import "FirebasePerformance/Sources/Instrumentation/FPRClassInstrumentor.h"
#import "FirebasePerformance/Sources/Instrumentation/FPRInstrument_Private.h"
#import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace.h"
#import "FirebasePerformance/Sources/Instrumentation/FPRProxyObjectHelper.h"
#import "FirebasePerformance/Sources/Instrumentation/FPRSelectorInstrumentor.h"
#import "FirebasePerformance/Sources/Instrumentation/Network/Delegates/FPRNSURLSessionDelegate.h"
#import "FirebasePerformance/Sources/Instrumentation/Network/FPRNetworkInstrumentHelpers.h"
// Declared for use in instrumentation functions below.
@interface FPRNSURLSessionInstrument ()
/** Registers an instrumentor for an NSURLSession subclass if it hasn't yet been instrumented.
*
* @param aClass The class we wish to instrument.
*/
- (void)registerInstrumentorForClass:(Class)aClass;
/** Registers an instrumentor for an NSURLSession proxy object if it hasn't yet been instrumented.
*
* @param proxy The proxy object we wish to instrument.
*/
- (void)registerProxyObject:(id)proxy;
@end
/** Returns the dispatch queue for all instrumentation to occur on. */
static dispatch_queue_t GetInstrumentationQueue(void) {
static dispatch_queue_t queue = nil;
static dispatch_once_t token = 0;
dispatch_once(&token, ^{
queue =
dispatch_queue_create("com.google.FPRNSURLSessionInstrumentation", DISPATCH_QUEUE_SERIAL);
});
return queue;
}
// This completion handler type is commonly used throughout NSURLSession.
typedef void (^FPRDataTaskCompletionHandler)(NSData *_Nullable,
NSURLResponse *_Nullable,
NSError *_Nullable);
typedef void (^FPRDownloadTaskCompletionHandler)(NSURL *_Nullable location,
NSURLResponse *_Nullable response,
NSError *_Nullable error);
#pragma mark - Instrumentation Functions
/** Wraps +sharedSession.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentSharedSession(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(sharedSession);
Class instrumentedClass = instrumentor.instrumentedClass;
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, YES);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentedClass);
}
typedef NSURLSession *(*OriginalImp)(id, SEL);
NSURLSession *sharedSession = ((OriginalImp)currentIMP)(session, selector);
if ([sharedSession isProxy]) {
[strongInstrument registerProxyObject:sharedSession];
} else {
[strongInstrument registerInstrumentorForClass:[sharedSession class]];
}
return sharedSession;
}];
}
/** Wraps +sessionWithConfiguration:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentSessionWithConfiguration(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(sessionWithConfiguration:);
Class instrumentedClass = instrumentor.instrumentedClass;
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, YES);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLSessionConfiguration *configuration) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentedClass);
}
typedef NSURLSession *(*OriginalImp)(id, SEL, NSURLSessionConfiguration *);
NSURLSession *sessionInstance = ((OriginalImp)currentIMP)(session, selector, configuration);
if ([sessionInstance isProxy]) {
[strongInstrument registerProxyObject:sessionInstance];
} else {
[strongInstrument registerInstrumentorForClass:[sessionInstance class]];
}
return sessionInstance;
}];
}
/** Wraps +sessionWithConfiguration:delegate:delegateQueue:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
* @param delegateInstrument The FPRNSURLSessionDelegateInstrument that will track the delegate
* selectors.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentSessionWithConfigurationDelegateDelegateQueue(
FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor,
FPRNSURLSessionDelegateInstrument *delegateInstrument) {
SEL selector = @selector(sessionWithConfiguration:delegate:delegateQueue:);
Class instrumentedClass = instrumentor.instrumentedClass;
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, YES);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor
setReplacingBlock:^(id session, NSURLSessionConfiguration *configuration,
id<NSURLSessionDelegate> delegate, NSOperationQueue *queue) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentedClass);
}
if (delegate) {
if ([delegate isProxy]) {
[delegateInstrument registerProxy:delegate];
} else {
[delegateInstrument registerClass:[delegate class]];
[delegateInstrument registerObject:delegate];
}
} else {
delegate = [[FPRNSURLSessionDelegate alloc] init];
}
typedef NSURLSession *(*OriginalImp)(id, SEL, NSURLSessionConfiguration *,
id<NSURLSessionDelegate>, NSOperationQueue *);
NSURLSession *sessionInstance =
((OriginalImp)currentIMP)([session class], selector, configuration, delegate, queue);
if ([sessionInstance isProxy]) {
[strongInstrument registerProxyObject:sessionInstance];
} else {
[strongInstrument registerInstrumentorForClass:[sessionInstance class]];
}
return sessionInstance;
}];
}
/** Wraps -dataTaskWithURL:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentDataTaskWithURL(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(dataTaskWithURL:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURL *url) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
}
typedef NSURLSessionDataTask *(*OriginalImp)(id, SEL, NSURL *);
NSURLSessionDataTask *dataTask = ((OriginalImp)currentIMP)(session, selector, url);
if (dataTask.originalRequest) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:dataTask.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:dataTask];
}
return dataTask;
}];
}
/** Instruments -dataTaskWithURL:completionHandler:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentDataTaskWithURLCompletionHandler(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(dataTaskWithURL:completionHandler:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURL *URL,
FPRDataTaskCompletionHandler completionHandler) {
__block NSURLSessionDataTask *task = nil;
FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
if (completionHandler) {
wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:task];
[trace didReceiveData:data];
[trace didCompleteRequestWithResponse:response error:error];
[FPRNetworkTrace removeNetworkTraceFromObject:task];
completionHandler(data, response, error);
};
}
typedef NSURLSessionDataTask *(*OriginalImp)(id, SEL, NSURL *, FPRDataTaskCompletionHandler);
task = ((OriginalImp)currentIMP)(session, selector, URL, wrappedCompletionHandler);
// Add the network trace object only when the trace object is not added to the task object.
if ([FPRNetworkTrace networkTraceFromObject:task] == nil) {
FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:task.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:task];
}
return task;
}];
}
/** Wraps -dataTaskWithRequest:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentDataTaskWithRequest(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(dataTaskWithRequest:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
}
typedef NSURLSessionDataTask *(*OriginalImp)(id, SEL, NSURLRequest *);
NSURLSessionDataTask *dataTask = ((OriginalImp)currentIMP)(session, selector, request);
if (dataTask.originalRequest) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:dataTask.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:dataTask];
}
return dataTask;
}];
}
/** Instruments -dataTaskWithRequest:completionHandler:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentDataTaskWithRequestCompletionHandler(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(dataTaskWithRequest:completionHandler:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request,
FPRDataTaskCompletionHandler completionHandler) {
__block NSURLSessionDataTask *task = nil;
FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
if (completionHandler) {
wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:task];
[trace didReceiveData:data];
[trace didCompleteRequestWithResponse:response error:error];
[FPRNetworkTrace removeNetworkTraceFromObject:task];
completionHandler(data, response, error);
};
}
typedef NSURLSessionDataTask *(*OriginalImp)(id, SEL, NSURLRequest *,
FPRDataTaskCompletionHandler);
task = ((OriginalImp)currentIMP)(session, selector, request, wrappedCompletionHandler);
// Add the network trace object only when the trace object is not added to the task object.
if ([FPRNetworkTrace networkTraceFromObject:task] == nil) {
FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:task.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:task];
}
return task;
}];
}
/** Instruments -uploadTaskWithRequest:fromFile:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentUploadTaskWithRequestFromFile(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(uploadTaskWithRequest:fromFile:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSURL *fileURL) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
}
typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSURL *);
NSURLSessionUploadTask *uploadTask =
((OriginalImp)currentIMP)(session, selector, request, fileURL);
if (uploadTask.originalRequest) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:uploadTask.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:uploadTask];
}
return uploadTask;
}];
}
/** Instruments -uploadTaskWithRequest:fromFile:completionHandler:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentUploadTaskWithRequestFromFileCompletionHandler(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(uploadTaskWithRequest:fromFile:completionHandler:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSURL *fileURL,
FPRDataTaskCompletionHandler completionHandler) {
FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:request];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[trace didUploadFileWithURL:fileURL];
FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
if (completionHandler) {
wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
[trace didReceiveData:data];
[trace didCompleteRequestWithResponse:response error:error];
completionHandler(data, response, error);
};
}
typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSURL *,
FPRDataTaskCompletionHandler);
return ((OriginalImp)currentIMP)(session, selector, request, fileURL, wrappedCompletionHandler);
}];
}
/** Instruments -uploadTaskWithRequest:fromData:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentUploadTaskWithRequestFromData(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(uploadTaskWithRequest:fromData:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSData *bodyData) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
}
typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSData *);
// To avoid a runtime warning in Xcode 15, the given `URLRequest`
// should have a nil `HTTPBody`. To workaround this, the `HTTPBody` data is removed
// and requestData is replaced with it, if it bodyData was `nil`.
NSMutableURLRequest *requestWithoutHTTPBody = [request mutableCopy];
NSData *requestData = bodyData ?: requestWithoutHTTPBody.HTTPBody;
requestWithoutHTTPBody.HTTPBody = nil;
NSURLSessionUploadTask *uploadTask =
((OriginalImp)currentIMP)(session, selector, requestWithoutHTTPBody, requestData);
if (uploadTask.originalRequest) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:uploadTask.originalRequest];
[trace start];
trace.requestSize = bodyData.length;
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:uploadTask];
}
return uploadTask;
}];
}
/** Instruments -uploadTaskWithRequest:fromData:completionHandler:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentUploadTaskWithRequestFromDataCompletionHandler(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(uploadTaskWithRequest:fromData:completionHandler:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSData *bodyData,
FPRDataTaskCompletionHandler completionHandler) {
FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:request];
[trace start];
trace.requestSize = bodyData.length;
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
if (completionHandler) {
wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
[trace didReceiveData:data];
[trace didCompleteRequestWithResponse:response error:error];
completionHandler(data, response, error);
};
}
typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSData *,
FPRDataTaskCompletionHandler);
// To avoid a runtime warning in Xcode 15, the given `URLRequest`
// should have a nil `HTTPBody`. To workaround this, the `HTTPBody` data is removed
// and requestData is replaced with it, if it bodyData was `nil`.
NSMutableURLRequest *requestWithoutHTTPBody = [request mutableCopy];
NSData *requestData = bodyData ?: requestWithoutHTTPBody.HTTPBody;
requestWithoutHTTPBody.HTTPBody = nil;
return ((OriginalImp)currentIMP)(session, selector, requestWithoutHTTPBody, requestData,
wrappedCompletionHandler);
}];
}
/** Instruments -uploadTaskWithStreamedRequest:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentUploadTaskWithStreamedRequest(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(uploadTaskWithStreamedRequest:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
}
typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSData *);
// To avoid a runtime warning in Xcode 15, the given `URLRequest`
// should have a nil `HTTPBody`. To workaround this, the `HTTPBody` data is removed
// and requestData is replaced with it, if it bodyData was `nil`.
NSMutableURLRequest *requestWithoutHTTPBody = [request mutableCopy];
NSData *requestData = requestWithoutHTTPBody.HTTPBody;
requestWithoutHTTPBody.HTTPBody = nil;
NSURLSessionUploadTask *uploadTask =
((OriginalImp)currentIMP)(session, selector, request, requestData);
if (uploadTask.originalRequest) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:uploadTask.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:uploadTask];
}
return uploadTask;
}];
}
/** Instruments -downloadTaskWithURL:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentDownloadTaskWithURL(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(downloadTaskWithURL:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURL *url) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
}
typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURL *);
NSURLSessionDownloadTask *downloadTask = ((OriginalImp)currentIMP)(session, selector, url);
if (downloadTask.originalRequest) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
}
return downloadTask;
}];
}
/** Instruments -downloadTaskWithURL:completionHandler:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentDownloadTaskWithURLCompletionHandler(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(downloadTaskWithURL:completionHandler:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURL *URL,
FPRDownloadTaskCompletionHandler completionHandler) {
__block NSURLSessionDownloadTask *downloadTask = nil;
FPRDownloadTaskCompletionHandler wrappedCompletionHandler = nil;
if (completionHandler) {
wrappedCompletionHandler = ^(NSURL *location, NSURLResponse *response, NSError *error) {
FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:downloadTask];
[trace didReceiveFileURL:location];
[trace didCompleteRequestWithResponse:response error:error];
completionHandler(location, response, error);
};
}
typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURL *,
FPRDownloadTaskCompletionHandler);
downloadTask = ((OriginalImp)currentIMP)(session, selector, URL, wrappedCompletionHandler);
// Add the network trace object only when the trace object is not added to the task object.
if ([FPRNetworkTrace networkTraceFromObject:downloadTask] == nil) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
}
return downloadTask;
}];
}
/** Instruments -downloadTaskWithRequest:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentDownloadTaskWithRequest(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(downloadTaskWithRequest:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
__weak FPRNSURLSessionInstrument *weakInstrument = instrument;
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request) {
__strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
if (!strongInstrument) {
ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
}
typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURLRequest *);
NSURLSessionDownloadTask *downloadTask = ((OriginalImp)currentIMP)(session, selector, request);
if (downloadTask.originalRequest) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
}
return downloadTask;
}];
}
/** Instruments -downloadTaskWithRequest:completionHandler:.
*
* @param instrument The FPRNSURLSessionInstrument instance.
* @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
*/
FOUNDATION_STATIC_INLINE
NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
void InstrumentDownloadTaskWithRequestCompletionHandler(FPRNSURLSessionInstrument *instrument,
FPRClassInstrumentor *instrumentor) {
SEL selector = @selector(downloadTaskWithRequest:completionHandler:);
FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
IMP currentIMP = selectorInstrumentor.currentIMP;
[selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request,
FPRDownloadTaskCompletionHandler completionHandler) {
__block NSURLSessionDownloadTask *downloadTask = nil;
FPRDownloadTaskCompletionHandler wrappedCompletionHandler = nil;
if (completionHandler) {
wrappedCompletionHandler = ^(NSURL *location, NSURLResponse *response, NSError *error) {
FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:downloadTask];
[trace didReceiveFileURL:location];
[trace didCompleteRequestWithResponse:response error:error];
completionHandler(location, response, error);
};
}
typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURLRequest *,
FPRDownloadTaskCompletionHandler);
downloadTask = ((OriginalImp)currentIMP)(session, selector, request, wrappedCompletionHandler);
// Add the network trace object only when the trace object is not added to the task object.
if ([FPRNetworkTrace networkTraceFromObject:downloadTask] == nil) {
FPRNetworkTrace *trace =
[[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
[trace start];
[trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
[FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
}
return downloadTask;
}];
}
#pragma mark - FPRNSURLSessionInstrument
@implementation FPRNSURLSessionInstrument
- (instancetype)init {
self = [super init];
if (self) {
_delegateInstrument = [[FPRNSURLSessionDelegateInstrument alloc] init];
[_delegateInstrument registerInstrumentors];
}
return self;
}
- (void)registerInstrumentors {
[self registerInstrumentorForClass:[NSURLSession class]];
}
- (void)deregisterInstrumentors {
[_delegateInstrument deregisterInstrumentors];
[super deregisterInstrumentors];
}
- (void)registerInstrumentorForClass:(Class)aClass {
dispatch_sync(GetInstrumentationQueue(), ^{
FPRAssert([aClass isSubclassOfClass:[NSURLSession class]],
@"Class %@ is not a subclass of "
"NSURLSession",
aClass);
// If this class has already been instrumented, just return.
FPRClassInstrumentor *instrumentor = [[FPRClassInstrumentor alloc] initWithClass:aClass];
if (![self registerClassInstrumentor:instrumentor]) {
return;
}
InstrumentSharedSession(self, instrumentor);
InstrumentSessionWithConfiguration(self, instrumentor);
InstrumentSessionWithConfigurationDelegateDelegateQueue(self, instrumentor,
_delegateInstrument);
InstrumentDataTaskWithURL(self, instrumentor);
InstrumentDataTaskWithURLCompletionHandler(self, instrumentor);
InstrumentDataTaskWithRequest(self, instrumentor);
InstrumentDataTaskWithRequestCompletionHandler(self, instrumentor);
InstrumentUploadTaskWithRequestFromFile(self, instrumentor);
InstrumentUploadTaskWithRequestFromFileCompletionHandler(self, instrumentor);
InstrumentUploadTaskWithRequestFromData(self, instrumentor);
InstrumentUploadTaskWithRequestFromDataCompletionHandler(self, instrumentor);
InstrumentUploadTaskWithStreamedRequest(self, instrumentor);
InstrumentDownloadTaskWithURL(self, instrumentor);
InstrumentDownloadTaskWithURLCompletionHandler(self, instrumentor);
InstrumentDownloadTaskWithRequest(self, instrumentor);
InstrumentDownloadTaskWithRequestCompletionHandler(self, instrumentor);
[instrumentor swizzle];
});
}
- (void)registerProxyObject:(id)proxy {
[FPRProxyObjectHelper registerProxyObject:proxy
forSuperclass:[NSURLSession class]
varFoundHandler:^(id ivar) {
[self registerInstrumentorForClass:[ivar class]];
}];
}
@end