FIRCLSMachO.m 16 KB

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