]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_procmaps_mac.cc
Merge ^/head r317808 through r317970.
[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
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 MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
39   Reset();
40 }
41
42 MemoryMappingLayout::~MemoryMappingLayout() {
43 }
44
45 // More information about Mach-O headers can be found in mach-o/loader.h
46 // Each Mach-O image has a header (mach_header or mach_header_64) starting with
47 // a magic number, and a list of linker load commands directly following the
48 // header.
49 // A load command is at least two 32-bit words: the command type and the
50 // command size in bytes. We're interested only in segment load commands
51 // (LC_SEGMENT and LC_SEGMENT_64), which tell that a part of the file is mapped
52 // into the task's address space.
53 // The |vmaddr|, |vmsize| and |fileoff| fields of segment_command or
54 // segment_command_64 correspond to the memory address, memory size and the
55 // file offset of the current memory segment.
56 // Because these fields are taken from the images as is, one needs to add
57 // _dyld_get_image_vmaddr_slide() to get the actual addresses at runtime.
58
59 void MemoryMappingLayout::Reset() {
60   // Count down from the top.
61   // TODO(glider): as per man 3 dyld, iterating over the headers with
62   // _dyld_image_count is thread-unsafe. We need to register callbacks for
63   // adding and removing images which will invalidate the MemoryMappingLayout
64   // state.
65   current_image_ = _dyld_image_count();
66   current_load_cmd_count_ = -1;
67   current_load_cmd_addr_ = 0;
68   current_magic_ = 0;
69   current_filetype_ = 0;
70   current_arch_ = kModuleArchUnknown;
71   internal_memset(current_uuid_, 0, kModuleUUIDSize);
72 }
73
74 // static
75 void MemoryMappingLayout::CacheMemoryMappings() {
76   // No-op on Mac for now.
77 }
78
79 void MemoryMappingLayout::LoadFromCache() {
80   // No-op on Mac for now.
81 }
82
83 // Next and NextSegmentLoad were inspired by base/sysinfo.cc in
84 // Google Perftools, https://github.com/gperftools/gperftools.
85
86 // NextSegmentLoad scans the current image for the next segment load command
87 // and returns the start and end addresses and file offset of the corresponding
88 // segment.
89 // Note that the segment addresses are not necessarily sorted.
90 template <u32 kLCSegment, typename SegmentCommand>
91 bool MemoryMappingLayout::NextSegmentLoad(uptr *start, uptr *end, uptr *offset,
92                                           char filename[], uptr filename_size,
93                                           ModuleArch *arch, u8 *uuid,
94                                           uptr *protection) {
95   const char *lc = current_load_cmd_addr_;
96   current_load_cmd_addr_ += ((const load_command *)lc)->cmdsize;
97   if (((const load_command *)lc)->cmd == kLCSegment) {
98     const sptr dlloff = _dyld_get_image_vmaddr_slide(current_image_);
99     const SegmentCommand* sc = (const SegmentCommand *)lc;
100     if (start) *start = sc->vmaddr + dlloff;
101     if (protection) {
102       // Return the initial protection.
103       *protection = sc->initprot;
104     }
105     if (end) *end = sc->vmaddr + sc->vmsize + dlloff;
106     if (offset) {
107       if (current_filetype_ == /*MH_EXECUTE*/ 0x2) {
108         *offset = sc->vmaddr;
109       } else {
110         *offset = sc->fileoff;
111       }
112     }
113     if (filename) {
114       internal_strncpy(filename, _dyld_get_image_name(current_image_),
115                        filename_size);
116     }
117     if (arch) {
118       *arch = current_arch_;
119     }
120     if (uuid) {
121       internal_memcpy(uuid, current_uuid_, kModuleUUIDSize);
122     }
123     return true;
124   }
125   return false;
126 }
127
128 ModuleArch ModuleArchFromCpuType(cpu_type_t cputype, cpu_subtype_t cpusubtype) {
129   cpusubtype = cpusubtype & ~CPU_SUBTYPE_MASK;
130   switch (cputype) {
131     case CPU_TYPE_I386:
132       return kModuleArchI386;
133     case CPU_TYPE_X86_64:
134       if (cpusubtype == CPU_SUBTYPE_X86_64_ALL) return kModuleArchX86_64;
135       if (cpusubtype == CPU_SUBTYPE_X86_64_H) return kModuleArchX86_64H;
136       CHECK(0 && "Invalid subtype of x86_64");
137       return kModuleArchUnknown;
138     case CPU_TYPE_ARM:
139       if (cpusubtype == CPU_SUBTYPE_ARM_V6) return kModuleArchARMV6;
140       if (cpusubtype == CPU_SUBTYPE_ARM_V7) return kModuleArchARMV7;
141       if (cpusubtype == CPU_SUBTYPE_ARM_V7S) return kModuleArchARMV7S;
142       if (cpusubtype == CPU_SUBTYPE_ARM_V7K) return kModuleArchARMV7K;
143       CHECK(0 && "Invalid subtype of ARM");
144       return kModuleArchUnknown;
145     case CPU_TYPE_ARM64:
146       return kModuleArchARM64;
147     default:
148       CHECK(0 && "Invalid CPU type");
149       return kModuleArchUnknown;
150   }
151 }
152
153 static const load_command *NextCommand(const load_command *lc) {
154   return (const load_command *)((char *)lc + lc->cmdsize);
155 }
156
157 static void FindUUID(const load_command *first_lc, u8 *uuid_output) {
158   for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) {
159     if (lc->cmd != LC_UUID) continue;
160
161     const uuid_command *uuid_lc = (const uuid_command *)lc;
162     const uint8_t *uuid = &uuid_lc->uuid[0];
163     internal_memcpy(uuid_output, uuid, kModuleUUIDSize);
164     return;
165   }
166 }
167
168 static bool IsModuleInstrumented(const load_command *first_lc) {
169   for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) {
170     if (lc->cmd != LC_LOAD_DYLIB) continue;
171
172     const dylib_command *dylib_lc = (const dylib_command *)lc;
173     uint32_t dylib_name_offset = dylib_lc->dylib.name.offset;
174     const char *dylib_name = ((const char *)dylib_lc) + dylib_name_offset;
175     dylib_name = StripModuleName(dylib_name);
176     if (dylib_name != 0 && (internal_strstr(dylib_name, "libclang_rt."))) {
177       return true;
178     }
179   }
180   return false;
181 }
182
183 bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
184                                char filename[], uptr filename_size,
185                                uptr *protection, ModuleArch *arch, u8 *uuid) {
186   for (; current_image_ >= 0; current_image_--) {
187     const mach_header* hdr = _dyld_get_image_header(current_image_);
188     if (!hdr) continue;
189     if (current_load_cmd_count_ < 0) {
190       // Set up for this image;
191       current_load_cmd_count_ = hdr->ncmds;
192       current_magic_ = hdr->magic;
193       current_filetype_ = hdr->filetype;
194       current_arch_ = ModuleArchFromCpuType(hdr->cputype, hdr->cpusubtype);
195       switch (current_magic_) {
196 #ifdef MH_MAGIC_64
197         case MH_MAGIC_64: {
198           current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header_64);
199           break;
200         }
201 #endif
202         case MH_MAGIC: {
203           current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header);
204           break;
205         }
206         default: {
207           continue;
208         }
209       }
210       FindUUID((const load_command *)current_load_cmd_addr_, &current_uuid_[0]);
211       current_instrumented_ =
212           IsModuleInstrumented((const load_command *)current_load_cmd_addr_);
213     }
214
215     for (; current_load_cmd_count_ >= 0; current_load_cmd_count_--) {
216       switch (current_magic_) {
217         // current_magic_ may be only one of MH_MAGIC, MH_MAGIC_64.
218 #ifdef MH_MAGIC_64
219         case MH_MAGIC_64: {
220           if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
221                   start, end, offset, filename, filename_size, arch, uuid,
222                   protection))
223             return true;
224           break;
225         }
226 #endif
227         case MH_MAGIC: {
228           if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
229                   start, end, offset, filename, filename_size, arch, uuid,
230                   protection))
231             return true;
232           break;
233         }
234       }
235     }
236     // If we get here, no more load_cmd's in this image talk about
237     // segments.  Go on to the next image.
238   }
239   return false;
240 }
241
242 void MemoryMappingLayout::DumpListOfModules(
243     InternalMmapVector<LoadedModule> *modules) {
244   Reset();
245   uptr cur_beg, cur_end, prot;
246   ModuleArch cur_arch;
247   u8 cur_uuid[kModuleUUIDSize];
248   InternalScopedString module_name(kMaxPathLength);
249   for (uptr i = 0; Next(&cur_beg, &cur_end, 0, module_name.data(),
250                         module_name.size(), &prot, &cur_arch, &cur_uuid[0]);
251        i++) {
252     const char *cur_name = module_name.data();
253     if (cur_name[0] == '\0')
254       continue;
255     LoadedModule *cur_module = nullptr;
256     if (!modules->empty() &&
257         0 == internal_strcmp(cur_name, modules->back().full_name())) {
258       cur_module = &modules->back();
259     } else {
260       modules->push_back(LoadedModule());
261       cur_module = &modules->back();
262       cur_module->set(cur_name, cur_beg, cur_arch, cur_uuid,
263                       current_instrumented_);
264     }
265     cur_module->addAddressRange(cur_beg, cur_end, prot & kProtectionExecute,
266                                 prot & kProtectionRead);
267   }
268 }
269
270 }  // namespace __sanitizer
271
272 #endif  // SANITIZER_MAC