Proyectos de Subversion Iphone Microlearning

Rev

| Ultima modificación | Ver Log |

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