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