FIRCLSMachO.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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(FIRCLSMachOSliceRef slice,
  174. FIRCLSMachOLoadCommandIterator block) {
  175. const struct load_command* cmd;
  176. uint32_t cmdCount;
  177. if (!block) {
  178. return;
  179. }
  180. if (!FIRCLSMachOSliceIsValid(slice)) {
  181. return;
  182. }
  183. FIRCLSMachOHeaderValues(slice, &cmd, &cmdCount);
  184. for (uint32_t i = 0; cmd != NULL && i < cmdCount; ++i) {
  185. block(cmd->cmd, cmd->cmdsize, cmd);
  186. cmd = (struct load_command*)((uintptr_t)cmd + cmd->cmdsize);
  187. }
  188. }
  189. struct FIRCLSMachOSlice FIRCLSMachOSliceGetCurrent(void) {
  190. const NXArchInfo* archInfo;
  191. struct FIRCLSMachOSlice slice;
  192. void* executableSymbol;
  193. Dl_info dlinfo;
  194. archInfo = NXGetLocalArchInfo();
  195. if (archInfo) {
  196. slice.cputype = archInfo->cputype;
  197. slice.cpusubtype = archInfo->cpusubtype;
  198. }
  199. slice.startAddress = NULL;
  200. // This call can fail when Exported Symbols File in Build Settings is missing the symbol value
  201. // defined as _MH_EXECUTE_SYM (if you look in the header the underscored MH_EXECUTE_SYM define is
  202. // there)
  203. executableSymbol = dlsym(RTLD_MAIN_ONLY, MH_EXECUTE_SYM);
  204. // get the address of the main function
  205. if (dladdr(executableSymbol, &dlinfo) != 0) {
  206. slice.startAddress = dlinfo.dli_fbase;
  207. }
  208. return slice;
  209. }
  210. struct FIRCLSMachOSlice FIRCLSMachOSliceWithHeader(void* machHeader) {
  211. struct FIRCLSMachOSlice slice;
  212. slice.startAddress = machHeader;
  213. return slice;
  214. }
  215. const char* FIRCLSMachOSliceGetExecutablePath(FIRCLSMachOSliceRef slice) {
  216. Dl_info info;
  217. if (!FIRCLSMachOSliceIsValid(slice)) {
  218. return NULL;
  219. }
  220. // use dladdr here to look up the information we need for a binary image
  221. if (dladdr(slice->startAddress, &info) == 0) {
  222. return NULL;
  223. }
  224. return info.dli_fname;
  225. }
  226. const char* FIRCLSMachOSliceGetArchitectureName(FIRCLSMachOSliceRef slice) {
  227. const NXArchInfo* archInfo;
  228. // there are some special cases here for types not handled by earlier OSes
  229. if (slice->cputype == CPU_TYPE_ARM && slice->cpusubtype == CPU_SUBTYPE_ARM_V7S) {
  230. return "armv7s";
  231. }
  232. if (slice->cputype == (CPU_TYPE_ARM | CPU_ARCH_ABI64)) {
  233. if (slice->cpusubtype == CLS_CPU_SUBTYPE_ARM64E) {
  234. return "arm64e";
  235. } else if (slice->cpusubtype == CPU_SUBTYPE_ARM64_ALL) {
  236. return "arm64";
  237. }
  238. }
  239. if (slice->cputype == (CPU_TYPE_ARM) && slice->cpusubtype == CPU_SUBTYPE_ARM_V7K) {
  240. return "armv7k";
  241. }
  242. archInfo = NXGetArchInfoFromCpuType(slice->cputype, slice->cpusubtype);
  243. if (!archInfo) {
  244. return "unknown";
  245. }
  246. return archInfo->name;
  247. }
  248. bool FIRCLSMachOSliceIs64Bit(FIRCLSMachOSliceRef slice) {
  249. // I'm pretty sure this is sufficient...
  250. return (slice->cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64;
  251. }
  252. bool FIRCLSMachOSliceGetSectionByName(FIRCLSMachOSliceRef slice,
  253. const char* segName,
  254. const char* sectionName,
  255. const void** ptr) {
  256. if (!ptr) {
  257. return false;
  258. }
  259. *ptr = NULL; // make sure this is set before returning
  260. FIRCLSMachOSection section;
  261. if (!FIRCLSMachOSliceInitSectionByName(slice, segName, sectionName, &section)) {
  262. return false;
  263. }
  264. // WARNING: this calculation isn't correct, but is here to maintain backwards
  265. // compatibility for now with callers of FIRCLSMachOSliceGetSectionByName. All new
  266. // users should be calling FIRCLSMachOSliceInitSectionByName
  267. *ptr = (const void*)((uintptr_t)slice->startAddress + section.offset);
  268. return true;
  269. }
  270. bool FIRCLSMachOSliceInitSectionByName(FIRCLSMachOSliceRef slice,
  271. const char* segName,
  272. const char* sectionName,
  273. FIRCLSMachOSection* section) {
  274. if (!FIRCLSMachOSliceIsValid(slice)) {
  275. return false;
  276. }
  277. if (!section) {
  278. return false;
  279. }
  280. memset(section, 0, sizeof(FIRCLSMachOSection));
  281. if (FIRCLSMachOSliceIs64Bit(slice)) {
  282. const struct section_64* sect =
  283. getsectbynamefromheader_64(slice->startAddress, segName, sectionName);
  284. if (!sect) {
  285. return false;
  286. }
  287. section->addr = sect->addr;
  288. section->size = sect->size;
  289. section->offset = sect->offset;
  290. } else {
  291. const struct section* sect = getsectbynamefromheader(slice->startAddress, segName, sectionName);
  292. if (!sect) {
  293. return false;
  294. }
  295. section->addr = sect->addr;
  296. section->size = sect->size;
  297. section->offset = sect->offset;
  298. }
  299. return true;
  300. }
  301. // TODO: this is left in-place just to ensure that old crashltyics + new fabric are still compatible
  302. // with each other. As a happy bonus, if that situation does come up, this will also fix the bug
  303. // that was preventing compact unwind on arm64 + iOS 9 from working correctly.
  304. void FIRCLSMachOSliceGetUnwindInformation(FIRCLSMachOSliceRef slice,
  305. const void** ehFrame,
  306. const void** unwindInfo) {
  307. if (!unwindInfo && !ehFrame) {
  308. return;
  309. }
  310. bool found = false;
  311. intptr_t slide = 0;
  312. // This is inefficient, but we have no other safe way to do this correctly. Modifying the
  313. // FIRCLSMachOSlice structure is tempting, but could introduce weird binary-compatibility issues
  314. // with version mis-matches.
  315. for (uint32_t i = 0; i < _dyld_image_count(); ++i) {
  316. const struct mach_header* header = _dyld_get_image_header(i);
  317. if (header == slice->startAddress) {
  318. found = true;
  319. slide = _dyld_get_image_vmaddr_slide(i);
  320. break;
  321. }
  322. }
  323. // make sure we were able to find a matching value
  324. if (!found) {
  325. return;
  326. }
  327. FIRCLSMachOSection section;
  328. if (unwindInfo) {
  329. if (FIRCLSMachOSliceInitSectionByName(slice, SEG_TEXT, "__unwind_info", &section)) {
  330. *unwindInfo = (void*)(section.addr + slide);
  331. }
  332. }
  333. if (ehFrame) {
  334. if (FIRCLSMachOSliceInitSectionByName(slice, SEG_TEXT, "__eh_frame", &section)) {
  335. *ehFrame = (void*)(section.addr + slide);
  336. }
  337. }
  338. }
  339. uint8_t const* FIRCLSMachOGetUUID(const struct load_command* cmd) {
  340. return ((const struct uuid_command*)cmd)->uuid;
  341. }
  342. const char* FIRCLSMachOGetDylibPath(const struct load_command* cmd) {
  343. const struct dylib_command* dylibcmd = (const struct dylib_command*)cmd;
  344. return (const char*)((uintptr_t)cmd + dylibcmd->dylib.name.offset);
  345. }
  346. bool FIRCLSMachOGetEncrypted(const struct load_command* cmd) {
  347. return ((struct encryption_info_command*)cmd)->cryptid > 0;
  348. }
  349. static FIRCLSMachOVersion FIRCLSMachOVersionFromEncoded(uint32_t encoded) {
  350. FIRCLSMachOVersion version;
  351. version.major = (encoded & 0xffff0000) >> 16;
  352. version.minor = (encoded & 0x0000ff00) >> 8;
  353. version.bugfix = encoded & 0x000000ff;
  354. return version;
  355. }
  356. FIRCLSMachOVersion FIRCLSMachOGetMinimumOSVersion(const struct load_command* cmd) {
  357. return FIRCLSMachOVersionFromEncoded(((const struct version_min_command*)cmd)->version);
  358. }
  359. FIRCLSMachOVersion FIRCLSMachOGetLinkedSDKVersion(const struct load_command* cmd) {
  360. return FIRCLSMachOVersionFromEncoded(((const struct version_min_command*)cmd)->sdk);
  361. }
  362. FIRCLSMachOSegmentCommand FIRCLSMachOGetSegmentCommand(const struct load_command* cmd) {
  363. FIRCLSMachOSegmentCommand segmentCommand;
  364. memset(&segmentCommand, 0, sizeof(FIRCLSMachOSegmentCommand));
  365. if (!cmd) {
  366. return segmentCommand;
  367. }
  368. if (cmd->cmd == LC_SEGMENT) {
  369. struct segment_command* segCmd = (struct segment_command*)cmd;
  370. memcpy(segmentCommand.segname, segCmd->segname, 16);
  371. segmentCommand.vmaddr = segCmd->vmaddr;
  372. segmentCommand.vmsize = segCmd->vmsize;
  373. } else if (cmd->cmd == LC_SEGMENT_64) {
  374. struct segment_command_64* segCmd = (struct segment_command_64*)cmd;
  375. memcpy(segmentCommand.segname, segCmd->segname, 16);
  376. segmentCommand.vmaddr = segCmd->vmaddr;
  377. segmentCommand.vmsize = segCmd->vmsize;
  378. }
  379. return segmentCommand;
  380. }
  381. NSString* FIRCLSMachONormalizeUUID(CFUUIDBytes* uuidBytes) {
  382. CFUUIDRef uuid = CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault, *uuidBytes);
  383. NSString* string = CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
  384. CFRelease(uuid);
  385. return [[string stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString];
  386. }
  387. NSString* FIRCLSMachOFormatVersion(FIRCLSMachOVersion* version) {
  388. if (!version) {
  389. return nil;
  390. }
  391. return [NSString stringWithFormat:@"%d.%d.%d", version->major, version->minor, version->bugfix];
  392. }