/core/externals/google-toolbox-for-mac/Foundation/GTMStackTrace.m

http://macfuse.googlecode.com/ · Objective C · 386 lines · 285 code · 39 blank · 62 comment · 58 complexity · 749fe5b5b59c01726e67c37bced77ae3 MD5 · raw file

  1. //
  2. // GTMStackTrace.m
  3. //
  4. // Copyright 2007-2008 Google Inc.
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License"); you may not
  7. // use this file except in compliance with the License. You may obtain a copy
  8. // of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. // License for the specific language governing permissions and limitations under
  16. // the License.
  17. //
  18. #include <stdlib.h>
  19. #include <dlfcn.h>
  20. #include <mach-o/nlist.h>
  21. #include "GTMStackTrace.h"
  22. #include "GTMObjC2Runtime.h"
  23. struct GTMClassDescription {
  24. const char *class_name;
  25. Method *class_methods;
  26. unsigned int class_method_count;
  27. Method *instance_methods;
  28. unsigned int instance_method_count;
  29. };
  30. #pragma mark Private utility functions
  31. static struct GTMClassDescription *GTMClassDescriptions(NSUInteger *total_count) {
  32. int class_count = objc_getClassList(nil, 0);
  33. struct GTMClassDescription *class_descs
  34. = calloc(class_count, sizeof(struct GTMClassDescription));
  35. if (class_descs) {
  36. Class *classes = calloc(class_count, sizeof(Class));
  37. if (classes) {
  38. objc_getClassList(classes, class_count);
  39. for (int i = 0; i < class_count; ++i) {
  40. class_descs[i].class_methods
  41. = class_copyMethodList(object_getClass(classes[i]),
  42. &class_descs[i].class_method_count);
  43. class_descs[i].instance_methods
  44. = class_copyMethodList(classes[i],
  45. &class_descs[i].instance_method_count);
  46. class_descs[i].class_name = class_getName(classes[i]);
  47. }
  48. free(classes);
  49. } else {
  50. // COV_NF_START - Don't know how to force this in a unittest
  51. free(class_descs);
  52. class_descs = NULL;
  53. class_count = 0;
  54. // COV_NF_END
  55. }
  56. }
  57. if (total_count) {
  58. *total_count = class_count;
  59. }
  60. return class_descs;
  61. }
  62. static void GTMFreeClassDescriptions(struct GTMClassDescription *class_descs,
  63. NSUInteger count) {
  64. if (!class_descs) return;
  65. for (NSUInteger i = 0; i < count; ++i) {
  66. if (class_descs[i].instance_methods) {
  67. free(class_descs[i].instance_methods);
  68. }
  69. if (class_descs[i].class_methods) {
  70. free(class_descs[i].class_methods);
  71. }
  72. }
  73. free(class_descs);
  74. }
  75. static NSUInteger GTMGetStackAddressDescriptorsForAddresses(void *pcs[],
  76. struct GTMAddressDescriptor outDescs[],
  77. NSUInteger count) {
  78. if (count < 1 || !pcs || !outDescs) return 0;
  79. NSUInteger class_desc_count;
  80. // Get our obj-c class descriptions. This is expensive, so we do it once
  81. // at the top. We go through this because dladdr doesn't work with
  82. // obj methods.
  83. struct GTMClassDescription *class_descs
  84. = GTMClassDescriptions(&class_desc_count);
  85. if (class_descs == NULL) {
  86. class_desc_count = 0;
  87. }
  88. // Iterate through the stack.
  89. for (NSUInteger i = 0; i < count; ++i) {
  90. const char *class_name = NULL;
  91. BOOL is_class_method = NO;
  92. size_t smallest_diff = SIZE_MAX;
  93. struct GTMAddressDescriptor *currDesc = &outDescs[i];
  94. currDesc->address = pcs[i];
  95. Method best_method = NULL;
  96. // Iterate through all the classes we know of.
  97. for (NSUInteger j = 0; j < class_desc_count; ++j) {
  98. // First check the class methods.
  99. for (NSUInteger k = 0; k < class_descs[j].class_method_count; ++k) {
  100. void *imp = (void *)method_getImplementation(class_descs[j].class_methods[k]);
  101. if (imp <= currDesc->address) {
  102. size_t diff = (size_t)currDesc->address - (size_t)imp;
  103. if (diff < smallest_diff) {
  104. best_method = class_descs[j].class_methods[k];
  105. class_name = class_descs[j].class_name;
  106. is_class_method = YES;
  107. smallest_diff = diff;
  108. }
  109. }
  110. }
  111. // Then check the instance methods.
  112. for (NSUInteger k = 0; k < class_descs[j].instance_method_count; ++k) {
  113. void *imp = (void *)method_getImplementation(class_descs[j].instance_methods[k]);
  114. if (imp <= currDesc->address) {
  115. size_t diff = (size_t)currDesc->address - (size_t)imp;
  116. if (diff < smallest_diff) {
  117. best_method = class_descs[j].instance_methods[k];
  118. class_name = class_descs[j].class_name;
  119. is_class_method = NO;
  120. smallest_diff = diff;
  121. }
  122. }
  123. }
  124. }
  125. // If we have one, store it off.
  126. if (best_method) {
  127. currDesc->symbol = sel_getName(method_getName(best_method));
  128. currDesc->is_class_method = is_class_method;
  129. currDesc->class_name = class_name;
  130. }
  131. Dl_info info = { NULL, NULL, NULL, NULL };
  132. // Check to see if the one returned by dladdr is better.
  133. dladdr(currDesc->address, &info);
  134. if ((size_t)currDesc->address - (size_t)info.dli_saddr < smallest_diff) {
  135. currDesc->symbol = info.dli_sname;
  136. currDesc->is_class_method = NO;
  137. currDesc->class_name = NULL;
  138. }
  139. currDesc->filename = info.dli_fname;
  140. if (!currDesc->symbol) {
  141. currDesc->symbol = "???";
  142. currDesc->is_class_method = NO;
  143. currDesc->class_name = NULL;
  144. }
  145. }
  146. GTMFreeClassDescriptions(class_descs, class_desc_count);
  147. return count;
  148. }
  149. static NSString *GTMStackTraceFromAddressDescriptors(struct GTMAddressDescriptor descs[],
  150. NSUInteger count) {
  151. NSMutableString *trace = [NSMutableString string];
  152. for (NSUInteger i = 0; i < count; i++) {
  153. // Newline between all the lines
  154. if (i) {
  155. [trace appendString:@"\n"];
  156. }
  157. NSString *fileName = nil;
  158. if (descs[i].filename) {
  159. fileName = [NSString stringWithCString:descs[i].filename
  160. encoding:NSUTF8StringEncoding];
  161. fileName = [fileName lastPathComponent];
  162. } else {
  163. fileName = @"??";
  164. }
  165. if (descs[i].class_name) {
  166. [trace appendFormat:@"#%-2lu %-35s %#0*lX %s[%s %s]",
  167. (unsigned long)i,
  168. [fileName UTF8String],
  169. // sizeof(void*) * 2 is the length of the hex address (32 vs 64) and + 2
  170. // for the 0x prefix
  171. (int)(sizeof(void *) * 2 + 2),
  172. (unsigned long)descs[i].address,
  173. (descs[i].is_class_method ? "+" : "-"),
  174. descs[i].class_name,
  175. (descs[i].symbol ? descs[i].symbol : "??")];
  176. } else {
  177. [trace appendFormat:@"#%-2lu %-35s %#0*lX %s()",
  178. (unsigned long)i,
  179. [fileName UTF8String],
  180. // sizeof(void*) * 2 is the length of the hex address (32 vs 64) and + 2
  181. // for the 0x prefix
  182. (int)(sizeof(void *) * 2 + 2),
  183. (unsigned long)descs[i].address,
  184. (descs[i].symbol ? descs[i].symbol : "??")];
  185. }
  186. }
  187. return trace;
  188. }
  189. #pragma mark Public functions
  190. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  191. // Before 10.5, we have to do this ourselves. 10.5 adds
  192. // +[NSThread callStackReturnAddresses].
  193. // Structure representing a small portion of a stack, starting from the saved
  194. // frame pointer, and continuing through the saved program counter.
  195. struct GTMStackFrame {
  196. void *saved_fp;
  197. #if defined (__ppc__) || defined(__ppc64__)
  198. void *padding;
  199. #endif
  200. void *saved_pc;
  201. };
  202. // __builtin_frame_address(0) is a gcc builtin that returns a pointer to the
  203. // current frame pointer. We then use the frame pointer to walk the stack
  204. // picking off program counters and other saved frame pointers. This works
  205. // great on i386, but PPC requires a little more work because the PC (or link
  206. // register) isn't always stored on the stack.
  207. //
  208. NSUInteger GTMGetStackProgramCounters(void *outPcs[], NSUInteger count) {
  209. if (!outPcs || (count < 1)) return 0;
  210. struct GTMStackFrame *fp;
  211. #if defined (__ppc__) || defined(__ppc64__)
  212. outPcs[0] = __builtin_return_address(0);
  213. fp = (struct GTMStackFrame *)__builtin_frame_address(1);
  214. #elif defined (__i386__) || defined(__x86_64__)
  215. fp = (struct GTMStackFrame *)__builtin_frame_address(0);
  216. #else
  217. #error architecture not supported
  218. #endif
  219. NSUInteger level = 0;
  220. while (level < count) {
  221. if (fp == NULL) {
  222. level--;
  223. break;
  224. }
  225. outPcs[level] = fp->saved_pc;
  226. level++;
  227. fp = (struct GTMStackFrame *)fp->saved_fp;
  228. }
  229. return level;
  230. }
  231. #endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232. NSUInteger GTMGetStackAddressDescriptors(struct GTMAddressDescriptor outDescs[],
  233. NSUInteger count) {
  234. if (count < 1 || !outDescs) return 0;
  235. NSUInteger result = 0;
  236. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  237. // Before 10.5, we collect the stack ourselves.
  238. void **pcs = calloc(count, sizeof(void*));
  239. if (!pcs) return 0;
  240. NSUInteger newSize = GTMGetStackProgramCounters(pcs, count);
  241. result = GTMGetStackAddressDescriptorsForAddresses(pcs, outDescs, newSize);
  242. free(pcs);
  243. #else // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  244. // Use +[NSThread callStackReturnAddresses]
  245. NSArray *addresses = [NSThread callStackReturnAddresses];
  246. NSUInteger addrCount = [addresses count];
  247. if (addrCount) {
  248. void **pcs = calloc(addrCount, sizeof(void*));
  249. if (pcs) {
  250. void **pcsScanner = pcs;
  251. for (NSNumber *address in addresses) {
  252. NSUInteger addr = [address unsignedIntegerValue];
  253. *pcsScanner = (void *)addr;
  254. ++pcsScanner;
  255. }
  256. if (count < addrCount) {
  257. addrCount = count;
  258. }
  259. // Fill in the desc structures
  260. result = GTMGetStackAddressDescriptorsForAddresses(pcs, outDescs, addrCount);
  261. }
  262. free(pcs);
  263. }
  264. #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  265. return result;
  266. }
  267. NSString *GTMStackTrace(void) {
  268. // If we don't have enough frames, return an empty string
  269. NSString *result = @"";
  270. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  271. // Before 10.5, we collect the stack ourselves.
  272. // The maximum number of stack frames that we will walk. We limit this so
  273. // that super-duper recursive functions (or bugs) don't send us for an
  274. // infinite loop.
  275. struct GTMAddressDescriptor descs[100];
  276. size_t depth = sizeof(descs) / sizeof(struct GTMAddressDescriptor);
  277. depth = GTMGetStackAddressDescriptors(descs, depth);
  278. // Start at the second item so that GTMStackTrace and it's utility calls (of
  279. // which there is currently 1) is not included in the output.
  280. const size_t kTracesToStrip = 2;
  281. if (depth > kTracesToStrip) {
  282. result = GTMStackTraceFromAddressDescriptors(&descs[kTracesToStrip],
  283. (depth - kTracesToStrip));
  284. }
  285. #else // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  286. // Use +[NSThread callStackReturnAddresses]
  287. NSArray *addresses = [NSThread callStackReturnAddresses];
  288. NSUInteger count = [addresses count];
  289. if (count) {
  290. void **pcs = calloc(count, sizeof(void*));
  291. struct GTMAddressDescriptor *descs
  292. = calloc(count, sizeof(struct GTMAddressDescriptor));
  293. if (pcs && descs) {
  294. void **pcsScanner = pcs;
  295. for (NSNumber *address in addresses) {
  296. NSUInteger addr = [address unsignedIntegerValue];
  297. *pcsScanner = (void *)addr;
  298. ++pcsScanner;
  299. }
  300. // Fill in the desc structures
  301. count = GTMGetStackAddressDescriptorsForAddresses(pcs, descs, count);
  302. // Build the trace
  303. // We skip 1 frame because the +[NSThread callStackReturnAddresses] will
  304. // start w/ this frame.
  305. const size_t kTracesToStrip = 1;
  306. if (count > kTracesToStrip) {
  307. result = GTMStackTraceFromAddressDescriptors(&descs[kTracesToStrip],
  308. (count - kTracesToStrip));
  309. }
  310. }
  311. free(pcs);
  312. free(descs);
  313. }
  314. #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  315. return result;
  316. }
  317. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 || \
  318. (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && \
  319. (__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_2_0))
  320. NSString *GTMStackTraceFromException(NSException *e) {
  321. NSString *trace = @"";
  322. // collect the addresses
  323. NSArray *addresses = [e callStackReturnAddresses];
  324. NSUInteger count = [addresses count];
  325. if (count) {
  326. void **pcs = calloc(count, sizeof(void*));
  327. struct GTMAddressDescriptor *descs
  328. = calloc(count, sizeof(struct GTMAddressDescriptor));
  329. if (pcs && descs) {
  330. void **pcsScanner = pcs;
  331. for (NSNumber *address in addresses) {
  332. NSUInteger addr = [address unsignedIntegerValue];
  333. *pcsScanner = (void *)addr;
  334. ++pcsScanner;
  335. }
  336. // Fill in the desc structures
  337. count = GTMGetStackAddressDescriptorsForAddresses(pcs, descs, count);
  338. // Build the trace
  339. trace = GTMStackTraceFromAddressDescriptors(descs, count);
  340. }
  341. free(pcs);
  342. free(descs);
  343. }
  344. return trace;
  345. }
  346. #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  347. //__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_2_0