FPRNSURLSessionDelegateInstrument.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. #import "FirebasePerformance/Sources/Instrumentation/Network/Delegates/FPRNSURLSessionDelegateInstrument.h"
  15. #import "FirebasePerformance/Sources/FPRConsoleLogger.h"
  16. #import "FirebasePerformance/Sources/Instrumentation/FPRClassInstrumentor.h"
  17. #import "FirebasePerformance/Sources/Instrumentation/FPRInstrument_Private.h"
  18. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace.h"
  19. #import "FirebasePerformance/Sources/Instrumentation/FPRSelectorInstrumentor.h"
  20. #import "FirebasePerformance/Sources/Instrumentation/Network/Delegates/FPRNSURLSessionDelegate.h"
  21. #import "FirebasePerformance/Sources/Instrumentation/Network/FPRNetworkInstrumentHelpers.h"
  22. /** Returns the dispatch queue for all instrumentation to occur on. */
  23. static dispatch_queue_t GetInstrumentationQueue() {
  24. static dispatch_queue_t queue;
  25. static dispatch_once_t token;
  26. dispatch_once(&token, ^{
  27. queue = dispatch_queue_create("com.google.FPRNSURLSessionDelegateInstrument",
  28. DISPATCH_QUEUE_SERIAL);
  29. });
  30. return queue;
  31. }
  32. #pragma mark - NSURLSessionTaskDelegate methods
  33. /** Instruments URLSession:task:didCompleteWithError:.
  34. *
  35. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  36. */
  37. FOUNDATION_STATIC_INLINE
  38. void InstrumentURLSessionTaskDidCompleteWithError(FPRClassInstrumentor *instrumentor) {
  39. SEL selector = @selector(URLSession:task:didCompleteWithError:);
  40. FPRSelectorInstrumentor *selectorInstrumentor =
  41. [instrumentor instrumentorForInstanceSelector:selector];
  42. if (selectorInstrumentor) {
  43. IMP currentIMP = selectorInstrumentor.currentIMP;
  44. [selectorInstrumentor setReplacingBlock:^(id object, NSURLSession *session,
  45. NSURLSessionTask *task, NSError *error) {
  46. @try {
  47. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:task];
  48. [trace didCompleteRequestWithResponse:task.response error:error];
  49. [FPRNetworkTrace removeNetworkTraceFromObject:task];
  50. } @catch (NSException *exception) {
  51. FPRLogInfo(kFPRNetworkTraceNotTrackable, @"Unable to track network request.");
  52. } @finally {
  53. typedef void (*OriginalImp)(id, SEL, NSURLSession *, NSURLSessionTask *, NSError *);
  54. ((OriginalImp)currentIMP)(object, selector, session, task, error);
  55. }
  56. }];
  57. }
  58. }
  59. /** Instruments URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:.
  60. *
  61. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  62. */
  63. FOUNDATION_STATIC_INLINE
  64. void InstrumentURLSessionTaskDidSendBodyDataTotalBytesSentTotalBytesExpectedToSend(
  65. FPRClassInstrumentor *instrumentor) {
  66. SEL selector = @selector(URLSession:
  67. task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:);
  68. FPRSelectorInstrumentor *selectorInstrumentor =
  69. [instrumentor instrumentorForInstanceSelector:selector];
  70. if (selectorInstrumentor) {
  71. IMP currentIMP = selectorInstrumentor.currentIMP;
  72. [selectorInstrumentor
  73. setReplacingBlock:^(id object, NSURLSession *session, NSURLSessionTask *task,
  74. int64_t bytesSent, int64_t totalBytesSent,
  75. int64_t totalBytesExpectedToSend) {
  76. @try {
  77. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:task];
  78. trace.requestSize = totalBytesSent;
  79. if (totalBytesSent >= totalBytesExpectedToSend) {
  80. if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
  81. NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
  82. [trace didCompleteRequestWithResponse:response error:task.error];
  83. [FPRNetworkTrace removeNetworkTraceFromObject:task];
  84. }
  85. }
  86. } @catch (NSException *exception) {
  87. FPRLogInfo(kFPRNetworkTraceNotTrackable, @"Unable to track network request.");
  88. } @finally {
  89. typedef void (*OriginalImp)(id, SEL, NSURLSession *, NSURLSessionTask *, int64_t,
  90. int64_t, int64_t);
  91. ((OriginalImp)currentIMP)(object, selector, session, task, bytesSent, totalBytesSent,
  92. totalBytesExpectedToSend);
  93. }
  94. }];
  95. }
  96. }
  97. #pragma mark - NSURLSessionDataDelegate methods
  98. /** Instruments URLSession:dataTask:didReceiveData:.
  99. *
  100. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  101. */
  102. FOUNDATION_STATIC_INLINE
  103. void InstrumentURLSessionDataTaskDidReceiveData(FPRClassInstrumentor *instrumentor) {
  104. SEL selector = @selector(URLSession:dataTask:didReceiveData:);
  105. FPRSelectorInstrumentor *selectorInstrumentor =
  106. [instrumentor instrumentorForInstanceSelector:selector];
  107. if (selectorInstrumentor) {
  108. IMP currentIMP = selectorInstrumentor.currentIMP;
  109. [selectorInstrumentor setReplacingBlock:^(id object, NSURLSession *session,
  110. NSURLSessionDataTask *dataTask, NSData *data) {
  111. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:dataTask];
  112. [trace didReceiveData:data];
  113. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  114. typedef void (*OriginalImp)(id, SEL, NSURLSession *, NSURLSessionDataTask *, NSData *);
  115. ((OriginalImp)currentIMP)(object, selector, session, dataTask, data);
  116. }];
  117. }
  118. }
  119. #pragma mark - NSURLSessionDownloadDelegate methods.
  120. /** Instruments URLSession:downloadTask:didFinishDownloadingToURL:.
  121. *
  122. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  123. */
  124. FOUNDATION_STATIC_INLINE
  125. void InstrumentURLSessionDownloadTaskDidFinishDownloadToURL(FPRClassInstrumentor *instrumentor) {
  126. SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:);
  127. FPRSelectorInstrumentor *selectorInstrumentor =
  128. [instrumentor instrumentorForInstanceSelector:selector];
  129. if (selectorInstrumentor) {
  130. IMP currentIMP = selectorInstrumentor.currentIMP;
  131. [selectorInstrumentor
  132. setReplacingBlock:^(id object, NSURLSession *session,
  133. NSURLSessionDownloadTask *downloadTask, NSURL *location) {
  134. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:downloadTask];
  135. [trace didReceiveFileURL:location];
  136. [trace didCompleteRequestWithResponse:downloadTask.response error:downloadTask.error];
  137. [FPRNetworkTrace removeNetworkTraceFromObject:downloadTask];
  138. typedef void (*OriginalImp)(id, SEL, NSURLSession *, NSURLSessionDownloadTask *, NSURL *);
  139. ((OriginalImp)currentIMP)(object, selector, session, downloadTask, location);
  140. }];
  141. }
  142. }
  143. /** Instruments URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:.
  144. *
  145. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  146. */
  147. FOUNDATION_STATIC_INLINE
  148. void InstrumentURLSessionDownloadTaskDidWriteDataTotalBytesWrittenTotalBytesExpectedToWrite(
  149. FPRClassInstrumentor *instrumentor) {
  150. SEL selector = @selector(URLSession:
  151. downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:);
  152. FPRSelectorInstrumentor *selectorInstrumentor =
  153. [instrumentor instrumentorForInstanceSelector:selector];
  154. if (selectorInstrumentor) {
  155. IMP currentIMP = selectorInstrumentor.currentIMP;
  156. [selectorInstrumentor
  157. setReplacingBlock:^(id object, NSURLSession *session,
  158. NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten,
  159. int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  160. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:downloadTask];
  161. [trace checkpointState:FPRNetworkTraceCheckpointStateResponseReceived];
  162. trace.responseSize = totalBytesWritten;
  163. if (totalBytesWritten >= totalBytesExpectedToWrite) {
  164. if ([downloadTask.response isKindOfClass:[NSHTTPURLResponse class]]) {
  165. NSHTTPURLResponse *response = (NSHTTPURLResponse *)downloadTask.response;
  166. [trace didCompleteRequestWithResponse:response error:downloadTask.error];
  167. [FPRNetworkTrace removeNetworkTraceFromObject:downloadTask];
  168. }
  169. }
  170. typedef void (*OriginalImp)(id, SEL, NSURLSession *, NSURLSessionDownloadTask *, int64_t,
  171. int64_t, int64_t);
  172. ((OriginalImp)currentIMP)(object, selector, session, downloadTask, bytesWritten,
  173. totalBytesWritten, totalBytesExpectedToWrite);
  174. }];
  175. }
  176. }
  177. #pragma mark - Helper functions
  178. FOUNDATION_STATIC_INLINE
  179. void CopySelector(SEL selector, FPRObjectInstrumentor *instrumentor) {
  180. static Class fromClass = Nil;
  181. static dispatch_once_t onceToken;
  182. dispatch_once(&onceToken, ^{
  183. fromClass = [FPRNSURLSessionDelegate class];
  184. });
  185. if (![instrumentor.instrumentedObject respondsToSelector:selector]) {
  186. [instrumentor copySelector:selector fromClass:fromClass isClassSelector:NO];
  187. }
  188. }
  189. #pragma mark - FPRNSURLSessionDelegateInstrument
  190. @implementation FPRNSURLSessionDelegateInstrument
  191. - (void)registerInstrumentors {
  192. // Do nothing by default; classes will be instrumented on-demand upon discovery.
  193. }
  194. - (void)registerClass:(Class)aClass {
  195. dispatch_sync(GetInstrumentationQueue(), ^{
  196. // If this class has already been instrumented, just return.
  197. FPRClassInstrumentor *instrumentor = [[FPRClassInstrumentor alloc] initWithClass:aClass];
  198. if (![self registerClassInstrumentor:instrumentor]) {
  199. return;
  200. }
  201. // NSURLSessionTaskDelegate methods.
  202. InstrumentURLSessionTaskDidCompleteWithError(instrumentor);
  203. InstrumentURLSessionTaskDidSendBodyDataTotalBytesSentTotalBytesExpectedToSend(instrumentor);
  204. // NSURLSessionDataDelegate methods.
  205. InstrumentURLSessionDataTaskDidReceiveData(instrumentor);
  206. // NSURLSessionDownloadDelegate methods.
  207. InstrumentURLSessionDownloadTaskDidFinishDownloadToURL(instrumentor);
  208. InstrumentURLSessionDownloadTaskDidWriteDataTotalBytesWrittenTotalBytesExpectedToWrite(
  209. instrumentor);
  210. [instrumentor swizzle];
  211. });
  212. }
  213. - (void)registerObject:(id)object {
  214. dispatch_sync(GetInstrumentationQueue(), ^{
  215. if ([object respondsToSelector:@selector(gul_class)]) {
  216. return;
  217. }
  218. FPRObjectInstrumentor *instrumentor = [[FPRObjectInstrumentor alloc] initWithObject:object];
  219. // Register the non-swizzled versions of these methods.
  220. // NSURLSessionTaskDelegate methods.
  221. CopySelector(@selector(URLSession:task:didCompleteWithError:), instrumentor);
  222. CopySelector(@selector(URLSession:
  223. task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:),
  224. instrumentor);
  225. // NSURLSessionDataDelegate methods.
  226. CopySelector(@selector(URLSession:dataTask:didReceiveData:), instrumentor);
  227. // NSURLSessionDownloadDelegate methods.
  228. CopySelector(@selector(URLSession:downloadTask:didFinishDownloadingToURL:), instrumentor);
  229. CopySelector(@selector(URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:),
  230. instrumentor);
  231. CopySelector(@selector(URLSession:
  232. downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:),
  233. instrumentor);
  234. [instrumentor swizzle];
  235. });
  236. }
  237. @end