FPRNSURLSessionInstrument.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /** NSURLSession is a class cluster and the type of class you get back from the various
  15. * initialization methods might not actually be NSURLSession. Inside those methods, this class
  16. * keeps track of seen NSURLSession subclasses and lazily swizzles them if they've not been seen.
  17. * Consequently, swizzling needs to occur on a serial queue for thread safety.
  18. */
  19. #import "FirebasePerformance/Sources/Instrumentation/Network/FPRNSURLSessionInstrument.h"
  20. #import "FirebasePerformance/Sources/Instrumentation/Network/FPRNSURLSessionInstrument_Private.h"
  21. #import "FirebasePerformance/Sources/Common/FPRDiagnostics.h"
  22. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  23. #import "FirebasePerformance/Sources/ISASwizzler/FPRObjectSwizzler.h"
  24. #import "FirebasePerformance/Sources/Instrumentation/FPRClassInstrumentor.h"
  25. #import "FirebasePerformance/Sources/Instrumentation/FPRInstrument_Private.h"
  26. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace.h"
  27. #import "FirebasePerformance/Sources/Instrumentation/FPRProxyObjectHelper.h"
  28. #import "FirebasePerformance/Sources/Instrumentation/FPRSelectorInstrumentor.h"
  29. #import "FirebasePerformance/Sources/Instrumentation/Network/Delegates/FPRNSURLSessionDelegate.h"
  30. #import "FirebasePerformance/Sources/Instrumentation/Network/FPRNetworkInstrumentHelpers.h"
  31. // Declared for use in instrumentation functions below.
  32. @interface FPRNSURLSessionInstrument ()
  33. /** Registers an instrumentor for an NSURLSession subclass if it hasn't yet been instrumented.
  34. *
  35. * @param aClass The class we wish to instrument.
  36. */
  37. - (void)registerInstrumentorForClass:(Class)aClass;
  38. /** Registers an instrumentor for an NSURLSession proxy object if it hasn't yet been instrumented.
  39. *
  40. * @param proxy The proxy object we wish to instrument.
  41. */
  42. - (void)registerProxyObject:(id)proxy;
  43. @end
  44. /** Returns the dispatch queue for all instrumentation to occur on. */
  45. static dispatch_queue_t GetInstrumentationQueue(void) {
  46. static dispatch_queue_t queue = nil;
  47. static dispatch_once_t token = 0;
  48. dispatch_once(&token, ^{
  49. queue =
  50. dispatch_queue_create("com.google.FPRNSURLSessionInstrumentation", DISPATCH_QUEUE_SERIAL);
  51. });
  52. return queue;
  53. }
  54. // This completion handler type is commonly used throughout NSURLSession.
  55. typedef void (^FPRDataTaskCompletionHandler)(NSData *_Nullable,
  56. NSURLResponse *_Nullable,
  57. NSError *_Nullable);
  58. typedef void (^FPRDownloadTaskCompletionHandler)(NSURL *_Nullable location,
  59. NSURLResponse *_Nullable response,
  60. NSError *_Nullable error);
  61. #pragma mark - Instrumentation Functions
  62. /** Wraps +sharedSession.
  63. *
  64. * @param instrument The FPRNSURLSessionInstrument instance.
  65. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  66. */
  67. FOUNDATION_STATIC_INLINE
  68. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  69. void InstrumentSharedSession(FPRNSURLSessionInstrument *instrument,
  70. FPRClassInstrumentor *instrumentor) {
  71. SEL selector = @selector(sharedSession);
  72. Class instrumentedClass = instrumentor.instrumentedClass;
  73. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, YES);
  74. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  75. IMP currentIMP = selectorInstrumentor.currentIMP;
  76. [selectorInstrumentor setReplacingBlock:^(id session) {
  77. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  78. if (!strongInstrument) {
  79. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentedClass);
  80. }
  81. typedef NSURLSession *(*OriginalImp)(id, SEL);
  82. NSURLSession *sharedSession = ((OriginalImp)currentIMP)(session, selector);
  83. if ([sharedSession isProxy]) {
  84. [strongInstrument registerProxyObject:sharedSession];
  85. } else {
  86. [strongInstrument registerInstrumentorForClass:[sharedSession class]];
  87. }
  88. return sharedSession;
  89. }];
  90. }
  91. /** Wraps +sessionWithConfiguration:.
  92. *
  93. * @param instrument The FPRNSURLSessionInstrument instance.
  94. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  95. */
  96. FOUNDATION_STATIC_INLINE
  97. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  98. void InstrumentSessionWithConfiguration(FPRNSURLSessionInstrument *instrument,
  99. FPRClassInstrumentor *instrumentor) {
  100. SEL selector = @selector(sessionWithConfiguration:);
  101. Class instrumentedClass = instrumentor.instrumentedClass;
  102. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, YES);
  103. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  104. IMP currentIMP = selectorInstrumentor.currentIMP;
  105. [selectorInstrumentor setReplacingBlock:^(id session, NSURLSessionConfiguration *configuration) {
  106. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  107. if (!strongInstrument) {
  108. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentedClass);
  109. }
  110. typedef NSURLSession *(*OriginalImp)(id, SEL, NSURLSessionConfiguration *);
  111. NSURLSession *sessionInstance = ((OriginalImp)currentIMP)(session, selector, configuration);
  112. if ([sessionInstance isProxy]) {
  113. [strongInstrument registerProxyObject:sessionInstance];
  114. } else {
  115. [strongInstrument registerInstrumentorForClass:[sessionInstance class]];
  116. }
  117. return sessionInstance;
  118. }];
  119. }
  120. /** Wraps +sessionWithConfiguration:delegate:delegateQueue:.
  121. *
  122. * @param instrument The FPRNSURLSessionInstrument instance.
  123. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  124. * @param delegateInstrument The FPRNSURLSessionDelegateInstrument that will track the delegate
  125. * selectors.
  126. */
  127. FOUNDATION_STATIC_INLINE
  128. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  129. void InstrumentSessionWithConfigurationDelegateDelegateQueue(
  130. FPRNSURLSessionInstrument *instrument,
  131. FPRClassInstrumentor *instrumentor,
  132. FPRNSURLSessionDelegateInstrument *delegateInstrument) {
  133. SEL selector = @selector(sessionWithConfiguration:delegate:delegateQueue:);
  134. Class instrumentedClass = instrumentor.instrumentedClass;
  135. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, YES);
  136. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  137. IMP currentIMP = selectorInstrumentor.currentIMP;
  138. [selectorInstrumentor
  139. setReplacingBlock:^(id session, NSURLSessionConfiguration *configuration,
  140. id<NSURLSessionDelegate> delegate, NSOperationQueue *queue) {
  141. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  142. if (!strongInstrument) {
  143. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentedClass);
  144. }
  145. if (delegate) {
  146. [delegateInstrument registerClass:[delegate class]];
  147. [delegateInstrument registerObject:delegate];
  148. } else {
  149. delegate = [[FPRNSURLSessionDelegate alloc] init];
  150. }
  151. typedef NSURLSession *(*OriginalImp)(id, SEL, NSURLSessionConfiguration *,
  152. id<NSURLSessionDelegate>, NSOperationQueue *);
  153. NSURLSession *sessionInstance =
  154. ((OriginalImp)currentIMP)([session class], selector, configuration, delegate, queue);
  155. if ([sessionInstance isProxy]) {
  156. [strongInstrument registerProxyObject:sessionInstance];
  157. } else {
  158. [strongInstrument registerInstrumentorForClass:[sessionInstance class]];
  159. }
  160. return sessionInstance;
  161. }];
  162. }
  163. /** Wraps -dataTaskWithURL:.
  164. *
  165. * @param instrument The FPRNSURLSessionInstrument instance.
  166. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  167. */
  168. FOUNDATION_STATIC_INLINE
  169. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  170. void InstrumentDataTaskWithURL(FPRNSURLSessionInstrument *instrument,
  171. FPRClassInstrumentor *instrumentor) {
  172. SEL selector = @selector(dataTaskWithURL:);
  173. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  174. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  175. IMP currentIMP = selectorInstrumentor.currentIMP;
  176. [selectorInstrumentor setReplacingBlock:^(id session, NSURL *url) {
  177. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  178. if (!strongInstrument) {
  179. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  180. }
  181. typedef NSURLSessionDataTask *(*OriginalImp)(id, SEL, NSURL *);
  182. NSURLSessionDataTask *dataTask = ((OriginalImp)currentIMP)(session, selector, url);
  183. if (dataTask.originalRequest) {
  184. FPRNetworkTrace *trace =
  185. [[FPRNetworkTrace alloc] initWithURLRequest:dataTask.originalRequest];
  186. [trace start];
  187. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  188. [FPRNetworkTrace addNetworkTrace:trace toObject:dataTask];
  189. }
  190. return dataTask;
  191. }];
  192. }
  193. /** Instruments -dataTaskWithURL:completionHandler:.
  194. *
  195. * @param instrument The FPRNSURLSessionInstrument instance.
  196. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  197. */
  198. FOUNDATION_STATIC_INLINE
  199. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  200. void InstrumentDataTaskWithURLCompletionHandler(FPRNSURLSessionInstrument *instrument,
  201. FPRClassInstrumentor *instrumentor) {
  202. SEL selector = @selector(dataTaskWithURL:completionHandler:);
  203. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  204. IMP currentIMP = selectorInstrumentor.currentIMP;
  205. [selectorInstrumentor setReplacingBlock:^(id session, NSURL *URL,
  206. FPRDataTaskCompletionHandler completionHandler) {
  207. __block NSURLSessionDataTask *task = nil;
  208. FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
  209. if (completionHandler) {
  210. wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
  211. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:task];
  212. [trace didReceiveData:data];
  213. [trace didCompleteRequestWithResponse:response error:error];
  214. [FPRNetworkTrace removeNetworkTraceFromObject:task];
  215. completionHandler(data, response, error);
  216. };
  217. }
  218. typedef NSURLSessionDataTask *(*OriginalImp)(id, SEL, NSURL *, FPRDataTaskCompletionHandler);
  219. task = ((OriginalImp)currentIMP)(session, selector, URL, wrappedCompletionHandler);
  220. // Add the network trace object only when the trace object is not added to the task object.
  221. if ([FPRNetworkTrace networkTraceFromObject:task] == nil) {
  222. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:task.originalRequest];
  223. [trace start];
  224. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  225. [FPRNetworkTrace addNetworkTrace:trace toObject:task];
  226. }
  227. return task;
  228. }];
  229. }
  230. /** Wraps -dataTaskWithRequest:.
  231. *
  232. * @param instrument The FPRNSURLSessionInstrument instance.
  233. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  234. */
  235. FOUNDATION_STATIC_INLINE
  236. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  237. void InstrumentDataTaskWithRequest(FPRNSURLSessionInstrument *instrument,
  238. FPRClassInstrumentor *instrumentor) {
  239. SEL selector = @selector(dataTaskWithRequest:);
  240. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  241. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  242. IMP currentIMP = selectorInstrumentor.currentIMP;
  243. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request) {
  244. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  245. if (!strongInstrument) {
  246. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  247. }
  248. typedef NSURLSessionDataTask *(*OriginalImp)(id, SEL, NSURLRequest *);
  249. NSURLSessionDataTask *dataTask = ((OriginalImp)currentIMP)(session, selector, request);
  250. if (dataTask.originalRequest) {
  251. FPRNetworkTrace *trace =
  252. [[FPRNetworkTrace alloc] initWithURLRequest:dataTask.originalRequest];
  253. [trace start];
  254. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  255. [FPRNetworkTrace addNetworkTrace:trace toObject:dataTask];
  256. }
  257. return dataTask;
  258. }];
  259. }
  260. /** Instruments -dataTaskWithRequest:completionHandler:.
  261. *
  262. * @param instrument The FPRNSURLSessionInstrument instance.
  263. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  264. */
  265. FOUNDATION_STATIC_INLINE
  266. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  267. void InstrumentDataTaskWithRequestCompletionHandler(FPRNSURLSessionInstrument *instrument,
  268. FPRClassInstrumentor *instrumentor) {
  269. SEL selector = @selector(dataTaskWithRequest:completionHandler:);
  270. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  271. IMP currentIMP = selectorInstrumentor.currentIMP;
  272. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request,
  273. FPRDataTaskCompletionHandler completionHandler) {
  274. __block NSURLSessionDataTask *task = nil;
  275. FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
  276. if (completionHandler) {
  277. wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
  278. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:task];
  279. [trace didReceiveData:data];
  280. [trace didCompleteRequestWithResponse:response error:error];
  281. [FPRNetworkTrace removeNetworkTraceFromObject:task];
  282. completionHandler(data, response, error);
  283. };
  284. }
  285. typedef NSURLSessionDataTask *(*OriginalImp)(id, SEL, NSURLRequest *,
  286. FPRDataTaskCompletionHandler);
  287. task = ((OriginalImp)currentIMP)(session, selector, request, wrappedCompletionHandler);
  288. // Add the network trace object only when the trace object is not added to the task object.
  289. if ([FPRNetworkTrace networkTraceFromObject:task] == nil) {
  290. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:task.originalRequest];
  291. [trace start];
  292. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  293. [FPRNetworkTrace addNetworkTrace:trace toObject:task];
  294. }
  295. return task;
  296. }];
  297. }
  298. /** Instruments -uploadTaskWithRequest:fromFile:.
  299. *
  300. * @param instrument The FPRNSURLSessionInstrument instance.
  301. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  302. */
  303. FOUNDATION_STATIC_INLINE
  304. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  305. void InstrumentUploadTaskWithRequestFromFile(FPRNSURLSessionInstrument *instrument,
  306. FPRClassInstrumentor *instrumentor) {
  307. SEL selector = @selector(uploadTaskWithRequest:fromFile:);
  308. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  309. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  310. IMP currentIMP = selectorInstrumentor.currentIMP;
  311. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSURL *fileURL) {
  312. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  313. if (!strongInstrument) {
  314. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  315. }
  316. typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSURL *);
  317. NSURLSessionUploadTask *uploadTask =
  318. ((OriginalImp)currentIMP)(session, selector, request, fileURL);
  319. if (uploadTask.originalRequest) {
  320. FPRNetworkTrace *trace =
  321. [[FPRNetworkTrace alloc] initWithURLRequest:uploadTask.originalRequest];
  322. [trace start];
  323. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  324. [FPRNetworkTrace addNetworkTrace:trace toObject:uploadTask];
  325. }
  326. return uploadTask;
  327. }];
  328. }
  329. /** Instruments -uploadTaskWithRequest:fromFile:completionHandler:.
  330. *
  331. * @param instrument The FPRNSURLSessionInstrument instance.
  332. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  333. */
  334. FOUNDATION_STATIC_INLINE
  335. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  336. void InstrumentUploadTaskWithRequestFromFileCompletionHandler(FPRNSURLSessionInstrument *instrument,
  337. FPRClassInstrumentor *instrumentor) {
  338. SEL selector = @selector(uploadTaskWithRequest:fromFile:completionHandler:);
  339. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  340. IMP currentIMP = selectorInstrumentor.currentIMP;
  341. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSURL *fileURL,
  342. FPRDataTaskCompletionHandler completionHandler) {
  343. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:request];
  344. [trace start];
  345. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  346. [trace didUploadFileWithURL:fileURL];
  347. FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
  348. if (completionHandler) {
  349. wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
  350. [trace didReceiveData:data];
  351. [trace didCompleteRequestWithResponse:response error:error];
  352. completionHandler(data, response, error);
  353. };
  354. }
  355. typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSURL *,
  356. FPRDataTaskCompletionHandler);
  357. return ((OriginalImp)currentIMP)(session, selector, request, fileURL, wrappedCompletionHandler);
  358. }];
  359. }
  360. /** Instruments -uploadTaskWithRequest:fromData:.
  361. *
  362. * @param instrument The FPRNSURLSessionInstrument instance.
  363. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  364. */
  365. FOUNDATION_STATIC_INLINE
  366. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  367. void InstrumentUploadTaskWithRequestFromData(FPRNSURLSessionInstrument *instrument,
  368. FPRClassInstrumentor *instrumentor) {
  369. SEL selector = @selector(uploadTaskWithRequest:fromData:);
  370. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  371. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  372. IMP currentIMP = selectorInstrumentor.currentIMP;
  373. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSData *bodyData) {
  374. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  375. if (!strongInstrument) {
  376. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  377. }
  378. typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSData *);
  379. // To avoid a runtime warning in Xcode 15, the given `URLRequest`
  380. // should have a nil `HTTPBody`. To workaround this, the `HTTPBody` data is removed
  381. // and requestData is replaced with it, if it bodyData was `nil`.
  382. NSMutableURLRequest *requestWithoutHTTPBody = [request mutableCopy];
  383. NSData *requestData = bodyData ?: requestWithoutHTTPBody.HTTPBody;
  384. requestWithoutHTTPBody.HTTPBody = nil;
  385. NSURLSessionUploadTask *uploadTask =
  386. ((OriginalImp)currentIMP)(session, selector, requestWithoutHTTPBody, requestData);
  387. if (uploadTask.originalRequest) {
  388. FPRNetworkTrace *trace =
  389. [[FPRNetworkTrace alloc] initWithURLRequest:uploadTask.originalRequest];
  390. [trace start];
  391. trace.requestSize = bodyData.length;
  392. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  393. [FPRNetworkTrace addNetworkTrace:trace toObject:uploadTask];
  394. }
  395. return uploadTask;
  396. }];
  397. }
  398. /** Instruments -uploadTaskWithRequest:fromData:completionHandler:.
  399. *
  400. * @param instrument The FPRNSURLSessionInstrument instance.
  401. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  402. */
  403. FOUNDATION_STATIC_INLINE
  404. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  405. void InstrumentUploadTaskWithRequestFromDataCompletionHandler(FPRNSURLSessionInstrument *instrument,
  406. FPRClassInstrumentor *instrumentor) {
  407. SEL selector = @selector(uploadTaskWithRequest:fromData:completionHandler:);
  408. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  409. IMP currentIMP = selectorInstrumentor.currentIMP;
  410. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSData *bodyData,
  411. FPRDataTaskCompletionHandler completionHandler) {
  412. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:request];
  413. [trace start];
  414. trace.requestSize = bodyData.length;
  415. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  416. FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
  417. if (completionHandler) {
  418. wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
  419. [trace didReceiveData:data];
  420. [trace didCompleteRequestWithResponse:response error:error];
  421. completionHandler(data, response, error);
  422. };
  423. }
  424. typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSData *,
  425. FPRDataTaskCompletionHandler);
  426. // To avoid a runtime warning in Xcode 15, the given `URLRequest`
  427. // should have a nil `HTTPBody`. To workaround this, the `HTTPBody` data is removed
  428. // and requestData is replaced with it, if it bodyData was `nil`.
  429. NSMutableURLRequest *requestWithoutHTTPBody = [request mutableCopy];
  430. NSData *requestData = bodyData ?: requestWithoutHTTPBody.HTTPBody;
  431. requestWithoutHTTPBody.HTTPBody = nil;
  432. return ((OriginalImp)currentIMP)(session, selector, requestWithoutHTTPBody, requestData,
  433. wrappedCompletionHandler);
  434. }];
  435. }
  436. /** Instruments -uploadTaskWithStreamedRequest:.
  437. *
  438. * @param instrument The FPRNSURLSessionInstrument instance.
  439. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  440. */
  441. FOUNDATION_STATIC_INLINE
  442. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  443. void InstrumentUploadTaskWithStreamedRequest(FPRNSURLSessionInstrument *instrument,
  444. FPRClassInstrumentor *instrumentor) {
  445. SEL selector = @selector(uploadTaskWithStreamedRequest:);
  446. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  447. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  448. IMP currentIMP = selectorInstrumentor.currentIMP;
  449. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request) {
  450. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  451. if (!strongInstrument) {
  452. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  453. }
  454. typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSData *);
  455. // To avoid a runtime warning in Xcode 15, the given `URLRequest`
  456. // should have a nil `HTTPBody`. To workaround this, the `HTTPBody` data is removed
  457. // and requestData is replaced with it, if it bodyData was `nil`.
  458. NSMutableURLRequest *requestWithoutHTTPBody = [request mutableCopy];
  459. NSData *requestData = requestWithoutHTTPBody.HTTPBody;
  460. requestWithoutHTTPBody.HTTPBody = nil;
  461. NSURLSessionUploadTask *uploadTask =
  462. ((OriginalImp)currentIMP)(session, selector, request, requestData);
  463. if (uploadTask.originalRequest) {
  464. FPRNetworkTrace *trace =
  465. [[FPRNetworkTrace alloc] initWithURLRequest:uploadTask.originalRequest];
  466. [trace start];
  467. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  468. [FPRNetworkTrace addNetworkTrace:trace toObject:uploadTask];
  469. }
  470. return uploadTask;
  471. }];
  472. }
  473. /** Instruments -downloadTaskWithURL:.
  474. *
  475. * @param instrument The FPRNSURLSessionInstrument instance.
  476. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  477. */
  478. FOUNDATION_STATIC_INLINE
  479. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  480. void InstrumentDownloadTaskWithURL(FPRNSURLSessionInstrument *instrument,
  481. FPRClassInstrumentor *instrumentor) {
  482. SEL selector = @selector(downloadTaskWithURL:);
  483. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  484. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  485. IMP currentIMP = selectorInstrumentor.currentIMP;
  486. [selectorInstrumentor setReplacingBlock:^(id session, NSURL *url) {
  487. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  488. if (!strongInstrument) {
  489. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  490. }
  491. typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURL *);
  492. NSURLSessionDownloadTask *downloadTask = ((OriginalImp)currentIMP)(session, selector, url);
  493. if (downloadTask.originalRequest) {
  494. FPRNetworkTrace *trace =
  495. [[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
  496. [trace start];
  497. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  498. [FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
  499. }
  500. return downloadTask;
  501. }];
  502. }
  503. /** Instruments -downloadTaskWithURL:completionHandler:.
  504. *
  505. * @param instrument The FPRNSURLSessionInstrument instance.
  506. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  507. */
  508. FOUNDATION_STATIC_INLINE
  509. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  510. void InstrumentDownloadTaskWithURLCompletionHandler(FPRNSURLSessionInstrument *instrument,
  511. FPRClassInstrumentor *instrumentor) {
  512. SEL selector = @selector(downloadTaskWithURL:completionHandler:);
  513. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  514. IMP currentIMP = selectorInstrumentor.currentIMP;
  515. [selectorInstrumentor setReplacingBlock:^(id session, NSURL *URL,
  516. FPRDownloadTaskCompletionHandler completionHandler) {
  517. __block NSURLSessionDownloadTask *downloadTask = nil;
  518. FPRDownloadTaskCompletionHandler wrappedCompletionHandler = nil;
  519. if (completionHandler) {
  520. wrappedCompletionHandler = ^(NSURL *location, NSURLResponse *response, NSError *error) {
  521. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:downloadTask];
  522. [trace didReceiveFileURL:location];
  523. [trace didCompleteRequestWithResponse:response error:error];
  524. completionHandler(location, response, error);
  525. };
  526. }
  527. typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURL *,
  528. FPRDownloadTaskCompletionHandler);
  529. downloadTask = ((OriginalImp)currentIMP)(session, selector, URL, wrappedCompletionHandler);
  530. // Add the network trace object only when the trace object is not added to the task object.
  531. if ([FPRNetworkTrace networkTraceFromObject:downloadTask] == nil) {
  532. FPRNetworkTrace *trace =
  533. [[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
  534. [trace start];
  535. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  536. [FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
  537. }
  538. return downloadTask;
  539. }];
  540. }
  541. /** Instruments -downloadTaskWithRequest:.
  542. *
  543. * @param instrument The FPRNSURLSessionInstrument instance.
  544. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  545. */
  546. FOUNDATION_STATIC_INLINE
  547. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  548. void InstrumentDownloadTaskWithRequest(FPRNSURLSessionInstrument *instrument,
  549. FPRClassInstrumentor *instrumentor) {
  550. SEL selector = @selector(downloadTaskWithRequest:);
  551. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  552. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  553. IMP currentIMP = selectorInstrumentor.currentIMP;
  554. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request) {
  555. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  556. if (!strongInstrument) {
  557. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  558. }
  559. typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURLRequest *);
  560. NSURLSessionDownloadTask *downloadTask = ((OriginalImp)currentIMP)(session, selector, request);
  561. if (downloadTask.originalRequest) {
  562. FPRNetworkTrace *trace =
  563. [[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
  564. [trace start];
  565. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  566. [FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
  567. }
  568. return downloadTask;
  569. }];
  570. }
  571. /** Instruments -downloadTaskWithRequest:completionHandler:.
  572. *
  573. * @param instrument The FPRNSURLSessionInstrument instance.
  574. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  575. */
  576. FOUNDATION_STATIC_INLINE
  577. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  578. void InstrumentDownloadTaskWithRequestCompletionHandler(FPRNSURLSessionInstrument *instrument,
  579. FPRClassInstrumentor *instrumentor) {
  580. SEL selector = @selector(downloadTaskWithRequest:completionHandler:);
  581. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  582. IMP currentIMP = selectorInstrumentor.currentIMP;
  583. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request,
  584. FPRDownloadTaskCompletionHandler completionHandler) {
  585. __block NSURLSessionDownloadTask *downloadTask = nil;
  586. FPRDownloadTaskCompletionHandler wrappedCompletionHandler = nil;
  587. if (completionHandler) {
  588. wrappedCompletionHandler = ^(NSURL *location, NSURLResponse *response, NSError *error) {
  589. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:downloadTask];
  590. [trace didReceiveFileURL:location];
  591. [trace didCompleteRequestWithResponse:response error:error];
  592. completionHandler(location, response, error);
  593. };
  594. }
  595. typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURLRequest *,
  596. FPRDownloadTaskCompletionHandler);
  597. downloadTask = ((OriginalImp)currentIMP)(session, selector, request, wrappedCompletionHandler);
  598. // Add the network trace object only when the trace object is not added to the task object.
  599. if ([FPRNetworkTrace networkTraceFromObject:downloadTask] == nil) {
  600. FPRNetworkTrace *trace =
  601. [[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
  602. [trace start];
  603. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  604. [FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
  605. }
  606. return downloadTask;
  607. }];
  608. }
  609. #pragma mark - FPRNSURLSessionInstrument
  610. @implementation FPRNSURLSessionInstrument
  611. - (instancetype)init {
  612. self = [super init];
  613. if (self) {
  614. _delegateInstrument = [[FPRNSURLSessionDelegateInstrument alloc] init];
  615. [_delegateInstrument registerInstrumentors];
  616. }
  617. return self;
  618. }
  619. - (void)registerInstrumentors {
  620. [self registerInstrumentorForClass:[NSURLSession class]];
  621. }
  622. - (void)deregisterInstrumentors {
  623. [_delegateInstrument deregisterInstrumentors];
  624. [super deregisterInstrumentors];
  625. }
  626. - (void)registerInstrumentorForClass:(Class)aClass {
  627. dispatch_sync(GetInstrumentationQueue(), ^{
  628. FPRAssert([aClass isSubclassOfClass:[NSURLSession class]],
  629. @"Class %@ is not a subclass of "
  630. "NSURLSession",
  631. aClass);
  632. // If this class has already been instrumented, just return.
  633. FPRClassInstrumentor *instrumentor = [[FPRClassInstrumentor alloc] initWithClass:aClass];
  634. if (![self registerClassInstrumentor:instrumentor]) {
  635. return;
  636. }
  637. InstrumentSharedSession(self, instrumentor);
  638. InstrumentSessionWithConfiguration(self, instrumentor);
  639. InstrumentSessionWithConfigurationDelegateDelegateQueue(self, instrumentor,
  640. _delegateInstrument);
  641. InstrumentDataTaskWithURL(self, instrumentor);
  642. InstrumentDataTaskWithURLCompletionHandler(self, instrumentor);
  643. InstrumentDataTaskWithRequest(self, instrumentor);
  644. InstrumentDataTaskWithRequestCompletionHandler(self, instrumentor);
  645. InstrumentUploadTaskWithRequestFromFile(self, instrumentor);
  646. InstrumentUploadTaskWithRequestFromFileCompletionHandler(self, instrumentor);
  647. InstrumentUploadTaskWithRequestFromData(self, instrumentor);
  648. InstrumentUploadTaskWithRequestFromDataCompletionHandler(self, instrumentor);
  649. InstrumentUploadTaskWithStreamedRequest(self, instrumentor);
  650. InstrumentDownloadTaskWithURL(self, instrumentor);
  651. InstrumentDownloadTaskWithURLCompletionHandler(self, instrumentor);
  652. InstrumentDownloadTaskWithRequest(self, instrumentor);
  653. InstrumentDownloadTaskWithRequestCompletionHandler(self, instrumentor);
  654. [instrumentor swizzle];
  655. });
  656. }
  657. - (void)registerProxyObject:(id)proxy {
  658. [FPRProxyObjectHelper registerProxyObject:proxy
  659. forSuperclass:[NSURLSession class]
  660. varFoundHandler:^(id ivar) {
  661. [self registerInstrumentorForClass:[ivar class]];
  662. }];
  663. }
  664. @end