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