FPRNSURLConnectionInstrument.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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/FPRNSURLConnectionInstrument.h"
  15. #import "FirebasePerformance/Sources/Instrumentation/Network/FPRNSURLConnectionInstrument_Private.h"
  16. #import "FirebasePerformance/Sources/Common/FPRDiagnostics.h"
  17. #import "FirebasePerformance/Sources/Instrumentation/FPRClassInstrumentor.h"
  18. #import "FirebasePerformance/Sources/Instrumentation/FPRInstrument_Private.h"
  19. #import "FirebasePerformance/Sources/Instrumentation/FPRNetworkTrace.h"
  20. #import "FirebasePerformance/Sources/Instrumentation/FPRObjectInstrumentor.h"
  21. #import "FirebasePerformance/Sources/Instrumentation/FPRSelectorInstrumentor.h"
  22. #import "FirebasePerformance/Sources/Instrumentation/Network/Delegates/FPRNSURLConnectionDelegate.h"
  23. #import "FirebasePerformance/Sources/Instrumentation/Network/FPRNetworkInstrumentHelpers.h"
  24. #import <GoogleUtilities/GULObjectSwizzler.h>
  25. #import "FirebasePerformance/Sources/Configurations/FPRConfigurations.h"
  26. static NSString *const kFPRDelegateKey = @"kFPRDelegateKey";
  27. typedef void (^FPRNSURLConnectionCompletionHandler)(NSURLResponse *_Nullable response,
  28. NSData *_Nullable data,
  29. NSError *_Nullable connectionError);
  30. /** Returns the dispatch queue for all instrumentation to occur on. */
  31. static dispatch_queue_t GetInstrumentationQueue() {
  32. static dispatch_queue_t queue = nil;
  33. static dispatch_once_t token = 0;
  34. dispatch_once(&token, ^{
  35. queue = dispatch_queue_create("com.google.FPRNSURLConnectionInstrumentation",
  36. DISPATCH_QUEUE_SERIAL);
  37. });
  38. return queue;
  39. }
  40. /** Instruments +sendAsynchronousRequest:queue:completionHandler:.
  41. *
  42. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  43. */
  44. FOUNDATION_STATIC_INLINE
  45. void InstrumentSendAsynchronousRequestQueueCompletionHandler(FPRClassInstrumentor *instrumentor) {
  46. SEL selector = @selector(sendAsynchronousRequest:queue:completionHandler:);
  47. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, YES);
  48. IMP currentIMP = selectorInstrumentor.currentIMP;
  49. [selectorInstrumentor
  50. setReplacingBlock:^(id connection, NSURLRequest *request, NSOperationQueue *queue,
  51. FPRNSURLConnectionCompletionHandler completionHandler) {
  52. FPRNetworkTrace *trace = [[FPRNetworkTrace alloc] initWithURLRequest:request];
  53. [trace start];
  54. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  55. // The completionHandler needs to be there for FPRNetworkTrace purposes, even if originally
  56. // nil.
  57. FPRNSURLConnectionCompletionHandler wrappedCompletionHandler =
  58. ^(NSURLResponse *_Nullable response, NSData *_Nullable data,
  59. NSError *_Nullable connectionError) {
  60. [trace didReceiveData:data];
  61. [trace didCompleteRequestWithResponse:response error:connectionError];
  62. if (completionHandler) {
  63. completionHandler(response, data, connectionError);
  64. }
  65. };
  66. typedef void (*OriginalImp)(id, SEL, NSURLRequest *, NSOperationQueue *,
  67. FPRNSURLConnectionCompletionHandler);
  68. ((OriginalImp)currentIMP)(connection, selector, request, queue, wrappedCompletionHandler);
  69. }];
  70. }
  71. /** Instruments -initWithRequest:delegate:.
  72. *
  73. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  74. * @param delegateInstrument The FPRNSURLConnectionDelegateInstrument to potentially add a new
  75. * class to.
  76. */
  77. FOUNDATION_STATIC_INLINE
  78. void InstrumentInitWithRequestDelegate(FPRClassInstrumentor *instrumentor,
  79. FPRNSURLConnectionDelegateInstrument *delegateInstrument) {
  80. SEL selector = @selector(initWithRequest:delegate:);
  81. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  82. IMP currentIMP = selectorInstrumentor.currentIMP;
  83. [selectorInstrumentor setReplacingBlock:^(id connection, NSURLRequest *request, id delegate) {
  84. if (delegate) {
  85. [delegateInstrument registerClass:[delegate class]];
  86. [delegateInstrument registerObject:delegate];
  87. [GULObjectSwizzler setAssociatedObject:connection
  88. key:kFPRDelegateKey
  89. value:delegate
  90. association:GUL_ASSOCIATION_ASSIGN];
  91. } else {
  92. delegate = [[FPRNSURLConnectionDelegate alloc] init];
  93. [GULObjectSwizzler setAssociatedObject:connection
  94. key:kFPRDelegateKey
  95. value:delegate
  96. association:GUL_ASSOCIATION_ASSIGN];
  97. }
  98. typedef NSURLConnection *(*OriginalImp)(id, SEL, NSURLRequest *, id);
  99. return ((OriginalImp)currentIMP)(connection, selector, request, delegate);
  100. }];
  101. }
  102. /** Instruments -initWithRequest:delegate:startImmediately:.
  103. *
  104. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  105. * @param delegateInstrument The FPRNSURLConnectionDelegateInstrument to potentially add a new
  106. * class to.
  107. */
  108. FOUNDATION_STATIC_INLINE
  109. void InstrumentInitWithRequestDelegateStartImmediately(
  110. FPRClassInstrumentor *instrumentor, FPRNSURLConnectionDelegateInstrument *delegateInstrument) {
  111. SEL selector = @selector(initWithRequest:delegate:startImmediately:);
  112. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  113. IMP currentIMP = selectorInstrumentor.currentIMP;
  114. [selectorInstrumentor setReplacingBlock:^(id connection, NSURLRequest *request, id delegate,
  115. BOOL startImmediately) {
  116. if (delegate) {
  117. [delegateInstrument registerClass:[delegate class]];
  118. [delegateInstrument registerObject:delegate];
  119. [GULObjectSwizzler setAssociatedObject:connection
  120. key:kFPRDelegateKey
  121. value:delegate
  122. association:GUL_ASSOCIATION_ASSIGN];
  123. } else {
  124. delegate = [[FPRNSURLConnectionDelegate alloc] init];
  125. [GULObjectSwizzler setAssociatedObject:connection
  126. key:kFPRDelegateKey
  127. value:delegate
  128. association:GUL_ASSOCIATION_ASSIGN];
  129. }
  130. typedef NSURLConnection *(*OriginalImp)(id, SEL, NSURLRequest *, id, BOOL);
  131. return ((OriginalImp)currentIMP)(connection, selector, request, delegate, startImmediately);
  132. }];
  133. }
  134. /** Instruments -start.
  135. *
  136. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  137. */
  138. FOUNDATION_STATIC_INLINE
  139. void InstrumentConnectionStart(FPRClassInstrumentor *instrumentor) {
  140. SEL selector = @selector(start);
  141. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  142. IMP currentIMP = selectorInstrumentor.currentIMP;
  143. [selectorInstrumentor setReplacingBlock:^(id object) {
  144. typedef void (*OriginalImp)(id, SEL);
  145. NSURLConnection *connection = (NSURLConnection *)object;
  146. if ([GULObjectSwizzler getAssociatedObject:connection key:kFPRDelegateKey]) {
  147. FPRNetworkTrace *trace =
  148. [[FPRNetworkTrace alloc] initWithURLRequest:connection.originalRequest];
  149. [trace start];
  150. [trace checkpointState:FPRNetworkTraceCheckpointStateInitiated];
  151. [FPRNetworkTrace addNetworkTrace:trace toObject:connection];
  152. }
  153. ((OriginalImp)currentIMP)(connection, selector);
  154. }];
  155. }
  156. /** Instruments -cancel.
  157. *
  158. * @param instrumentor The FPRClassInstrumentor to add the selector instrumentor to.
  159. */
  160. FOUNDATION_STATIC_INLINE
  161. void InstrumentConnectionCancel(FPRClassInstrumentor *instrumentor) {
  162. SEL selector = @selector(cancel);
  163. FPRSelectorInstrumentor *selectorInstrumentor = SelectorInstrumentor(selector, instrumentor, NO);
  164. IMP currentIMP = selectorInstrumentor.currentIMP;
  165. [selectorInstrumentor setReplacingBlock:^(id object) {
  166. typedef void (*OriginalImp)(id, SEL);
  167. NSURLConnection *connection = (NSURLConnection *)object;
  168. FPRNetworkTrace *trace = [FPRNetworkTrace networkTraceFromObject:connection];
  169. [trace didCompleteRequestWithResponse:nil error:nil];
  170. [FPRNetworkTrace removeNetworkTraceFromObject:connection];
  171. ((OriginalImp)currentIMP)(connection, selector);
  172. }];
  173. }
  174. @implementation FPRNSURLConnectionInstrument
  175. - (instancetype)init {
  176. self = [super init];
  177. if (self) {
  178. _delegateInstrument = [[FPRNSURLConnectionDelegateInstrument alloc] init];
  179. [_delegateInstrument registerInstrumentors];
  180. }
  181. return self;
  182. }
  183. - (void)dealloc {
  184. [_delegateInstrument deregisterInstrumentors];
  185. }
  186. - (void)registerInstrumentors {
  187. dispatch_sync(GetInstrumentationQueue(), ^{
  188. FPRClassInstrumentor *instrumentor =
  189. [[FPRClassInstrumentor alloc] initWithClass:[NSURLConnection class]];
  190. if (![self registerClassInstrumentor:instrumentor]) {
  191. FPRAssert(NO, @"NSURLConnection should only be instrumented once.");
  192. }
  193. InstrumentSendAsynchronousRequestQueueCompletionHandler(instrumentor);
  194. InstrumentInitWithRequestDelegate(instrumentor, _delegateInstrument);
  195. InstrumentInitWithRequestDelegateStartImmediately(instrumentor, _delegateInstrument);
  196. InstrumentConnectionStart(instrumentor);
  197. InstrumentConnectionCancel(instrumentor);
  198. [instrumentor swizzle];
  199. });
  200. }
  201. - (void)deregisterInstrumentors {
  202. [_delegateInstrument deregisterInstrumentors];
  203. [super deregisterInstrumentors];
  204. }
  205. @end