FIRCLSProcess.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. // Copyright 2019 Google
  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. #include "Crashlytics/Crashlytics/Components/FIRCLSProcess.h"
  15. #include "Crashlytics/Crashlytics/Helpers/FIRCLSDefines.h"
  16. #include "Crashlytics/Crashlytics/Helpers/FIRCLSFeatures.h"
  17. #include "Crashlytics/Crashlytics/Components/FIRCLSGlobals.h"
  18. #include "Crashlytics/Crashlytics/Helpers/FIRCLSProfiling.h"
  19. #include "Crashlytics/Crashlytics/Helpers/FIRCLSThreadState.h"
  20. #include "Crashlytics/Crashlytics/Unwind/FIRCLSUnwind.h"
  21. #include "Crashlytics/Crashlytics/Helpers/FIRCLSUtility.h"
  22. #include <dispatch/dispatch.h>
  23. #include <objc/message.h>
  24. #include <pthread.h>
  25. #include <sys/sysctl.h>
  26. #define THREAD_NAME_BUFFER_SIZE (64)
  27. #pragma mark Prototypes
  28. static bool FIRCLSProcessGetThreadName(FIRCLSProcess *process,
  29. thread_t thread,
  30. char *buffer,
  31. size_t length);
  32. static const char *FIRCLSProcessGetThreadDispatchQueueName(FIRCLSProcess *process, thread_t thread);
  33. #pragma mark - API
  34. bool FIRCLSProcessInit(FIRCLSProcess *process, thread_t crashedThread, void *uapVoid) {
  35. if (!process) {
  36. return false;
  37. }
  38. process->task = mach_task_self();
  39. process->thisThread = mach_thread_self();
  40. process->crashedThread = crashedThread;
  41. process->uapVoid = uapVoid;
  42. if (task_threads(process->task, &process->threads, &process->threadCount) != KERN_SUCCESS) {
  43. // failed to get all threads
  44. process->threadCount = 0;
  45. FIRCLSSDKLog("Error: unable to get task threads\n");
  46. return false;
  47. }
  48. return true;
  49. }
  50. // https://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  51. bool FIRCLSProcessDebuggerAttached(void) {
  52. int junk;
  53. int mib[4];
  54. struct kinfo_proc info;
  55. size_t size;
  56. // Initialize the flags so that, if sysctl fails for some bizarre
  57. // reason, we get a predictable result.
  58. info.kp_proc.p_flag = 0;
  59. // Initialize mib, which tells sysctl the info we want, in this case
  60. // we're looking for information about a specific process ID.
  61. mib[0] = CTL_KERN;
  62. mib[1] = KERN_PROC;
  63. mib[2] = KERN_PROC_PID;
  64. mib[3] = getpid();
  65. // Call sysctl.
  66. size = sizeof(info);
  67. junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
  68. if (junk != 0) {
  69. FIRCLSSDKLog("sysctl failed while trying to get kinfo_proc\n");
  70. return false;
  71. }
  72. // We're being debugged if the P_TRACED flag is set.
  73. return (info.kp_proc.p_flag & P_TRACED) != 0;
  74. }
  75. #pragma mark - Thread Support
  76. static bool FIRCLSProcessIsCurrentThread(FIRCLSProcess *process, thread_t thread) {
  77. return MACH_PORT_INDEX(process->thisThread) == MACH_PORT_INDEX(thread);
  78. }
  79. static bool FIRCLSProcessIsCrashedThread(FIRCLSProcess *process, thread_t thread) {
  80. return MACH_PORT_INDEX(process->crashedThread) == MACH_PORT_INDEX(thread);
  81. }
  82. static uint32_t FIRCLSProcessGetThreadCount(FIRCLSProcess *process) {
  83. return process->threadCount;
  84. }
  85. static thread_t FIRCLSProcessGetThread(FIRCLSProcess *process, uint32_t index) {
  86. if (index >= process->threadCount) {
  87. return MACH_PORT_NULL;
  88. }
  89. return process->threads[index];
  90. }
  91. bool FIRCLSProcessSuspendAllOtherThreads(FIRCLSProcess *process) {
  92. mach_msg_type_number_t i;
  93. bool success;
  94. success = true;
  95. for (i = 0; i < process->threadCount; ++i) {
  96. thread_t thread;
  97. thread = FIRCLSProcessGetThread(process, i);
  98. if (FIRCLSProcessIsCurrentThread(process, thread)) {
  99. continue;
  100. }
  101. // FIXME: workaround to get this building on watch, but we need to suspend/resume threads!
  102. #if CLS_CAN_SUSPEND_THREADS
  103. success = success && (thread_suspend(thread) == KERN_SUCCESS);
  104. #endif
  105. }
  106. return success;
  107. }
  108. bool FIRCLSProcessResumeAllOtherThreads(FIRCLSProcess *process) {
  109. mach_msg_type_number_t i;
  110. bool success;
  111. success = true;
  112. for (i = 0; i < process->threadCount; ++i) {
  113. thread_t thread;
  114. thread = FIRCLSProcessGetThread(process, i);
  115. if (FIRCLSProcessIsCurrentThread(process, thread)) {
  116. continue;
  117. }
  118. // FIXME: workaround to get this building on watch, but we need to suspend/resume threads!
  119. #if CLS_CAN_SUSPEND_THREADS
  120. success = success && (thread_resume(thread) == KERN_SUCCESS);
  121. #endif
  122. }
  123. return success;
  124. }
  125. #pragma mark - Thread Properties
  126. void *FIRCLSThreadGetCurrentPC(void) {
  127. return __builtin_return_address(0);
  128. }
  129. static bool FIRCLSProcessGetThreadState(FIRCLSProcess *process,
  130. thread_t thread,
  131. FIRCLSThreadContext *context) {
  132. if (!FIRCLSIsValidPointer(context)) {
  133. FIRCLSSDKLogError("Invalid context supplied\n");
  134. return false;
  135. }
  136. // If the thread context we should use is non-NULL, then just assign it here. Otherwise,
  137. // query the thread state
  138. if (FIRCLSProcessIsCrashedThread(process, thread) && FIRCLSIsValidPointer(process->uapVoid)) {
  139. *context = *((_STRUCT_UCONTEXT *)process->uapVoid)->uc_mcontext;
  140. return true;
  141. }
  142. // Here's a wild trick: emulate what thread_get_state would do. It apppears that
  143. // we cannot reliably unwind out of thread_get_state. So, instead of trying, setup
  144. // a thread context that resembles what the real thing would look like
  145. if (FIRCLSProcessIsCurrentThread(process, thread)) {
  146. FIRCLSSDKLog("Faking current thread\n");
  147. memset(context, 0, sizeof(FIRCLSThreadContext));
  148. // Compute the frame address, and then base the stack value off of that. A frame pushes
  149. // two pointers onto the stack, so we have to offset.
  150. const uintptr_t frameAddress = (uintptr_t)__builtin_frame_address(0);
  151. const uintptr_t stackAddress = FIRCLSUnwindStackPointerFromFramePointer(frameAddress);
  152. #if CLS_CPU_X86_64
  153. context->__ss.__rip = (uintptr_t)FIRCLSThreadGetCurrentPC();
  154. context->__ss.__rbp = frameAddress;
  155. context->__ss.__rsp = stackAddress;
  156. #elif CLS_CPU_I386
  157. context->__ss.__eip = (uintptr_t)FIRCLSThreadGetCurrentPC();
  158. context->__ss.__ebp = frameAddress;
  159. context->__ss.__esp = stackAddress;
  160. #elif CLS_CPU_ARM64
  161. FIRCLSThreadContextSetPC(context, (uintptr_t)FIRCLSThreadGetCurrentPC());
  162. FIRCLSThreadContextSetFramePointer(context, frameAddress);
  163. FIRCLSThreadContextSetLinkRegister(context, (uintptr_t)__builtin_return_address(0));
  164. FIRCLSThreadContextSetStackPointer(context, stackAddress);
  165. #elif CLS_CPU_ARM
  166. context->__ss.__pc = (uintptr_t)FIRCLSThreadGetCurrentPC();
  167. context->__ss.__r[7] = frameAddress;
  168. context->__ss.__lr = (uintptr_t)__builtin_return_address(0);
  169. context->__ss.__sp = stackAddress;
  170. #endif
  171. return true;
  172. }
  173. #if !TARGET_OS_WATCH
  174. // try to get the value by querying the thread state
  175. mach_msg_type_number_t stateCount = FIRCLSThreadStateCount;
  176. // For unknown reasons, thread_get_state returns this value on Rosetta,
  177. // but still succeeds.
  178. const int ROSETTA_SUCCESS = 268435459;
  179. kern_return_t status = thread_get_state(thread, FIRCLSThreadState, (thread_state_t)(&(context->__ss)),
  180. &stateCount);
  181. if (status != KERN_SUCCESS && status != ROSETTA_SUCCESS) {
  182. FIRCLSSDKLogError("Failed to get thread state via thread_get_state for thread: %i\n", thread);
  183. return false;
  184. }
  185. return true;
  186. #else
  187. return false;
  188. #endif
  189. }
  190. static bool FIRCLSProcessGetThreadName(FIRCLSProcess *process,
  191. thread_t thread,
  192. char *buffer,
  193. size_t length) {
  194. pthread_t pthread;
  195. if (!buffer || length <= 0) {
  196. return false;
  197. }
  198. pthread = pthread_from_mach_thread_np(thread);
  199. return pthread_getname_np(pthread, buffer, length) == 0;
  200. }
  201. static const char *FIRCLSProcessGetThreadDispatchQueueName(FIRCLSProcess *process,
  202. thread_t thread) {
  203. thread_identifier_info_data_t info;
  204. mach_msg_type_number_t infoCount;
  205. dispatch_queue_t *queueAddress;
  206. dispatch_queue_t queue;
  207. const char *string;
  208. infoCount = THREAD_IDENTIFIER_INFO_COUNT;
  209. if (thread_info(thread, THREAD_IDENTIFIER_INFO, (thread_info_t)&info, &infoCount) !=
  210. KERN_SUCCESS) {
  211. FIRCLSSDKLog("Unable to get thread info\n");
  212. return NULL;
  213. }
  214. queueAddress = (dispatch_queue_t *)info.dispatch_qaddr;
  215. if (queueAddress == NULL) {
  216. return "";
  217. }
  218. // Sometimes a queue address is invalid. I cannot explain why this is, but
  219. // it can cause a crash.
  220. if (!FIRCLSReadMemory((vm_address_t)queueAddress, &queue, sizeof(void *))) {
  221. return "";
  222. }
  223. // here, we know it is safe to de-reference this address, so attempt to get the queue name
  224. if (!queue) {
  225. return "";
  226. }
  227. string = dispatch_queue_get_label(queue);
  228. // but, we still don't if the entire string is valid, so check that too
  229. if (!FIRCLSReadString((vm_address_t)string, (char **)&string, 128)) {
  230. return "";
  231. }
  232. return string;
  233. }
  234. #pragma mark - Data Recording
  235. static bool FIRCLSProcessRecordThreadRegisters(FIRCLSThreadContext context, FIRCLSFile *file) {
  236. #if CLS_CPU_ARM
  237. FIRCLSFileWriteHashEntryUint64(file, "r0", context.__ss.__r[0]);
  238. FIRCLSFileWriteHashEntryUint64(file, "r1", context.__ss.__r[1]);
  239. FIRCLSFileWriteHashEntryUint64(file, "r2", context.__ss.__r[2]);
  240. FIRCLSFileWriteHashEntryUint64(file, "r3", context.__ss.__r[3]);
  241. FIRCLSFileWriteHashEntryUint64(file, "r4", context.__ss.__r[4]);
  242. FIRCLSFileWriteHashEntryUint64(file, "r5", context.__ss.__r[5]);
  243. FIRCLSFileWriteHashEntryUint64(file, "r6", context.__ss.__r[6]);
  244. FIRCLSFileWriteHashEntryUint64(file, "r7", context.__ss.__r[7]);
  245. FIRCLSFileWriteHashEntryUint64(file, "r8", context.__ss.__r[8]);
  246. FIRCLSFileWriteHashEntryUint64(file, "r9", context.__ss.__r[9]);
  247. FIRCLSFileWriteHashEntryUint64(file, "r10", context.__ss.__r[10]);
  248. FIRCLSFileWriteHashEntryUint64(file, "r11", context.__ss.__r[11]);
  249. FIRCLSFileWriteHashEntryUint64(file, "ip", context.__ss.__r[12]);
  250. FIRCLSFileWriteHashEntryUint64(file, "sp", context.__ss.__sp);
  251. FIRCLSFileWriteHashEntryUint64(file, "lr", context.__ss.__lr);
  252. FIRCLSFileWriteHashEntryUint64(file, "pc", context.__ss.__pc);
  253. FIRCLSFileWriteHashEntryUint64(file, "cpsr", context.__ss.__cpsr);
  254. #elif CLS_CPU_ARM64
  255. FIRCLSFileWriteHashEntryUint64(file, "x0", context.__ss.__x[0]);
  256. FIRCLSFileWriteHashEntryUint64(file, "x1", context.__ss.__x[1]);
  257. FIRCLSFileWriteHashEntryUint64(file, "x2", context.__ss.__x[2]);
  258. FIRCLSFileWriteHashEntryUint64(file, "x3", context.__ss.__x[3]);
  259. FIRCLSFileWriteHashEntryUint64(file, "x4", context.__ss.__x[4]);
  260. FIRCLSFileWriteHashEntryUint64(file, "x5", context.__ss.__x[5]);
  261. FIRCLSFileWriteHashEntryUint64(file, "x6", context.__ss.__x[6]);
  262. FIRCLSFileWriteHashEntryUint64(file, "x7", context.__ss.__x[7]);
  263. FIRCLSFileWriteHashEntryUint64(file, "x8", context.__ss.__x[8]);
  264. FIRCLSFileWriteHashEntryUint64(file, "x9", context.__ss.__x[9]);
  265. FIRCLSFileWriteHashEntryUint64(file, "x10", context.__ss.__x[10]);
  266. FIRCLSFileWriteHashEntryUint64(file, "x11", context.__ss.__x[11]);
  267. FIRCLSFileWriteHashEntryUint64(file, "x12", context.__ss.__x[12]);
  268. FIRCLSFileWriteHashEntryUint64(file, "x13", context.__ss.__x[13]);
  269. FIRCLSFileWriteHashEntryUint64(file, "x14", context.__ss.__x[14]);
  270. FIRCLSFileWriteHashEntryUint64(file, "x15", context.__ss.__x[15]);
  271. FIRCLSFileWriteHashEntryUint64(file, "x16", context.__ss.__x[16]);
  272. FIRCLSFileWriteHashEntryUint64(file, "x17", context.__ss.__x[17]);
  273. FIRCLSFileWriteHashEntryUint64(file, "x18", context.__ss.__x[18]);
  274. FIRCLSFileWriteHashEntryUint64(file, "x19", context.__ss.__x[19]);
  275. FIRCLSFileWriteHashEntryUint64(file, "x20", context.__ss.__x[20]);
  276. FIRCLSFileWriteHashEntryUint64(file, "x21", context.__ss.__x[21]);
  277. FIRCLSFileWriteHashEntryUint64(file, "x22", context.__ss.__x[22]);
  278. FIRCLSFileWriteHashEntryUint64(file, "x23", context.__ss.__x[23]);
  279. FIRCLSFileWriteHashEntryUint64(file, "x24", context.__ss.__x[24]);
  280. FIRCLSFileWriteHashEntryUint64(file, "x25", context.__ss.__x[25]);
  281. FIRCLSFileWriteHashEntryUint64(file, "x26", context.__ss.__x[26]);
  282. FIRCLSFileWriteHashEntryUint64(file, "x27", context.__ss.__x[27]);
  283. FIRCLSFileWriteHashEntryUint64(file, "x28", context.__ss.__x[28]);
  284. FIRCLSFileWriteHashEntryUint64(file, "fp", FIRCLSThreadContextGetFramePointer(&context));
  285. FIRCLSFileWriteHashEntryUint64(file, "sp", FIRCLSThreadContextGetStackPointer(&context));
  286. FIRCLSFileWriteHashEntryUint64(file, "lr", FIRCLSThreadContextGetLinkRegister(&context));
  287. FIRCLSFileWriteHashEntryUint64(file, "pc", FIRCLSThreadContextGetPC(&context));
  288. FIRCLSFileWriteHashEntryUint64(file, "cpsr", context.__ss.__cpsr);
  289. #elif CLS_CPU_I386
  290. FIRCLSFileWriteHashEntryUint64(file, "eax", context.__ss.__eax);
  291. FIRCLSFileWriteHashEntryUint64(file, "ebx", context.__ss.__ebx);
  292. FIRCLSFileWriteHashEntryUint64(file, "ecx", context.__ss.__ecx);
  293. FIRCLSFileWriteHashEntryUint64(file, "edx", context.__ss.__edx);
  294. FIRCLSFileWriteHashEntryUint64(file, "edi", context.__ss.__edi);
  295. FIRCLSFileWriteHashEntryUint64(file, "esi", context.__ss.__esi);
  296. FIRCLSFileWriteHashEntryUint64(file, "ebp", context.__ss.__ebp);
  297. FIRCLSFileWriteHashEntryUint64(file, "esp", context.__ss.__esp);
  298. FIRCLSFileWriteHashEntryUint64(file, "ss", context.__ss.__ss);
  299. FIRCLSFileWriteHashEntryUint64(file, "eflags", context.__ss.__eflags);
  300. FIRCLSFileWriteHashEntryUint64(file, "eip", context.__ss.__eip);
  301. FIRCLSFileWriteHashEntryUint64(file, "cs", context.__ss.__cs);
  302. FIRCLSFileWriteHashEntryUint64(file, "ds", context.__ss.__ds);
  303. FIRCLSFileWriteHashEntryUint64(file, "es", context.__ss.__es);
  304. FIRCLSFileWriteHashEntryUint64(file, "fs", context.__ss.__fs);
  305. FIRCLSFileWriteHashEntryUint64(file, "gs", context.__ss.__gs);
  306. // how do we get the cr2 register?
  307. #elif CLS_CPU_X86_64
  308. FIRCLSFileWriteHashEntryUint64(file, "rax", context.__ss.__rax);
  309. FIRCLSFileWriteHashEntryUint64(file, "rbx", context.__ss.__rbx);
  310. FIRCLSFileWriteHashEntryUint64(file, "rcx", context.__ss.__rcx);
  311. FIRCLSFileWriteHashEntryUint64(file, "rdx", context.__ss.__rdx);
  312. FIRCLSFileWriteHashEntryUint64(file, "rdi", context.__ss.__rdi);
  313. FIRCLSFileWriteHashEntryUint64(file, "rsi", context.__ss.__rsi);
  314. FIRCLSFileWriteHashEntryUint64(file, "rbp", context.__ss.__rbp);
  315. FIRCLSFileWriteHashEntryUint64(file, "rsp", context.__ss.__rsp);
  316. FIRCLSFileWriteHashEntryUint64(file, "r8", context.__ss.__r8);
  317. FIRCLSFileWriteHashEntryUint64(file, "r9", context.__ss.__r9);
  318. FIRCLSFileWriteHashEntryUint64(file, "r10", context.__ss.__r10);
  319. FIRCLSFileWriteHashEntryUint64(file, "r11", context.__ss.__r11);
  320. FIRCLSFileWriteHashEntryUint64(file, "r12", context.__ss.__r12);
  321. FIRCLSFileWriteHashEntryUint64(file, "r13", context.__ss.__r13);
  322. FIRCLSFileWriteHashEntryUint64(file, "r14", context.__ss.__r14);
  323. FIRCLSFileWriteHashEntryUint64(file, "r15", context.__ss.__r15);
  324. FIRCLSFileWriteHashEntryUint64(file, "rip", context.__ss.__rip);
  325. FIRCLSFileWriteHashEntryUint64(file, "rflags", context.__ss.__rflags);
  326. FIRCLSFileWriteHashEntryUint64(file, "cs", context.__ss.__cs);
  327. FIRCLSFileWriteHashEntryUint64(file, "fs", context.__ss.__fs);
  328. FIRCLSFileWriteHashEntryUint64(file, "gs", context.__ss.__gs);
  329. #endif
  330. return true;
  331. }
  332. static bool FIRCLSProcessRecordThread(FIRCLSProcess *process, thread_t thread, FIRCLSFile *file) {
  333. FIRCLSUnwindContext unwindContext;
  334. FIRCLSThreadContext context;
  335. if (!FIRCLSProcessGetThreadState(process, thread, &context)) {
  336. FIRCLSSDKLogError("Unable to get thread state\n");
  337. return false;
  338. }
  339. if (!FIRCLSUnwindInit(&unwindContext, context)) {
  340. FIRCLSSDKLog("Unable to init unwind context\n");
  341. return false;
  342. }
  343. FIRCLSFileWriteHashStart(file);
  344. // registers
  345. FIRCLSFileWriteHashKey(file, "registers");
  346. FIRCLSFileWriteHashStart(file);
  347. FIRCLSProcessRecordThreadRegisters(context, file);
  348. FIRCLSFileWriteHashEnd(file);
  349. // stacktrace
  350. FIRCLSFileWriteHashKey(file, "stacktrace");
  351. // stacktrace is an array of integers
  352. FIRCLSFileWriteArrayStart(file);
  353. uint32_t repeatedPCCount = 0;
  354. uint64_t repeatedPC = 0;
  355. const FIRCLSInternalLogLevel level = _firclsContext.writable->internalLogging.logLevel;
  356. while (FIRCLSUnwindNextFrame(&unwindContext)) {
  357. const uintptr_t pc = FIRCLSUnwindGetPC(&unwindContext);
  358. const uint32_t frameCount = FIRCLSUnwindGetFrameRepeatCount(&unwindContext);
  359. if (repeatedPC == pc && repeatedPC != 0) {
  360. // actively counting a recursion
  361. repeatedPCCount = frameCount;
  362. continue;
  363. }
  364. if (frameCount >= FIRCLSUnwindInfiniteRecursionCountThreshold && repeatedPC == 0) {
  365. repeatedPC = pc;
  366. FIRCLSSDKLogWarn("Possible infinite recursion - suppressing logging\n");
  367. _firclsContext.writable->internalLogging.logLevel = FIRCLSInternalLogLevelWarn;
  368. continue;
  369. }
  370. if (repeatedPC != 0) {
  371. // at this point, we've recorded a repeated PC, but it is now no longer
  372. // repeating, so we can restore the logging
  373. _firclsContext.writable->internalLogging.logLevel = level;
  374. }
  375. FIRCLSFileWriteArrayEntryUint64(file, pc);
  376. }
  377. FIRCLSFileWriteArrayEnd(file);
  378. // crashed?
  379. if (FIRCLSProcessIsCrashedThread(process, thread)) {
  380. FIRCLSFileWriteHashEntryBoolean(file, "crashed", true);
  381. }
  382. if (repeatedPC != 0) {
  383. FIRCLSFileWriteHashEntryUint64(file, "repeated_pc", repeatedPC);
  384. FIRCLSFileWriteHashEntryUint64(file, "repeat_count", repeatedPCCount);
  385. }
  386. // Just for extra safety, restore the logging level again. The logic
  387. // above is fairly tricky, this is cheap, and no logging is a real pain.
  388. _firclsContext.writable->internalLogging.logLevel = level;
  389. // end thread info
  390. FIRCLSFileWriteHashEnd(file);
  391. return true;
  392. }
  393. bool FIRCLSProcessRecordAllThreads(FIRCLSProcess *process, FIRCLSFile *file) {
  394. uint32_t threadCount;
  395. uint32_t i;
  396. threadCount = FIRCLSProcessGetThreadCount(process);
  397. FIRCLSFileWriteSectionStart(file, "threads");
  398. FIRCLSFileWriteArrayStart(file);
  399. for (i = 0; i < threadCount; ++i) {
  400. thread_t thread;
  401. thread = FIRCLSProcessGetThread(process, i);
  402. FIRCLSSDKLogInfo("recording thread %d data\n", i);
  403. if (!FIRCLSProcessRecordThread(process, thread, file)) {
  404. FIRCLSSDKLogError("Failed to record thread state. Closing threads JSON to prevent malformed crash report.\n");
  405. FIRCLSFileWriteArrayEnd(file);
  406. FIRCLSFileWriteSectionEnd(file);
  407. return false;
  408. }
  409. }
  410. FIRCLSFileWriteArrayEnd(file);
  411. FIRCLSFileWriteSectionEnd(file);
  412. FIRCLSSDKLogInfo("Completed recording all thread data\n");
  413. return true;
  414. }
  415. void FIRCLSProcessRecordThreadNames(FIRCLSProcess *process, FIRCLSFile *file) {
  416. uint32_t threadCount;
  417. uint32_t i;
  418. FIRCLSFileWriteSectionStart(file, "thread_names");
  419. FIRCLSFileWriteArrayStart(file);
  420. threadCount = FIRCLSProcessGetThreadCount(process);
  421. for (i = 0; i < threadCount; ++i) {
  422. thread_t thread;
  423. char name[THREAD_NAME_BUFFER_SIZE];
  424. thread = FIRCLSProcessGetThread(process, i);
  425. name[0] = 0; // null-terminate, just in case nothing is written
  426. FIRCLSProcessGetThreadName(process, thread, name, THREAD_NAME_BUFFER_SIZE);
  427. FIRCLSFileWriteArrayEntryString(file, name);
  428. }
  429. FIRCLSFileWriteArrayEnd(file);
  430. FIRCLSFileWriteSectionEnd(file);
  431. }
  432. void FIRCLSProcessRecordDispatchQueueNames(FIRCLSProcess *process, FIRCLSFile *file) {
  433. uint32_t threadCount;
  434. uint32_t i;
  435. FIRCLSFileWriteSectionStart(file, "dispatch_queue_names");
  436. FIRCLSFileWriteArrayStart(file);
  437. threadCount = FIRCLSProcessGetThreadCount(process);
  438. for (i = 0; i < threadCount; ++i) {
  439. thread_t thread;
  440. const char *name;
  441. thread = FIRCLSProcessGetThread(process, i);
  442. name = FIRCLSProcessGetThreadDispatchQueueName(process, thread);
  443. // Apple Report Converter will fail to parse this when "name" is null,
  444. // so we will use an empty string instead.
  445. if (name == NULL) {
  446. name = "";
  447. }
  448. FIRCLSFileWriteArrayEntryString(file, name);
  449. }
  450. FIRCLSFileWriteArrayEnd(file);
  451. FIRCLSFileWriteSectionEnd(file);
  452. }
  453. #pragma mark - Othe Process Info
  454. bool FIRCLSProcessGetMemoryUsage(uint64_t *active,
  455. uint64_t *inactive,
  456. uint64_t *wired,
  457. uint64_t *freeMem) {
  458. mach_port_t hostPort;
  459. mach_msg_type_number_t hostSize;
  460. vm_size_t pageSize;
  461. vm_statistics_data_t vmStat;
  462. hostPort = mach_host_self();
  463. hostSize = sizeof(vm_statistics_data_t) / sizeof(integer_t);
  464. pageSize = _firclsContext.readonly->host.pageSize;
  465. if (host_statistics(hostPort, HOST_VM_INFO, (host_info_t)&vmStat, &hostSize) != KERN_SUCCESS) {
  466. FIRCLSSDKLog("Failed to get vm statistics\n");
  467. return false;
  468. }
  469. if (!(active && inactive && wired && freeMem)) {
  470. FIRCLSSDKLog("Invalid pointers\n");
  471. return false;
  472. }
  473. // compute the sizes in bytes and return the values
  474. *active = vmStat.active_count * pageSize;
  475. *inactive = vmStat.inactive_count * pageSize;
  476. *wired = vmStat.wire_count * pageSize;
  477. *freeMem = vmStat.free_count * pageSize;
  478. return true;
  479. }
  480. bool FIRCLSProcessGetInfo(FIRCLSProcess *process,
  481. uint64_t *virtualSize,
  482. uint64_t *residentSize,
  483. time_value_t *userTime,
  484. time_value_t *systemTime) {
  485. struct task_basic_info_64 taskInfo;
  486. mach_msg_type_number_t count;
  487. count = TASK_BASIC_INFO_64_COUNT;
  488. if (task_info(process->task, TASK_BASIC_INFO_64, (task_info_t)&taskInfo, &count) !=
  489. KERN_SUCCESS) {
  490. FIRCLSSDKLog("Failed to get task info\n");
  491. return false;
  492. }
  493. if (!(virtualSize && residentSize && userTime && systemTime)) {
  494. FIRCLSSDKLog("Invalid pointers\n");
  495. return false;
  496. }
  497. *virtualSize = taskInfo.virtual_size;
  498. *residentSize = taskInfo.resident_size;
  499. *userTime = taskInfo.user_time;
  500. *systemTime = taskInfo.system_time;
  501. return true;
  502. }
  503. void FIRCLSProcessRecordStats(FIRCLSProcess *process, FIRCLSFile *file) {
  504. uint64_t active;
  505. uint64_t inactive;
  506. uint64_t virtualSize;
  507. uint64_t residentSize;
  508. uint64_t wired;
  509. uint64_t freeMem;
  510. time_value_t userTime;
  511. time_value_t systemTime;
  512. if (!FIRCLSProcessGetMemoryUsage(&active, &inactive, &wired, &freeMem)) {
  513. FIRCLSSDKLog("Unable to get process memory usage\n");
  514. return;
  515. }
  516. if (!FIRCLSProcessGetInfo(process, &virtualSize, &residentSize, &userTime, &systemTime)) {
  517. FIRCLSSDKLog("Unable to get process stats\n");
  518. return;
  519. }
  520. FIRCLSFileWriteSectionStart(file, "process_stats");
  521. FIRCLSFileWriteHashStart(file);
  522. FIRCLSFileWriteHashEntryUint64(file, "active", active);
  523. FIRCLSFileWriteHashEntryUint64(file, "inactive", inactive);
  524. FIRCLSFileWriteHashEntryUint64(file, "wired", wired);
  525. FIRCLSFileWriteHashEntryUint64(file, "freeMem", freeMem); // Intentionally left in, for now. Arg.
  526. FIRCLSFileWriteHashEntryUint64(file, "free_mem", freeMem);
  527. FIRCLSFileWriteHashEntryUint64(file, "virtual", virtualSize);
  528. FIRCLSFileWriteHashEntryUint64(file, "resident", active);
  529. FIRCLSFileWriteHashEntryUint64(file, "user_time",
  530. (userTime.seconds * 1000 * 1000) + userTime.microseconds);
  531. FIRCLSFileWriteHashEntryUint64(file, "sys_time",
  532. (systemTime.seconds * 1000 * 1000) + systemTime.microseconds);
  533. FIRCLSFileWriteHashEnd(file);
  534. FIRCLSFileWriteSectionEnd(file);
  535. }
  536. #pragma mark - Runtime Info
  537. #define OBJC_MSG_SEND_START ((vm_address_t)objc_msgSend)
  538. #define OBJC_MSG_SEND_SUPER_START ((vm_address_t)objc_msgSendSuper)
  539. #define OBJC_MSG_SEND_END (OBJC_MSG_SEND_START + 66)
  540. #define OBJC_MSG_SEND_SUPER_END (OBJC_MSG_SEND_SUPER_START + 66)
  541. #if !CLS_CPU_ARM64
  542. #define OBJC_MSG_SEND_STRET_START ((vm_address_t)objc_msgSend_stret)
  543. #define OBJC_MSG_SEND_SUPER_STRET_START ((vm_address_t)objc_msgSendSuper_stret)
  544. #define OBJC_MSG_SEND_STRET_END (OBJC_MSG_SEND_STRET_START + 66)
  545. #define OBJC_MSG_SEND_SUPER_STRET_END (OBJC_MSG_SEND_SUPER_STRET_START + 66)
  546. #endif
  547. #if CLS_CPU_X86
  548. #define OBJC_MSG_SEND_FPRET_START ((vm_address_t)objc_msgSend_fpret)
  549. #define OBJC_MSG_SEND_FPRET_END (OBJC_MSG_SEND_FPRET_START + 66)
  550. #endif
  551. static const char *FIRCLSProcessGetObjCSelectorName(FIRCLSThreadContext registers) {
  552. void *selectorAddress;
  553. void *selRegister;
  554. #if !CLS_CPU_ARM64
  555. void *stretSelRegister;
  556. #endif
  557. vm_address_t pc;
  558. // First, did we crash in objc_msgSend? The two ways I can think
  559. // of doing this are to use dladdr, and then comparing the strings to
  560. // objc_msg*, or looking up the symbols, and guessing if we are "close enough".
  561. selectorAddress = NULL;
  562. #if CLS_CPU_ARM
  563. pc = registers.__ss.__pc;
  564. selRegister = (void *)registers.__ss.__r[1];
  565. stretSelRegister = (void *)registers.__ss.__r[2];
  566. #elif CLS_CPU_ARM64
  567. pc = FIRCLSThreadContextGetPC(&registers);
  568. selRegister = (void *)registers.__ss.__x[1];
  569. #elif CLS_CPU_I386
  570. pc = registers.__ss.__eip;
  571. selRegister = (void *)registers.__ss.__ecx;
  572. stretSelRegister = (void *)registers.__ss.__ecx;
  573. #elif CLS_CPU_X86_64
  574. pc = registers.__ss.__rip;
  575. selRegister = (void *)registers.__ss.__rsi;
  576. stretSelRegister = (void *)registers.__ss.__rdx;
  577. #endif
  578. if ((pc >= OBJC_MSG_SEND_START) && (pc <= OBJC_MSG_SEND_END)) {
  579. selectorAddress = selRegister;
  580. }
  581. #if !CLS_CPU_ARM64
  582. if ((pc >= OBJC_MSG_SEND_SUPER_START) && (pc <= OBJC_MSG_SEND_SUPER_END)) {
  583. selectorAddress = selRegister;
  584. }
  585. if ((pc >= OBJC_MSG_SEND_STRET_START) && (pc <= OBJC_MSG_SEND_STRET_END)) {
  586. selectorAddress = stretSelRegister;
  587. }
  588. if ((pc >= OBJC_MSG_SEND_SUPER_STRET_START) && (pc <= OBJC_MSG_SEND_SUPER_STRET_END)) {
  589. selectorAddress = stretSelRegister;
  590. }
  591. #if CLS_CPU_X86
  592. if ((pc >= OBJC_MSG_SEND_FPRET_START) && (pc <= OBJC_MSG_SEND_FPRET_END)) {
  593. selectorAddress = selRegister;
  594. }
  595. #endif
  596. #endif
  597. if (!selectorAddress) {
  598. return "";
  599. }
  600. if (!FIRCLSReadString((vm_address_t)selectorAddress, (char **)&selectorAddress, 128)) {
  601. FIRCLSSDKLog("Unable to read the selector string\n");
  602. return "";
  603. }
  604. return selectorAddress;
  605. }
  606. #define CRASH_ALIGN __attribute__((aligned(8)))
  607. typedef struct {
  608. unsigned version CRASH_ALIGN;
  609. const char *message CRASH_ALIGN;
  610. const char *signature CRASH_ALIGN;
  611. const char *backtrace CRASH_ALIGN;
  612. const char *message2 CRASH_ALIGN;
  613. void *reserved CRASH_ALIGN;
  614. void *reserved2 CRASH_ALIGN;
  615. } crash_info_t;
  616. static void FIRCLSProcessRecordCrashInfo(FIRCLSFile *file) {
  617. // TODO: this should be abstracted into binary images, if possible
  618. FIRCLSBinaryImageRuntimeNode *nodes = _firclsContext.writable->binaryImage.nodes;
  619. if (!nodes) {
  620. FIRCLSSDKLogError("The node structure is NULL\n");
  621. return;
  622. }
  623. for (uint32_t i = 0; i < CLS_BINARY_IMAGE_RUNTIME_NODE_COUNT; ++i) {
  624. FIRCLSBinaryImageRuntimeNode *node = &nodes[i];
  625. if (!node->crashInfo) {
  626. continue;
  627. }
  628. crash_info_t info;
  629. if (!FIRCLSReadMemory((vm_address_t)node->crashInfo, &info, sizeof(crash_info_t))) {
  630. continue;
  631. }
  632. FIRCLSSDKLogDebug("Found crash info with version %d\n", info.version);
  633. // Currently support versions 0 through 5.
  634. // 4 was in use for a long time, but it appears that with iOS 9 / swift 2.0, the verison has
  635. // been bumped.
  636. if (info.version > 5) {
  637. continue;
  638. }
  639. if (!info.message) {
  640. continue;
  641. }
  642. #if CLS_BINARY_IMAGE_RUNTIME_NODE_RECORD_NAME
  643. FIRCLSSDKLogInfo("Found crash info for %s\n", node->name);
  644. #endif
  645. FIRCLSSDKLogDebug("attempting to read crash info string\n");
  646. char *string = NULL;
  647. if (!FIRCLSReadString((vm_address_t)info.message, &string, 256)) {
  648. FIRCLSSDKLogError("Failed to copy crash info string\n");
  649. continue;
  650. }
  651. // The crash_info_t's message may contain the device's UDID, in this case,
  652. // make sure that we do our best to redact that information before writing the
  653. // rest of the message to disk. This also has the effect of not uploading that
  654. // information in the subsequent crash report.
  655. FIRCLSRedactUUID(string);
  656. FIRCLSFileWriteArrayEntryHexEncodedString(file, string);
  657. }
  658. }
  659. void FIRCLSProcessRecordRuntimeInfo(FIRCLSProcess *process, FIRCLSFile *file) {
  660. FIRCLSThreadContext mcontext;
  661. if (!FIRCLSProcessGetThreadState(process, process->crashedThread, &mcontext)) {
  662. FIRCLSSDKLogError("unable to get crashed thread state");
  663. }
  664. FIRCLSFileWriteSectionStart(file, "runtime");
  665. FIRCLSFileWriteHashStart(file);
  666. FIRCLSFileWriteHashEntryString(file, "objc_selector", FIRCLSProcessGetObjCSelectorName(mcontext));
  667. FIRCLSFileWriteHashKey(file, "crash_info_entries");
  668. FIRCLSFileWriteArrayStart(file);
  669. FIRCLSProcessRecordCrashInfo(file);
  670. FIRCLSFileWriteArrayEnd(file);
  671. FIRCLSFileWriteHashEnd(file);
  672. FIRCLSFileWriteSectionEnd(file);
  673. }