FPRNSURLSessionInstrument.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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/Instrumentation/FPRClassInstrumentor.h"
  24. #import "FirebasePerformance/Sources/Instrumentation/FPRInstrument_Private.h"
  25. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace.h"
  26. #import "FirebasePerformance/Sources/Instrumentation/FPRProxyObjectHelper.h"
  27. #import "FirebasePerformance/Sources/Instrumentation/FPRSelectorInstrumentor.h"
  28. #import "FirebasePerformance/Sources/Instrumentation/Network/Delegates/FPRNSURLSessionDelegate.h"
  29. #import "FirebasePerformance/Sources/Instrumentation/Network/FPRNetworkInstrumentHelpers.h"
  30. #import <GoogleUtilities/GULObjectSwizzler.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. NSURLSessionUploadTask *uploadTask =
  380. ((OriginalImp)currentIMP)(session, selector, request, bodyData);
  381. if (uploadTask.originalRequest) {
  382. FPRNetworkTrace *trace =
  383. [[FPRNetworkTrace alloc] initWithURLRequest:uploadTask.originalRequest];
  384. [trace start];
  385. trace.requestSize = bodyData.length;
  386. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  387. [FPRNetworkTrace addNetworkTrace:trace toObject:uploadTask];
  388. }
  389. return uploadTask;
  390. }];
  391. }
  392. /** Instruments -uploadTaskWithRequest:fromData:completionHandler:.
  393. *
  394. * @param instrument The FPRNSURLSessionInstrument instance.
  395. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  396. */
  397. FOUNDATION_STATIC_INLINE
  398. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  399. void InstrumentUploadTaskWithRequestFromDataCompletionHandler(FPRNSURLSessionInstrument *instrument,
  400. FPRClassInstrumentor *instrumentor) {
  401. SEL selector = @selector(uploadTaskWithRequest:fromData:completionHandler:);
  402. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  403. IMP currentIMP = selectorInstrumentor.currentIMP;
  404. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request, NSData *bodyData,
  405. FPRDataTaskCompletionHandler completionHandler) {
  406. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:request];
  407. [trace start];
  408. trace.requestSize = bodyData.length;
  409. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  410. FPRDataTaskCompletionHandler wrappedCompletionHandler = nil;
  411. if (completionHandler) {
  412. wrappedCompletionHandler = ^(NSData *data, NSURLResponse *response, NSError *error) {
  413. [trace didReceiveData:data];
  414. [trace didCompleteRequestWithResponse:response error:error];
  415. completionHandler(data, response, error);
  416. };
  417. }
  418. typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *, NSData *,
  419. FPRDataTaskCompletionHandler);
  420. return ((OriginalImp)currentIMP)(session, selector, request, bodyData,
  421. wrappedCompletionHandler);
  422. }];
  423. }
  424. /** Instruments -uploadTaskWithStreamedRequest:.
  425. *
  426. * @param instrument The FPRNSURLSessionInstrument instance.
  427. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  428. */
  429. FOUNDATION_STATIC_INLINE
  430. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  431. void InstrumentUploadTaskWithStreamedRequest(FPRNSURLSessionInstrument *instrument,
  432. FPRClassInstrumentor *instrumentor) {
  433. SEL selector = @selector(uploadTaskWithStreamedRequest:);
  434. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  435. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  436. IMP currentIMP = selectorInstrumentor.currentIMP;
  437. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request) {
  438. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  439. if (!strongInstrument) {
  440. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  441. }
  442. typedef NSURLSessionUploadTask *(*OriginalImp)(id, SEL, NSURLRequest *);
  443. NSURLSessionUploadTask *uploadTask = ((OriginalImp)currentIMP)(session, selector, request);
  444. if (uploadTask.originalRequest) {
  445. FPRNetworkTrace *trace =
  446. [[FPRNetworkTrace alloc] initWithURLRequest:uploadTask.originalRequest];
  447. [trace start];
  448. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  449. [FPRNetworkTrace addNetworkTrace:trace toObject:uploadTask];
  450. }
  451. return uploadTask;
  452. }];
  453. }
  454. /** Instruments -downloadTaskWithURL:.
  455. *
  456. * @param instrument The FPRNSURLSessionInstrument instance.
  457. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  458. */
  459. FOUNDATION_STATIC_INLINE
  460. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  461. void InstrumentDownloadTaskWithURL(FPRNSURLSessionInstrument *instrument,
  462. FPRClassInstrumentor *instrumentor) {
  463. SEL selector = @selector(downloadTaskWithURL:);
  464. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  465. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  466. IMP currentIMP = selectorInstrumentor.currentIMP;
  467. [selectorInstrumentor setReplacingBlock:^(id session, NSURL *url) {
  468. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  469. if (!strongInstrument) {
  470. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  471. }
  472. typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURL *);
  473. NSURLSessionDownloadTask *downloadTask = ((OriginalImp)currentIMP)(session, selector, url);
  474. if (downloadTask.originalRequest) {
  475. FPRNetworkTrace *trace =
  476. [[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
  477. [trace start];
  478. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  479. [FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
  480. }
  481. return downloadTask;
  482. }];
  483. }
  484. /** Instruments -downloadTaskWithURL:completionHandler:.
  485. *
  486. * @param instrument The FPRNSURLSessionInstrument instance.
  487. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  488. */
  489. FOUNDATION_STATIC_INLINE
  490. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  491. void InstrumentDownloadTaskWithURLCompletionHandler(FPRNSURLSessionInstrument *instrument,
  492. FPRClassInstrumentor *instrumentor) {
  493. SEL selector = @selector(downloadTaskWithURL:completionHandler:);
  494. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  495. IMP currentIMP = selectorInstrumentor.currentIMP;
  496. [selectorInstrumentor setReplacingBlock:^(id session, NSURL *URL,
  497. FPRDownloadTaskCompletionHandler completionHandler) {
  498. __block NSURLSessionDownloadTask *downloadTask = nil;
  499. FPRDownloadTaskCompletionHandler wrappedCompletionHandler = nil;
  500. if (completionHandler) {
  501. wrappedCompletionHandler = ^(NSURL *location, NSURLResponse *response, NSError *error) {
  502. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:downloadTask];
  503. [trace didReceiveFileURL:location];
  504. [trace didCompleteRequestWithResponse:response error:error];
  505. completionHandler(location, response, error);
  506. };
  507. }
  508. typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURL *,
  509. FPRDownloadTaskCompletionHandler);
  510. downloadTask = ((OriginalImp)currentIMP)(session, selector, URL, wrappedCompletionHandler);
  511. // Add the network trace object only when the trace object is not added to the task object.
  512. if ([FPRNetworkTrace networkTraceFromObject:downloadTask] == nil) {
  513. FPRNetworkTrace *trace =
  514. [[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
  515. [trace start];
  516. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  517. [FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
  518. }
  519. return downloadTask;
  520. }];
  521. }
  522. /** Instruments -downloadTaskWithRequest:.
  523. *
  524. * @param instrument The FPRNSURLSessionInstrument instance.
  525. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  526. */
  527. FOUNDATION_STATIC_INLINE
  528. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  529. void InstrumentDownloadTaskWithRequest(FPRNSURLSessionInstrument *instrument,
  530. FPRClassInstrumentor *instrumentor) {
  531. SEL selector = @selector(downloadTaskWithRequest:);
  532. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  533. __weak FPRNSURLSessionInstrument *weakInstrument = instrument;
  534. IMP currentIMP = selectorInstrumentor.currentIMP;
  535. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request) {
  536. __strong FPRNSURLSessionInstrument *strongInstrument = weakInstrument;
  537. if (!strongInstrument) {
  538. ThrowExceptionBecauseInstrumentHasBeenDeallocated(selector, instrumentor.instrumentedClass);
  539. }
  540. typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURLRequest *);
  541. NSURLSessionDownloadTask *downloadTask = ((OriginalImp)currentIMP)(session, selector, request);
  542. if (downloadTask.originalRequest) {
  543. FPRNetworkTrace *trace =
  544. [[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
  545. [trace start];
  546. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  547. [FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
  548. }
  549. return downloadTask;
  550. }];
  551. }
  552. /** Instruments -downloadTaskWithRequest:completionHandler:.
  553. *
  554. * @param instrument The FPRNSURLSessionInstrument instance.
  555. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  556. */
  557. FOUNDATION_STATIC_INLINE
  558. NS_EXTENSION_UNAVAILABLE("Firebase Performance is not supported for extensions.")
  559. void InstrumentDownloadTaskWithRequestCompletionHandler(FPRNSURLSessionInstrument *instrument,
  560. FPRClassInstrumentor *instrumentor) {
  561. SEL selector = @selector(downloadTaskWithRequest:completionHandler:);
  562. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  563. IMP currentIMP = selectorInstrumentor.currentIMP;
  564. [selectorInstrumentor setReplacingBlock:^(id session, NSURLRequest *request,
  565. FPRDownloadTaskCompletionHandler completionHandler) {
  566. __block NSURLSessionDownloadTask *downloadTask = nil;
  567. FPRDownloadTaskCompletionHandler wrappedCompletionHandler = nil;
  568. if (completionHandler) {
  569. wrappedCompletionHandler = ^(NSURL *location, NSURLResponse *response, NSError *error) {
  570. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:downloadTask];
  571. [trace didReceiveFileURL:location];
  572. [trace didCompleteRequestWithResponse:response error:error];
  573. completionHandler(location, response, error);
  574. };
  575. }
  576. typedef NSURLSessionDownloadTask *(*OriginalImp)(id, SEL, NSURLRequest *,
  577. FPRDownloadTaskCompletionHandler);
  578. downloadTask = ((OriginalImp)currentIMP)(session, selector, request, wrappedCompletionHandler);
  579. // Add the network trace object only when the trace object is not added to the task object.
  580. if ([FPRNetworkTrace networkTraceFromObject:downloadTask] == nil) {
  581. FPRNetworkTrace *trace =
  582. [[FPRNetworkTrace alloc] initWithURLRequest:downloadTask.originalRequest];
  583. [trace start];
  584. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  585. [FPRNetworkTrace addNetworkTrace:trace toObject:downloadTask];
  586. }
  587. return downloadTask;
  588. }];
  589. }
  590. #pragma mark - FPRNSURLSessionInstrument
  591. @implementation FPRNSURLSessionInstrument
  592. - (instancetype)init {
  593. self = [super init];
  594. if (self) {
  595. _delegateInstrument = [[FPRNSURLSessionDelegateInstrument alloc] init];
  596. [_delegateInstrument registerInstrumentors];
  597. }
  598. return self;
  599. }
  600. - (void)registerInstrumentors {
  601. [self registerInstrumentorForClass:[NSURLSession class]];
  602. }
  603. - (void)deregisterInstrumentors {
  604. [_delegateInstrument deregisterInstrumentors];
  605. [super deregisterInstrumentors];
  606. }
  607. - (void)registerInstrumentorForClass:(Class)aClass {
  608. dispatch_sync(GetInstrumentationQueue(), ^{
  609. FPRAssert([aClass isSubclassOfClass:[NSURLSession class]],
  610. @"Class %@ is not a subclass of "
  611. "NSURLSession",
  612. aClass);
  613. // If this class has already been instrumented, just return.
  614. FPRClassInstrumentor *instrumentor = [[FPRClassInstrumentor alloc] initWithClass:aClass];
  615. if (![self registerClassInstrumentor:instrumentor]) {
  616. return;
  617. }
  618. InstrumentSharedSession(self, instrumentor);
  619. InstrumentSessionWithConfiguration(self, instrumentor);
  620. InstrumentSessionWithConfigurationDelegateDelegateQueue(self, instrumentor,
  621. _delegateInstrument);
  622. InstrumentDataTaskWithURL(self, instrumentor);
  623. InstrumentDataTaskWithURLCompletionHandler(self, instrumentor);
  624. InstrumentDataTaskWithRequest(self, instrumentor);
  625. InstrumentDataTaskWithRequestCompletionHandler(self, instrumentor);
  626. InstrumentUploadTaskWithRequestFromFile(self, instrumentor);
  627. InstrumentUploadTaskWithRequestFromFileCompletionHandler(self, instrumentor);
  628. InstrumentUploadTaskWithRequestFromData(self, instrumentor);
  629. InstrumentUploadTaskWithRequestFromDataCompletionHandler(self, instrumentor);
  630. InstrumentUploadTaskWithStreamedRequest(self, instrumentor);
  631. InstrumentDownloadTaskWithURL(self, instrumentor);
  632. InstrumentDownloadTaskWithURLCompletionHandler(self, instrumentor);
  633. InstrumentDownloadTaskWithRequest(self, instrumentor);
  634. InstrumentDownloadTaskWithRequestCompletionHandler(self, instrumentor);
  635. [instrumentor swizzle];
  636. });
  637. }
  638. - (void)registerProxyObject:(id)proxy {
  639. [FPRProxyObjectHelper registerProxyObject:proxy
  640. forSuperclass:[NSURLSession class]
  641. varFoundHandler:^(id ivar) {
  642. [self registerInstrumentorForClass:[ivar class]];
  643. }];
  644. }
  645. @end