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/Shared/FIRCLSMachO/FIRCLSMachO.h"
16
 
17
#include <Foundation/Foundation.h>
18
 
19
#include <mach-o/dyld.h>
20
#include <mach-o/fat.h>
21
#include <mach-o/getsect.h>
22
#include <mach-o/ldsyms.h>
23
 
24
#include <sys/mman.h>
25
#include <sys/stat.h>
26
 
27
#include <dlfcn.h>
28
#include <fcntl.h>
29
 
30
#include <stdio.h>
31
 
32
#include <unistd.h>
33
 
34
// This is defined in newer versions of iOS/macOS in usr/include/mach/machine.h
35
#define CLS_CPU_SUBTYPE_ARM64E ((cpu_subtype_t)2)
36
 
37
static void FIRCLSMachOHeaderValues(FIRCLSMachOSliceRef slice,
38
                                    const struct load_command** cmds,
39
                                    uint32_t* cmdCount);
40
static bool FIRCLSMachOSliceIsValid(FIRCLSMachOSliceRef slice);
41
 
42
bool FIRCLSMachOFileInitWithPath(FIRCLSMachOFileRef file, const char* path) {
43
  struct stat statBuffer;
44
 
45
  if (!file || !path) {
46
    return false;
47
  }
48
 
49
  file->fd = 0;
50
  file->mappedFile = NULL;
51
  file->mappedSize = 0;
52
 
53
  file->fd = open(path, O_RDONLY);
54
  if (file->fd < 0) {
55
    // unable to open mach-o file
56
    return false;
57
  }
58
 
59
  if (fstat(file->fd, &statBuffer) == -1) {
60
    close(file->fd);
61
    return false;
62
  }
63
 
64
  // We need some minimum size for this to even be a possible mach-o file.  I believe
65
  // its probably quite a bit bigger than this, but this at least covers something.
66
  // We also need it to be a regular file.
67
  file->mappedSize = (size_t)statBuffer.st_size;
68
  if (statBuffer.st_size < 16 || !(statBuffer.st_mode & S_IFREG)) {
69
    close(file->fd);
70
    return false;
71
  }
72
 
73
  // Map the file to memory. MAP_SHARED can potentially reduce the amount of actual private
74
  // memory needed to do this mapping. Also, be sure to check for the correct failure result.
75
  file->mappedFile = mmap(0, file->mappedSize, PROT_READ, MAP_FILE | MAP_SHARED, file->fd, 0);
76
  if (!file->mappedFile || (file->mappedFile == MAP_FAILED)) {
77
    close(file->fd);
78
    return false;
79
  }
80
 
81
  return true;
82
}
83
 
84
bool FIRCLSMachOFileInitWithCurrent(FIRCLSMachOFileRef file) {
85
  struct FIRCLSMachOSlice slice = FIRCLSMachOSliceGetCurrent();
86
 
87
  const char* imagePath = FIRCLSMachOSliceGetExecutablePath(&slice);
88
 
89
  return FIRCLSMachOFileInitWithPath(file, imagePath);
90
}
91
 
92
void FIRCLSMachOFileDestroy(FIRCLSMachOFileRef file) {
93
  if (!file) {
94
    return;
95
  }
96
 
97
  if (file->mappedFile && file->mappedSize > 0) {
98
    munmap(file->mappedFile, file->mappedSize);
99
  }
100
 
101
  close(file->fd);
102
}
103
 
104
void FIRCLSMachOFileEnumerateSlices(FIRCLSMachOFileRef file, FIRCLSMachOSliceIterator block) {
105
  FIRCLSMachOEnumerateSlicesAtAddress(file->mappedFile, block);
106
}
107
 
108
void FIRCLSMachOEnumerateSlicesAtAddress(void* executableData, FIRCLSMachOSliceIterator block) {
109
  // check the magic value, to determine if we have a fat header or not
110
  uint32_t magicValue;
111
  uint32_t archCount;
112
  const struct fat_arch* fatArch;
113
  struct FIRCLSMachOSlice slice;
114
 
115
  memset(&slice, 0, sizeof(struct FIRCLSMachOSlice));
116
 
117
  magicValue = ((struct fat_header*)executableData)->magic;
118
  if ((magicValue != FAT_MAGIC) && (magicValue != FAT_CIGAM)) {
119
    slice.startAddress = executableData;
120
 
121
    // use this to fill in the values
122
    FIRCLSMachOHeaderValues(&slice, NULL, NULL);
123
 
124
    block(&slice);
125
 
126
    return;
127
  }
128
 
129
  archCount = OSSwapBigToHostInt32(((struct fat_header*)executableData)->nfat_arch);
130
  fatArch = executableData + sizeof(struct fat_header);
131
 
132
  for (uint32_t i = 0; i < archCount; ++i) {
133
    slice.cputype = OSSwapBigToHostInt32(fatArch->cputype);
134
    slice.cpusubtype = OSSwapBigToHostInt32(fatArch->cpusubtype);
135
    slice.startAddress = executableData + OSSwapBigToHostInt32(fatArch->offset);
136
 
137
    block(&slice);
138
 
139
    // advance to the next fat_arch structure
140
    fatArch = (struct fat_arch*)((uintptr_t)fatArch + sizeof(struct fat_arch));
141
  }
142
}
143
 
144
struct FIRCLSMachOSlice FIRCLSMachOFileSliceWithArchitectureName(FIRCLSMachOFileRef file,
145
                                                                 const char* name) {
146
  __block struct FIRCLSMachOSlice value;
147
 
148
  memset(&value, 0, sizeof(struct FIRCLSMachOSlice));
149
 
150
  FIRCLSMachOFileEnumerateSlices(file, ^(FIRCLSMachOSliceRef slice) {
151
    if (strcmp(FIRCLSMachOSliceGetArchitectureName(slice), name) == 0) {
152
      value = *slice;
153
    }
154
  });
155
 
156
  return value;
157
}
158
 
159
static void FIRCLSMachOHeaderValues(FIRCLSMachOSliceRef slice,
160
                                    const struct load_command** cmds,
161
                                    uint32_t* cmdCount) {
162
  const struct mach_header* header32 = (const struct mach_header*)slice->startAddress;
163
  const struct mach_header_64* header64 = (const struct mach_header_64*)slice->startAddress;
164
  uint32_t commandCount;
165
  const void* commandsAddress;
166
 
167
  if (cmds) {
168
    *cmds = NULL;
169
  }
170
 
171
  if (cmdCount) {
172
    *cmdCount = 0;
173
  }
174
 
175
  if (!slice->startAddress) {
176
    return;
177
  }
178
 
179
  // the 32 and 64 bit versions have an identical structures, so this will work
180
  switch (header32->magic) {
181
    case MH_MAGIC:  // 32-bit
182
    case MH_CIGAM:
183
      slice->cputype = header32->cputype;
184
      slice->cpusubtype = header32->cpusubtype;
185
      commandCount = header32->ncmds;
186
      commandsAddress = slice->startAddress + sizeof(struct mach_header);
187
      break;
188
    case MH_MAGIC_64:  // 64-bit
189
    case MH_CIGAM_64:
190
      slice->cputype = header64->cputype;
191
      slice->cpusubtype = header64->cpusubtype;
192
      commandCount = header64->ncmds;
193
      commandsAddress = slice->startAddress + sizeof(struct mach_header_64);
194
      break;
195
    default:
196
      // not a valid header
197
      return;
198
  }
199
 
200
  // assign everything back by reference
201
  if (cmds) {
202
    *cmds = commandsAddress;
203
  }
204
 
205
  if (cmdCount) {
206
    *cmdCount = commandCount;
207
  }
208
}
209
 
210
static bool FIRCLSMachOSliceIsValid(FIRCLSMachOSliceRef slice) {
211
  if (!slice) {
212
    return false;
213
  }
214
 
215
  if (!slice->startAddress) {
216
    return false;
217
  }
218
 
219
  return true;
220
}
221
 
222
void FIRCLSMachOSliceEnumerateLoadCommands(FIRCLSMachOSliceRef slice,
223
                                           FIRCLSMachOLoadCommandIterator block) {
224
  const struct load_command* cmd;
225
  uint32_t cmdCount;
226
 
227
  if (!block) {
228
    return;
229
  }
230
 
231
  if (!FIRCLSMachOSliceIsValid(slice)) {
232
    return;
233
  }
234
 
235
  FIRCLSMachOHeaderValues(slice, &cmd, &cmdCount);
236
 
237
  for (uint32_t i = 0; cmd != NULL && i < cmdCount; ++i) {
238
    block(cmd->cmd, cmd->cmdsize, cmd);
239
 
240
    cmd = (struct load_command*)((uintptr_t)cmd + cmd->cmdsize);
241
  }
242
}
243
 
244
struct FIRCLSMachOSlice FIRCLSMachOSliceGetCurrent(void) {
245
  const NXArchInfo* archInfo;
246
  struct FIRCLSMachOSlice slice;
247
  void* executableSymbol;
248
  Dl_info dlinfo;
249
 
250
  archInfo = NXGetLocalArchInfo();
251
  if (archInfo) {
252
    slice.cputype = archInfo->cputype;
253
    slice.cpusubtype = archInfo->cpusubtype;
254
  }
255
 
256
  slice.startAddress = NULL;
257
 
258
  // This call can fail when Exported Symbols File in Build Settings is missing the symbol value
259
  // defined as _MH_EXECUTE_SYM (if you look in the header the underscored MH_EXECUTE_SYM define is
260
  // there)
261
  executableSymbol = dlsym(RTLD_MAIN_ONLY, MH_EXECUTE_SYM);
262
 
263
  // get the address of the main function
264
  if (dladdr(executableSymbol, &dlinfo) != 0) {
265
    slice.startAddress = dlinfo.dli_fbase;
266
  }
267
 
268
  return slice;
269
}
270
 
271
struct FIRCLSMachOSlice FIRCLSMachOSliceWithHeader(void* machHeader) {
272
  struct FIRCLSMachOSlice slice;
273
 
274
  slice.startAddress = machHeader;
275
 
276
  return slice;
277
}
278
 
279
const char* FIRCLSMachOSliceGetExecutablePath(FIRCLSMachOSliceRef slice) {
280
  Dl_info info;
281
 
282
  if (!FIRCLSMachOSliceIsValid(slice)) {
283
    return NULL;
284
  }
285
 
286
  // use dladdr here to look up the information we need for a binary image
287
  if (dladdr(slice->startAddress, &info) == 0) {
288
    return NULL;
289
  }
290
 
291
  return info.dli_fname;
292
}
293
 
294
const char* FIRCLSMachOSliceGetArchitectureName(FIRCLSMachOSliceRef slice) {
295
  const NXArchInfo* archInfo;
296
 
297
  // there are some special cases here for types not handled by earlier OSes
298
  if (slice->cputype == CPU_TYPE_ARM && slice->cpusubtype == CPU_SUBTYPE_ARM_V7S) {
299
    return "armv7s";
300
  }
301
 
302
  if (slice->cputype == (CPU_TYPE_ARM | CPU_ARCH_ABI64)) {
303
    if (slice->cpusubtype == CLS_CPU_SUBTYPE_ARM64E) {
304
      return "arm64e";
305
    } else if (slice->cpusubtype == CPU_SUBTYPE_ARM64_ALL) {
306
      return "arm64";
307
    }
308
  }
309
 
310
  if (slice->cputype == (CPU_TYPE_ARM) && slice->cpusubtype == CPU_SUBTYPE_ARM_V7K) {
311
    return "armv7k";
312
  }
313
 
314
  archInfo = NXGetArchInfoFromCpuType(slice->cputype, slice->cpusubtype);
315
  if (!archInfo) {
316
    return "unknown";
317
  }
318
 
319
  return archInfo->name;
320
}
321
 
322
bool FIRCLSMachOSliceIs64Bit(FIRCLSMachOSliceRef slice) {
323
  // I'm pretty sure this is sufficient...
324
  return (slice->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64;
325
}
326
 
327
bool FIRCLSMachOSliceGetSectionByName(FIRCLSMachOSliceRef slice,
328
                                      const char* segName,
329
                                      const char* sectionName,
330
                                      const void** ptr) {
331
  if (!ptr) {
332
    return false;
333
  }
334
 
335
  *ptr = NULL;  // make sure this is set before returning
336
 
337
  FIRCLSMachOSection section;
338
 
339
  if (!FIRCLSMachOSliceInitSectionByName(slice, segName, sectionName, &section)) {
340
    return false;
341
  }
342
 
343
  // WARNING: this calculation isn't correct, but is here to maintain backwards
344
  // compatibility for now with callers of FIRCLSMachOSliceGetSectionByName. All new
345
  // users should be calling FIRCLSMachOSliceInitSectionByName
346
  *ptr = (const void*)((uintptr_t)slice->startAddress + section.offset);
347
 
348
  return true;
349
}
350
 
351
bool FIRCLSMachOSliceInitSectionByName(FIRCLSMachOSliceRef slice,
352
                                       const char* segName,
353
                                       const char* sectionName,
354
                                       FIRCLSMachOSection* section) {
355
  if (!FIRCLSMachOSliceIsValid(slice)) {
356
    return false;
357
  }
358
 
359
  if (!section) {
360
    return false;
361
  }
362
 
363
  memset(section, 0, sizeof(FIRCLSMachOSection));
364
 
365
  if (FIRCLSMachOSliceIs64Bit(slice)) {
366
    const struct section_64* sect =
367
        getsectbynamefromheader_64(slice->startAddress, segName, sectionName);
368
    if (!sect) {
369
      return false;
370
    }
371
 
372
    section->addr = sect->addr;
373
    section->size = sect->size;
374
    section->offset = sect->offset;
375
  } else {
376
    const struct section* sect = getsectbynamefromheader(slice->startAddress, segName, sectionName);
377
    if (!sect) {
378
      return false;
379
    }
380
 
381
    section->addr = sect->addr;
382
    section->size = sect->size;
383
    section->offset = sect->offset;
384
  }
385
 
386
  return true;
387
}
388
 
389
// TODO: this is left in-place just to ensure that old crashltyics + new fabric are still compatible
390
// with each other. As a happy bonus, if that situation does come up, this will also fix the bug
391
// that was preventing compact unwind on arm64 + iOS 9 from working correctly.
392
void FIRCLSMachOSliceGetUnwindInformation(FIRCLSMachOSliceRef slice,
393
                                          const void** ehFrame,
394
                                          const void** unwindInfo) {
395
  if (!unwindInfo && !ehFrame) {
396
    return;
397
  }
398
 
399
  bool found = false;
400
  intptr_t slide = 0;
401
 
402
  // This is inefficient, but we have no other safe way to do this correctly. Modifying the
403
  // FIRCLSMachOSlice structure is tempting, but could introduce weird binary-compatibility issues
404
  // with version mis-matches.
405
  for (uint32_t i = 0; i < _dyld_image_count(); ++i) {
406
    const struct mach_header* header = _dyld_get_image_header(i);
407
 
408
    if (header == slice->startAddress) {
409
      found = true;
410
      slide = _dyld_get_image_vmaddr_slide(i);
411
      break;
412
    }
413
  }
414
 
415
  // make sure we were able to find a matching value
416
  if (!found) {
417
    return;
418
  }
419
 
420
  FIRCLSMachOSection section;
421
 
422
  if (unwindInfo) {
423
    if (FIRCLSMachOSliceInitSectionByName(slice, SEG_TEXT, "__unwind_info", &section)) {
424
      *unwindInfo = (void*)(section.addr + slide);
425
    }
426
  }
427
 
428
  if (ehFrame) {
429
    if (FIRCLSMachOSliceInitSectionByName(slice, SEG_TEXT, "__eh_frame", &section)) {
430
      *ehFrame = (void*)(section.addr + slide);
431
    }
432
  }
433
}
434
 
435
uint8_t const* FIRCLSMachOGetUUID(const struct load_command* cmd) {
436
  return ((const struct uuid_command*)cmd)->uuid;
437
}
438
 
439
const char* FIRCLSMachOGetDylibPath(const struct load_command* cmd) {
440
  const struct dylib_command* dylibcmd = (const struct dylib_command*)cmd;
441
 
442
  return (const char*)((uintptr_t)cmd + dylibcmd->dylib.name.offset);
443
}
444
 
445
bool FIRCLSMachOGetEncrypted(const struct load_command* cmd) {
446
  return ((struct encryption_info_command*)cmd)->cryptid > 0;
447
}
448
 
449
static FIRCLSMachOVersion FIRCLSMachOVersionFromEncoded(uint32_t encoded) {
450
  FIRCLSMachOVersion version;
451
 
452
  version.major = (encoded & 0xffff0000) >> 16;
453
  version.minor = (encoded & 0x0000ff00) >> 8;
454
  version.bugfix = encoded & 0x000000ff;
455
 
456
  return version;
457
}
458
 
459
FIRCLSMachOVersion FIRCLSMachOGetMinimumOSVersion(const struct load_command* cmd) {
460
  return FIRCLSMachOVersionFromEncoded(((const struct version_min_command*)cmd)->version);
461
}
462
 
463
FIRCLSMachOVersion FIRCLSMachOGetLinkedSDKVersion(const struct load_command* cmd) {
464
  return FIRCLSMachOVersionFromEncoded(((const struct version_min_command*)cmd)->sdk);
465
}
466
 
467
FIRCLSMachOSegmentCommand FIRCLSMachOGetSegmentCommand(const struct load_command* cmd) {
468
  FIRCLSMachOSegmentCommand segmentCommand;
469
 
470
  memset(&segmentCommand, 0, sizeof(FIRCLSMachOSegmentCommand));
471
 
472
  if (!cmd) {
473
    return segmentCommand;
474
  }
475
 
476
  if (cmd->cmd == LC_SEGMENT) {
477
    struct segment_command* segCmd = (struct segment_command*)cmd;
478
 
479
    memcpy(segmentCommand.segname, segCmd->segname, 16);
480
    segmentCommand.vmaddr = segCmd->vmaddr;
481
    segmentCommand.vmsize = segCmd->vmsize;
482
  } else if (cmd->cmd == LC_SEGMENT_64) {
483
    struct segment_command_64* segCmd = (struct segment_command_64*)cmd;
484
 
485
    memcpy(segmentCommand.segname, segCmd->segname, 16);
486
    segmentCommand.vmaddr = segCmd->vmaddr;
487
    segmentCommand.vmsize = segCmd->vmsize;
488
  }
489
 
490
  return segmentCommand;
491
}
492
 
493
NSString* FIRCLSMachONormalizeUUID(CFUUIDBytes* uuidBytes) {
494
  CFUUIDRef uuid = CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault, *uuidBytes);
495
 
496
  NSString* string = CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
497
 
498
  CFRelease(uuid);
499
 
500
  return [[string stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString];
501
}
502
 
503
NSString* FIRCLSMachOFormatVersion(FIRCLSMachOVersion* version) {
504
  if (!version) {
505
    return nil;
506
  }
507
 
508
  return [NSString stringWithFormat:@"%d.%d.%d", version->major, version->minor, version->bugfix];
509
}