1 //===-- sanitizer_procmaps_mac.cc -----------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Information about the process mappings (Mac-specific parts).
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
15 #include "sanitizer_common.h"
16 #include "sanitizer_placement_new.h"
17 #include "sanitizer_procmaps.h"
19 #include <mach-o/dyld.h>
20 #include <mach-o/loader.h>
21 #include <mach/mach.h>
23 // These are not available in older macOS SDKs.
24 #ifndef CPU_SUBTYPE_X86_64_H
25 #define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8) /* Haswell */
27 #ifndef CPU_SUBTYPE_ARM_V7S
28 #define CPU_SUBTYPE_ARM_V7S ((cpu_subtype_t)11) /* Swift */
30 #ifndef CPU_SUBTYPE_ARM_V7K
31 #define CPU_SUBTYPE_ARM_V7K ((cpu_subtype_t)12)
33 #ifndef CPU_TYPE_ARM64
34 #define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64)
37 namespace __sanitizer {
39 MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
43 MemoryMappingLayout::~MemoryMappingLayout() {
46 // More information about Mach-O headers can be found in mach-o/loader.h
47 // Each Mach-O image has a header (mach_header or mach_header_64) starting with
48 // a magic number, and a list of linker load commands directly following the
50 // A load command is at least two 32-bit words: the command type and the
51 // command size in bytes. We're interested only in segment load commands
52 // (LC_SEGMENT and LC_SEGMENT_64), which tell that a part of the file is mapped
53 // into the task's address space.
54 // The |vmaddr|, |vmsize| and |fileoff| fields of segment_command or
55 // segment_command_64 correspond to the memory address, memory size and the
56 // file offset of the current memory segment.
57 // Because these fields are taken from the images as is, one needs to add
58 // _dyld_get_image_vmaddr_slide() to get the actual addresses at runtime.
60 void MemoryMappingLayout::Reset() {
61 // Count down from the top.
62 // TODO(glider): as per man 3 dyld, iterating over the headers with
63 // _dyld_image_count is thread-unsafe. We need to register callbacks for
64 // adding and removing images which will invalidate the MemoryMappingLayout
66 current_image_ = _dyld_image_count();
67 current_load_cmd_count_ = -1;
68 current_load_cmd_addr_ = 0;
70 current_filetype_ = 0;
71 current_arch_ = kModuleArchUnknown;
72 internal_memset(current_uuid_, 0, kModuleUUIDSize);
75 // The dyld load address should be unchanged throughout process execution,
76 // and it is expensive to compute once many libraries have been loaded,
77 // so cache it here and do not reset.
78 static mach_header *dyld_hdr = 0;
79 static const char kDyldPath[] = "/usr/lib/dyld";
80 static const int kDyldImageIdx = -1;
83 void MemoryMappingLayout::CacheMemoryMappings() {
84 // No-op on Mac for now.
87 void MemoryMappingLayout::LoadFromCache() {
88 // No-op on Mac for now.
91 // Next and NextSegmentLoad were inspired by base/sysinfo.cc in
92 // Google Perftools, https://github.com/gperftools/gperftools.
94 // NextSegmentLoad scans the current image for the next segment load command
95 // and returns the start and end addresses and file offset of the corresponding
97 // Note that the segment addresses are not necessarily sorted.
98 template <u32 kLCSegment, typename SegmentCommand>
99 bool MemoryMappingLayout::NextSegmentLoad(uptr *start, uptr *end, uptr *offset,
100 char filename[], uptr filename_size,
101 ModuleArch *arch, u8 *uuid,
103 const char *lc = current_load_cmd_addr_;
104 current_load_cmd_addr_ += ((const load_command *)lc)->cmdsize;
105 if (((const load_command *)lc)->cmd == kLCSegment) {
106 const SegmentCommand* sc = (const SegmentCommand *)lc;
107 GetSegmentAddrRange(start, end, sc->vmaddr, sc->vmsize);
109 // Return the initial protection.
110 *protection = sc->initprot;
113 if (current_filetype_ == /*MH_EXECUTE*/ 0x2) {
114 *offset = sc->vmaddr;
116 *offset = sc->fileoff;
120 if (current_image_ == kDyldImageIdx) {
121 internal_strncpy(filename, kDyldPath, filename_size);
123 internal_strncpy(filename, _dyld_get_image_name(current_image_),
128 *arch = current_arch_;
131 internal_memcpy(uuid, current_uuid_, kModuleUUIDSize);
138 ModuleArch ModuleArchFromCpuType(cpu_type_t cputype, cpu_subtype_t cpusubtype) {
139 cpusubtype = cpusubtype & ~CPU_SUBTYPE_MASK;
142 return kModuleArchI386;
143 case CPU_TYPE_X86_64:
144 if (cpusubtype == CPU_SUBTYPE_X86_64_ALL) return kModuleArchX86_64;
145 if (cpusubtype == CPU_SUBTYPE_X86_64_H) return kModuleArchX86_64H;
146 CHECK(0 && "Invalid subtype of x86_64");
147 return kModuleArchUnknown;
149 if (cpusubtype == CPU_SUBTYPE_ARM_V6) return kModuleArchARMV6;
150 if (cpusubtype == CPU_SUBTYPE_ARM_V7) return kModuleArchARMV7;
151 if (cpusubtype == CPU_SUBTYPE_ARM_V7S) return kModuleArchARMV7S;
152 if (cpusubtype == CPU_SUBTYPE_ARM_V7K) return kModuleArchARMV7K;
153 CHECK(0 && "Invalid subtype of ARM");
154 return kModuleArchUnknown;
156 return kModuleArchARM64;
158 CHECK(0 && "Invalid CPU type");
159 return kModuleArchUnknown;
163 static const load_command *NextCommand(const load_command *lc) {
164 return (const load_command *)((char *)lc + lc->cmdsize);
167 static void FindUUID(const load_command *first_lc, u8 *uuid_output) {
168 for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) {
169 if (lc->cmd != LC_UUID) continue;
171 const uuid_command *uuid_lc = (const uuid_command *)lc;
172 const uint8_t *uuid = &uuid_lc->uuid[0];
173 internal_memcpy(uuid_output, uuid, kModuleUUIDSize);
178 static bool IsModuleInstrumented(const load_command *first_lc) {
179 for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) {
180 if (lc->cmd != LC_LOAD_DYLIB) continue;
182 const dylib_command *dylib_lc = (const dylib_command *)lc;
183 uint32_t dylib_name_offset = dylib_lc->dylib.name.offset;
184 const char *dylib_name = ((const char *)dylib_lc) + dylib_name_offset;
185 dylib_name = StripModuleName(dylib_name);
186 if (dylib_name != 0 && (internal_strstr(dylib_name, "libclang_rt."))) {
193 // _dyld_get_image_header() and related APIs don't report dyld itself.
194 // We work around this by manually recursing through the memory map
195 // until we hit a Mach header matching dyld instead. These recurse
196 // calls are expensive, but the first memory map generation occurs
197 // early in the process, when dyld is one of the only images loaded,
198 // so it will be hit after only a few iterations.
199 static mach_header *get_dyld_image_header() {
200 mach_port_name_t port;
201 if (task_for_pid(mach_task_self(), internal_getpid(), &port) !=
208 vm_address_t address = 0;
209 kern_return_t err = KERN_SUCCESS;
210 mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
213 struct vm_region_submap_info_64 info;
214 err = vm_region_recurse_64(port, &address, &size, &depth,
215 (vm_region_info_t)&info, &count);
216 if (err != KERN_SUCCESS) return nullptr;
218 if (size >= sizeof(mach_header) &&
219 info.protection & MemoryMappingLayout::kProtectionRead) {
220 mach_header *hdr = (mach_header *)address;
221 if ((hdr->magic == MH_MAGIC || hdr->magic == MH_MAGIC_64) &&
222 hdr->filetype == MH_DYLINKER) {
230 const mach_header *get_dyld_hdr() {
231 if (!dyld_hdr) dyld_hdr = get_dyld_image_header();
236 void MemoryMappingLayout::GetSegmentAddrRange(uptr *start, uptr *end,
237 uptr vmaddr, uptr vmsize) {
238 if (current_image_ == kDyldImageIdx) {
239 // vmaddr is masked with 0xfffff because on macOS versions < 10.12,
240 // it contains an absolute address rather than an offset for dyld.
241 // To make matters even more complicated, this absolute address
242 // isn't actually the absolute segment address, but the offset portion
243 // of the address is accurate when combined with the dyld base address,
244 // and the mask will give just this offset.
245 if (start) *start = (vmaddr & 0xfffff) + (uptr)get_dyld_hdr();
246 if (end) *end = (vmaddr & 0xfffff) + vmsize + (uptr)get_dyld_hdr();
248 const sptr dlloff = _dyld_get_image_vmaddr_slide(current_image_);
249 if (start) *start = vmaddr + dlloff;
250 if (end) *end = vmaddr + vmsize + dlloff;
254 bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
255 char filename[], uptr filename_size,
256 uptr *protection, ModuleArch *arch, u8 *uuid) {
257 for (; current_image_ >= kDyldImageIdx; current_image_--) {
258 const mach_header *hdr = (current_image_ == kDyldImageIdx)
260 : _dyld_get_image_header(current_image_);
262 if (current_load_cmd_count_ < 0) {
263 // Set up for this image;
264 current_load_cmd_count_ = hdr->ncmds;
265 current_magic_ = hdr->magic;
266 current_filetype_ = hdr->filetype;
267 current_arch_ = ModuleArchFromCpuType(hdr->cputype, hdr->cpusubtype);
268 switch (current_magic_) {
271 current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header_64);
276 current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header);
283 FindUUID((const load_command *)current_load_cmd_addr_, ¤t_uuid_[0]);
284 current_instrumented_ =
285 IsModuleInstrumented((const load_command *)current_load_cmd_addr_);
288 for (; current_load_cmd_count_ >= 0; current_load_cmd_count_--) {
289 switch (current_magic_) {
290 // current_magic_ may be only one of MH_MAGIC, MH_MAGIC_64.
293 if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
294 start, end, offset, filename, filename_size, arch, uuid,
301 if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
302 start, end, offset, filename, filename_size, arch, uuid,
309 // If we get here, no more load_cmd's in this image talk about
310 // segments. Go on to the next image.
315 void MemoryMappingLayout::DumpListOfModules(
316 InternalMmapVector<LoadedModule> *modules) {
318 uptr cur_beg, cur_end, prot;
320 u8 cur_uuid[kModuleUUIDSize];
321 InternalScopedString module_name(kMaxPathLength);
322 for (uptr i = 0; Next(&cur_beg, &cur_end, 0, module_name.data(),
323 module_name.size(), &prot, &cur_arch, &cur_uuid[0]);
325 const char *cur_name = module_name.data();
326 if (cur_name[0] == '\0')
328 LoadedModule *cur_module = nullptr;
329 if (!modules->empty() &&
330 0 == internal_strcmp(cur_name, modules->back().full_name())) {
331 cur_module = &modules->back();
333 modules->push_back(LoadedModule());
334 cur_module = &modules->back();
335 cur_module->set(cur_name, cur_beg, cur_arch, cur_uuid,
336 current_instrumented_);
338 cur_module->addAddressRange(cur_beg, cur_end, prot & kProtectionExecute,
339 prot & kProtectionWrite);
343 } // namespace __sanitizer
345 #endif // SANITIZER_MAC