]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303571, and update
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_procmaps_mac.cc
1 //===-- sanitizer_procmaps_mac.cc -----------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Information about the process mappings (Mac-specific parts).
11 //===----------------------------------------------------------------------===//
12
13 #include "sanitizer_platform.h"
14 #if SANITIZER_MAC
15 #include "sanitizer_common.h"
16 #include "sanitizer_placement_new.h"
17 #include "sanitizer_procmaps.h"
18
19 #include <mach-o/dyld.h>
20 #include <mach-o/loader.h>
21 #include <mach/mach.h>
22
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 */
26 #endif
27 #ifndef CPU_SUBTYPE_ARM_V7S
28 #define CPU_SUBTYPE_ARM_V7S   ((cpu_subtype_t)11)  /* Swift */
29 #endif
30 #ifndef CPU_SUBTYPE_ARM_V7K
31 #define CPU_SUBTYPE_ARM_V7K   ((cpu_subtype_t)12)
32 #endif
33 #ifndef CPU_TYPE_ARM64
34 #define CPU_TYPE_ARM64        (CPU_TYPE_ARM | CPU_ARCH_ABI64)
35 #endif
36
37 namespace __sanitizer {
38
39 MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
40   Reset();
41 }
42
43 MemoryMappingLayout::~MemoryMappingLayout() {
44 }
45
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
49 // header.
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.
59
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
65   // state.
66   current_image_ = _dyld_image_count();
67   current_load_cmd_count_ = -1;
68   current_load_cmd_addr_ = 0;
69   current_magic_ = 0;
70   current_filetype_ = 0;
71   current_arch_ = kModuleArchUnknown;
72   internal_memset(current_uuid_, 0, kModuleUUIDSize);
73 }
74
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;
81
82 // static
83 void MemoryMappingLayout::CacheMemoryMappings() {
84   // No-op on Mac for now.
85 }
86
87 void MemoryMappingLayout::LoadFromCache() {
88   // No-op on Mac for now.
89 }
90
91 // Next and NextSegmentLoad were inspired by base/sysinfo.cc in
92 // Google Perftools, https://github.com/gperftools/gperftools.
93
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
96 // segment.
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,
102                                           uptr *protection) {
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);
108     if (protection) {
109       // Return the initial protection.
110       *protection = sc->initprot;
111     }
112     if (offset) {
113       if (current_filetype_ == /*MH_EXECUTE*/ 0x2) {
114         *offset = sc->vmaddr;
115       } else {
116         *offset = sc->fileoff;
117       }
118     }
119     if (filename) {
120       if (current_image_ == kDyldImageIdx) {
121         internal_strncpy(filename, kDyldPath, filename_size);
122       } else {
123         internal_strncpy(filename, _dyld_get_image_name(current_image_),
124                          filename_size);
125       }
126     }
127     if (arch) {
128       *arch = current_arch_;
129     }
130     if (uuid) {
131       internal_memcpy(uuid, current_uuid_, kModuleUUIDSize);
132     }
133     return true;
134   }
135   return false;
136 }
137
138 ModuleArch ModuleArchFromCpuType(cpu_type_t cputype, cpu_subtype_t cpusubtype) {
139   cpusubtype = cpusubtype & ~CPU_SUBTYPE_MASK;
140   switch (cputype) {
141     case CPU_TYPE_I386:
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;
148     case CPU_TYPE_ARM:
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;
155     case CPU_TYPE_ARM64:
156       return kModuleArchARM64;
157     default:
158       CHECK(0 && "Invalid CPU type");
159       return kModuleArchUnknown;
160   }
161 }
162
163 static const load_command *NextCommand(const load_command *lc) {
164   return (const load_command *)((char *)lc + lc->cmdsize);
165 }
166
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;
170
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);
174     return;
175   }
176 }
177
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;
181
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."))) {
187       return true;
188     }
189   }
190   return false;
191 }
192
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) !=
202       KERN_SUCCESS) {
203     return nullptr;
204   }
205
206   unsigned depth = 1;
207   vm_size_t size = 0;
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;
211
212   while (true) {
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;
217
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) {
223         return hdr;
224       }
225     }
226     address += size;
227   }
228 }
229
230 const mach_header *get_dyld_hdr() {
231   if (!dyld_hdr) dyld_hdr = get_dyld_image_header();
232
233   return dyld_hdr;
234 }
235
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();
247   } else {
248     const sptr dlloff = _dyld_get_image_vmaddr_slide(current_image_);
249     if (start) *start = vmaddr + dlloff;
250     if (end) *end = vmaddr + vmsize + dlloff;
251   }
252 }
253
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)
259                                  ? get_dyld_hdr()
260                                  : _dyld_get_image_header(current_image_);
261     if (!hdr) continue;
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_) {
269 #ifdef MH_MAGIC_64
270         case MH_MAGIC_64: {
271           current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header_64);
272           break;
273         }
274 #endif
275         case MH_MAGIC: {
276           current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header);
277           break;
278         }
279         default: {
280           continue;
281         }
282       }
283       FindUUID((const load_command *)current_load_cmd_addr_, &current_uuid_[0]);
284       current_instrumented_ =
285           IsModuleInstrumented((const load_command *)current_load_cmd_addr_);
286     }
287
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.
291 #ifdef MH_MAGIC_64
292         case MH_MAGIC_64: {
293           if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
294                   start, end, offset, filename, filename_size, arch, uuid,
295                   protection))
296             return true;
297           break;
298         }
299 #endif
300         case MH_MAGIC: {
301           if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
302                   start, end, offset, filename, filename_size, arch, uuid,
303                   protection))
304             return true;
305           break;
306         }
307       }
308     }
309     // If we get here, no more load_cmd's in this image talk about
310     // segments.  Go on to the next image.
311   }
312   return false;
313 }
314
315 void MemoryMappingLayout::DumpListOfModules(
316     InternalMmapVector<LoadedModule> *modules) {
317   Reset();
318   uptr cur_beg, cur_end, prot;
319   ModuleArch cur_arch;
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]);
324        i++) {
325     const char *cur_name = module_name.data();
326     if (cur_name[0] == '\0')
327       continue;
328     LoadedModule *cur_module = nullptr;
329     if (!modules->empty() &&
330         0 == internal_strcmp(cur_name, modules->back().full_name())) {
331       cur_module = &modules->back();
332     } else {
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_);
337     }
338     cur_module->addAddressRange(cur_beg, cur_end, prot & kProtectionExecute,
339                                 prot & kProtectionWrite);
340   }
341 }
342
343 }  // namespace __sanitizer
344
345 #endif  // SANITIZER_MAC