sanitizer_procmaps_mac.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. //===-- sanitizer_procmaps_mac.cpp ----------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Information about the process mappings (Mac-specific parts).
  10. //===----------------------------------------------------------------------===//
  11. #include "sanitizer_platform.h"
  12. #if SANITIZER_APPLE
  13. #include "sanitizer_common.h"
  14. #include "sanitizer_placement_new.h"
  15. #include "sanitizer_procmaps.h"
  16. #include <mach-o/dyld.h>
  17. #include <mach-o/loader.h>
  18. #include <mach/mach.h>
  19. // These are not available in older macOS SDKs.
  20. #ifndef CPU_SUBTYPE_X86_64_H
  21. #define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8) /* Haswell */
  22. #endif
  23. #ifndef CPU_SUBTYPE_ARM_V7S
  24. #define CPU_SUBTYPE_ARM_V7S ((cpu_subtype_t)11) /* Swift */
  25. #endif
  26. #ifndef CPU_SUBTYPE_ARM_V7K
  27. #define CPU_SUBTYPE_ARM_V7K ((cpu_subtype_t)12)
  28. #endif
  29. #ifndef CPU_TYPE_ARM64
  30. #define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64)
  31. #endif
  32. namespace __sanitizer {
  33. // Contains information used to iterate through sections.
  34. struct MemoryMappedSegmentData {
  35. char name[kMaxSegName];
  36. uptr nsects;
  37. const char *current_load_cmd_addr;
  38. u32 lc_type;
  39. uptr base_virt_addr;
  40. uptr addr_mask;
  41. };
  42. template <typename Section>
  43. static void NextSectionLoad(LoadedModule *module, MemoryMappedSegmentData *data,
  44. bool isWritable) {
  45. const Section *sc = (const Section *)data->current_load_cmd_addr;
  46. data->current_load_cmd_addr += sizeof(Section);
  47. uptr sec_start = (sc->addr & data->addr_mask) + data->base_virt_addr;
  48. uptr sec_end = sec_start + sc->size;
  49. module->addAddressRange(sec_start, sec_end, /*executable=*/false, isWritable,
  50. sc->sectname);
  51. }
  52. void MemoryMappedSegment::AddAddressRanges(LoadedModule *module) {
  53. // Don't iterate over sections when the caller hasn't set up the
  54. // data pointer, when there are no sections, or when the segment
  55. // is executable. Avoid iterating over executable sections because
  56. // it will confuse libignore, and because the extra granularity
  57. // of information is not needed by any sanitizers.
  58. if (!data_ || !data_->nsects || IsExecutable()) {
  59. module->addAddressRange(start, end, IsExecutable(), IsWritable(),
  60. data_ ? data_->name : nullptr);
  61. return;
  62. }
  63. do {
  64. if (data_->lc_type == LC_SEGMENT) {
  65. NextSectionLoad<struct section>(module, data_, IsWritable());
  66. #ifdef MH_MAGIC_64
  67. } else if (data_->lc_type == LC_SEGMENT_64) {
  68. NextSectionLoad<struct section_64>(module, data_, IsWritable());
  69. #endif
  70. }
  71. } while (--data_->nsects);
  72. }
  73. MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
  74. Reset();
  75. }
  76. MemoryMappingLayout::~MemoryMappingLayout() {
  77. }
  78. bool MemoryMappingLayout::Error() const {
  79. return false;
  80. }
  81. // More information about Mach-O headers can be found in mach-o/loader.h
  82. // Each Mach-O image has a header (mach_header or mach_header_64) starting with
  83. // a magic number, and a list of linker load commands directly following the
  84. // header.
  85. // A load command is at least two 32-bit words: the command type and the
  86. // command size in bytes. We're interested only in segment load commands
  87. // (LC_SEGMENT and LC_SEGMENT_64), which tell that a part of the file is mapped
  88. // into the task's address space.
  89. // The |vmaddr|, |vmsize| and |fileoff| fields of segment_command or
  90. // segment_command_64 correspond to the memory address, memory size and the
  91. // file offset of the current memory segment.
  92. // Because these fields are taken from the images as is, one needs to add
  93. // _dyld_get_image_vmaddr_slide() to get the actual addresses at runtime.
  94. void MemoryMappingLayout::Reset() {
  95. // Count down from the top.
  96. // TODO(glider): as per man 3 dyld, iterating over the headers with
  97. // _dyld_image_count is thread-unsafe. We need to register callbacks for
  98. // adding and removing images which will invalidate the MemoryMappingLayout
  99. // state.
  100. data_.current_image = _dyld_image_count();
  101. data_.current_load_cmd_count = -1;
  102. data_.current_load_cmd_addr = 0;
  103. data_.current_magic = 0;
  104. data_.current_filetype = 0;
  105. data_.current_arch = kModuleArchUnknown;
  106. internal_memset(data_.current_uuid, 0, kModuleUUIDSize);
  107. }
  108. // The dyld load address should be unchanged throughout process execution,
  109. // and it is expensive to compute once many libraries have been loaded,
  110. // so cache it here and do not reset.
  111. static mach_header *dyld_hdr = 0;
  112. static const char kDyldPath[] = "/usr/lib/dyld";
  113. static const int kDyldImageIdx = -1;
  114. // static
  115. void MemoryMappingLayout::CacheMemoryMappings() {
  116. // No-op on Mac for now.
  117. }
  118. void MemoryMappingLayout::LoadFromCache() {
  119. // No-op on Mac for now.
  120. }
  121. static bool IsDyldHdr(const mach_header *hdr) {
  122. return (hdr->magic == MH_MAGIC || hdr->magic == MH_MAGIC_64) &&
  123. hdr->filetype == MH_DYLINKER;
  124. }
  125. // _dyld_get_image_header() and related APIs don't report dyld itself.
  126. // We work around this by manually recursing through the memory map
  127. // until we hit a Mach header matching dyld instead. These recurse
  128. // calls are expensive, but the first memory map generation occurs
  129. // early in the process, when dyld is one of the only images loaded,
  130. // so it will be hit after only a few iterations. These assumptions don't hold
  131. // on macOS 13+ anymore (dyld itself has moved into the shared cache).
  132. static mach_header *GetDyldImageHeaderViaVMRegion() {
  133. vm_address_t address = 0;
  134. while (true) {
  135. vm_size_t size = 0;
  136. unsigned depth = 1;
  137. struct vm_region_submap_info_64 info;
  138. mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
  139. kern_return_t err =
  140. vm_region_recurse_64(mach_task_self(), &address, &size, &depth,
  141. (vm_region_info_t)&info, &count);
  142. if (err != KERN_SUCCESS) return nullptr;
  143. if (size >= sizeof(mach_header) && info.protection & kProtectionRead) {
  144. mach_header *hdr = (mach_header *)address;
  145. if (IsDyldHdr(hdr)) {
  146. return hdr;
  147. }
  148. }
  149. address += size;
  150. }
  151. }
  152. extern "C" {
  153. struct dyld_shared_cache_dylib_text_info {
  154. uint64_t version; // current version 2
  155. // following fields all exist in version 1
  156. uint64_t loadAddressUnslid;
  157. uint64_t textSegmentSize;
  158. uuid_t dylibUuid;
  159. const char *path; // pointer invalid at end of iterations
  160. // following fields all exist in version 2
  161. uint64_t textSegmentOffset; // offset from start of cache
  162. };
  163. typedef struct dyld_shared_cache_dylib_text_info
  164. dyld_shared_cache_dylib_text_info;
  165. extern bool _dyld_get_shared_cache_uuid(uuid_t uuid);
  166. extern const void *_dyld_get_shared_cache_range(size_t *length);
  167. extern int dyld_shared_cache_iterate_text(
  168. const uuid_t cacheUuid,
  169. void (^callback)(const dyld_shared_cache_dylib_text_info *info));
  170. } // extern "C"
  171. static mach_header *GetDyldImageHeaderViaSharedCache() {
  172. uuid_t uuid;
  173. bool hasCache = _dyld_get_shared_cache_uuid(uuid);
  174. if (!hasCache)
  175. return nullptr;
  176. size_t cacheLength;
  177. __block uptr cacheStart = (uptr)_dyld_get_shared_cache_range(&cacheLength);
  178. CHECK(cacheStart && cacheLength);
  179. __block mach_header *dyldHdr = nullptr;
  180. int res = dyld_shared_cache_iterate_text(
  181. uuid, ^(const dyld_shared_cache_dylib_text_info *info) {
  182. CHECK_GE(info->version, 2);
  183. mach_header *hdr =
  184. (mach_header *)(cacheStart + info->textSegmentOffset);
  185. if (IsDyldHdr(hdr))
  186. dyldHdr = hdr;
  187. });
  188. CHECK_EQ(res, 0);
  189. return dyldHdr;
  190. }
  191. const mach_header *get_dyld_hdr() {
  192. if (!dyld_hdr) {
  193. // On macOS 13+, dyld itself has moved into the shared cache. Looking it up
  194. // via vm_region_recurse_64() causes spins/hangs/crashes.
  195. if (GetMacosAlignedVersion() >= MacosVersion(13, 0)) {
  196. dyld_hdr = GetDyldImageHeaderViaSharedCache();
  197. if (!dyld_hdr) {
  198. VReport(1,
  199. "Failed to lookup the dyld image header in the shared cache on "
  200. "macOS 13+ (or no shared cache in use). Falling back to "
  201. "lookup via vm_region_recurse_64().\n");
  202. dyld_hdr = GetDyldImageHeaderViaVMRegion();
  203. }
  204. } else {
  205. dyld_hdr = GetDyldImageHeaderViaVMRegion();
  206. }
  207. CHECK(dyld_hdr);
  208. }
  209. return dyld_hdr;
  210. }
  211. // Next and NextSegmentLoad were inspired by base/sysinfo.cc in
  212. // Google Perftools, https://github.com/gperftools/gperftools.
  213. // NextSegmentLoad scans the current image for the next segment load command
  214. // and returns the start and end addresses and file offset of the corresponding
  215. // segment.
  216. // Note that the segment addresses are not necessarily sorted.
  217. template <u32 kLCSegment, typename SegmentCommand>
  218. static bool NextSegmentLoad(MemoryMappedSegment *segment,
  219. MemoryMappedSegmentData *seg_data,
  220. MemoryMappingLayoutData *layout_data) {
  221. const char *lc = layout_data->current_load_cmd_addr;
  222. layout_data->current_load_cmd_addr += ((const load_command *)lc)->cmdsize;
  223. if (((const load_command *)lc)->cmd == kLCSegment) {
  224. const SegmentCommand* sc = (const SegmentCommand *)lc;
  225. uptr base_virt_addr, addr_mask;
  226. if (layout_data->current_image == kDyldImageIdx) {
  227. base_virt_addr = (uptr)get_dyld_hdr();
  228. // vmaddr is masked with 0xfffff because on macOS versions < 10.12,
  229. // it contains an absolute address rather than an offset for dyld.
  230. // To make matters even more complicated, this absolute address
  231. // isn't actually the absolute segment address, but the offset portion
  232. // of the address is accurate when combined with the dyld base address,
  233. // and the mask will give just this offset.
  234. addr_mask = 0xfffff;
  235. } else {
  236. base_virt_addr =
  237. (uptr)_dyld_get_image_vmaddr_slide(layout_data->current_image);
  238. addr_mask = ~0;
  239. }
  240. segment->start = (sc->vmaddr & addr_mask) + base_virt_addr;
  241. segment->end = segment->start + sc->vmsize;
  242. // Most callers don't need section information, so only fill this struct
  243. // when required.
  244. if (seg_data) {
  245. seg_data->nsects = sc->nsects;
  246. seg_data->current_load_cmd_addr =
  247. (const char *)lc + sizeof(SegmentCommand);
  248. seg_data->lc_type = kLCSegment;
  249. seg_data->base_virt_addr = base_virt_addr;
  250. seg_data->addr_mask = addr_mask;
  251. internal_strncpy(seg_data->name, sc->segname,
  252. ARRAY_SIZE(seg_data->name));
  253. }
  254. // Return the initial protection.
  255. segment->protection = sc->initprot;
  256. segment->offset = (layout_data->current_filetype ==
  257. /*MH_EXECUTE*/ 0x2)
  258. ? sc->vmaddr
  259. : sc->fileoff;
  260. if (segment->filename) {
  261. const char *src = (layout_data->current_image == kDyldImageIdx)
  262. ? kDyldPath
  263. : _dyld_get_image_name(layout_data->current_image);
  264. internal_strncpy(segment->filename, src, segment->filename_size);
  265. }
  266. segment->arch = layout_data->current_arch;
  267. internal_memcpy(segment->uuid, layout_data->current_uuid, kModuleUUIDSize);
  268. return true;
  269. }
  270. return false;
  271. }
  272. ModuleArch ModuleArchFromCpuType(cpu_type_t cputype, cpu_subtype_t cpusubtype) {
  273. cpusubtype = cpusubtype & ~CPU_SUBTYPE_MASK;
  274. switch (cputype) {
  275. case CPU_TYPE_I386:
  276. return kModuleArchI386;
  277. case CPU_TYPE_X86_64:
  278. if (cpusubtype == CPU_SUBTYPE_X86_64_ALL) return kModuleArchX86_64;
  279. if (cpusubtype == CPU_SUBTYPE_X86_64_H) return kModuleArchX86_64H;
  280. CHECK(0 && "Invalid subtype of x86_64");
  281. return kModuleArchUnknown;
  282. case CPU_TYPE_ARM:
  283. if (cpusubtype == CPU_SUBTYPE_ARM_V6) return kModuleArchARMV6;
  284. if (cpusubtype == CPU_SUBTYPE_ARM_V7) return kModuleArchARMV7;
  285. if (cpusubtype == CPU_SUBTYPE_ARM_V7S) return kModuleArchARMV7S;
  286. if (cpusubtype == CPU_SUBTYPE_ARM_V7K) return kModuleArchARMV7K;
  287. CHECK(0 && "Invalid subtype of ARM");
  288. return kModuleArchUnknown;
  289. case CPU_TYPE_ARM64:
  290. return kModuleArchARM64;
  291. default:
  292. CHECK(0 && "Invalid CPU type");
  293. return kModuleArchUnknown;
  294. }
  295. }
  296. static const load_command *NextCommand(const load_command *lc) {
  297. return (const load_command *)((const char *)lc + lc->cmdsize);
  298. }
  299. static void FindUUID(const load_command *first_lc, u8 *uuid_output) {
  300. for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) {
  301. if (lc->cmd != LC_UUID) continue;
  302. const uuid_command *uuid_lc = (const uuid_command *)lc;
  303. const uint8_t *uuid = &uuid_lc->uuid[0];
  304. internal_memcpy(uuid_output, uuid, kModuleUUIDSize);
  305. return;
  306. }
  307. }
  308. static bool IsModuleInstrumented(const load_command *first_lc) {
  309. for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) {
  310. if (lc->cmd != LC_LOAD_DYLIB) continue;
  311. const dylib_command *dylib_lc = (const dylib_command *)lc;
  312. uint32_t dylib_name_offset = dylib_lc->dylib.name.offset;
  313. const char *dylib_name = ((const char *)dylib_lc) + dylib_name_offset;
  314. dylib_name = StripModuleName(dylib_name);
  315. if (dylib_name != 0 && (internal_strstr(dylib_name, "libclang_rt."))) {
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. bool MemoryMappingLayout::Next(MemoryMappedSegment *segment) {
  322. for (; data_.current_image >= kDyldImageIdx; data_.current_image--) {
  323. const mach_header *hdr = (data_.current_image == kDyldImageIdx)
  324. ? get_dyld_hdr()
  325. : _dyld_get_image_header(data_.current_image);
  326. if (!hdr) continue;
  327. if (data_.current_load_cmd_count < 0) {
  328. // Set up for this image;
  329. data_.current_load_cmd_count = hdr->ncmds;
  330. data_.current_magic = hdr->magic;
  331. data_.current_filetype = hdr->filetype;
  332. data_.current_arch = ModuleArchFromCpuType(hdr->cputype, hdr->cpusubtype);
  333. switch (data_.current_magic) {
  334. #ifdef MH_MAGIC_64
  335. case MH_MAGIC_64: {
  336. data_.current_load_cmd_addr =
  337. (const char *)hdr + sizeof(mach_header_64);
  338. break;
  339. }
  340. #endif
  341. case MH_MAGIC: {
  342. data_.current_load_cmd_addr = (const char *)hdr + sizeof(mach_header);
  343. break;
  344. }
  345. default: {
  346. continue;
  347. }
  348. }
  349. FindUUID((const load_command *)data_.current_load_cmd_addr,
  350. data_.current_uuid);
  351. data_.current_instrumented = IsModuleInstrumented(
  352. (const load_command *)data_.current_load_cmd_addr);
  353. }
  354. for (; data_.current_load_cmd_count >= 0; data_.current_load_cmd_count--) {
  355. switch (data_.current_magic) {
  356. // data_.current_magic may be only one of MH_MAGIC, MH_MAGIC_64.
  357. #ifdef MH_MAGIC_64
  358. case MH_MAGIC_64: {
  359. if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
  360. segment, segment->data_, &data_))
  361. return true;
  362. break;
  363. }
  364. #endif
  365. case MH_MAGIC: {
  366. if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
  367. segment, segment->data_, &data_))
  368. return true;
  369. break;
  370. }
  371. }
  372. }
  373. // If we get here, no more load_cmd's in this image talk about
  374. // segments. Go on to the next image.
  375. }
  376. return false;
  377. }
  378. void MemoryMappingLayout::DumpListOfModules(
  379. InternalMmapVectorNoCtor<LoadedModule> *modules) {
  380. Reset();
  381. InternalMmapVector<char> module_name(kMaxPathLength);
  382. MemoryMappedSegment segment(module_name.data(), module_name.size());
  383. MemoryMappedSegmentData data;
  384. segment.data_ = &data;
  385. while (Next(&segment)) {
  386. if (segment.filename[0] == '\0') continue;
  387. LoadedModule *cur_module = nullptr;
  388. if (!modules->empty() &&
  389. 0 == internal_strcmp(segment.filename, modules->back().full_name())) {
  390. cur_module = &modules->back();
  391. } else {
  392. modules->push_back(LoadedModule());
  393. cur_module = &modules->back();
  394. cur_module->set(segment.filename, segment.start, segment.arch,
  395. segment.uuid, data_.current_instrumented);
  396. }
  397. segment.AddAddressRanges(cur_module);
  398. }
  399. }
  400. } // namespace __sanitizer
  401. #endif // SANITIZER_APPLE