FIRCLSMachO.m 15 KB

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