Vendor import of compiler-rt trunk r290819:
[freebsd.git] / 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 void FindUUID(const load_command *first_lc, u8 *uuid_output) {
154   const load_command *current_lc = first_lc;
155   while (1) {
156     if (current_lc->cmd == 0) return;
157     if (current_lc->cmd == LC_UUID) {
158       const uuid_command *uuid_lc = (const uuid_command *)current_lc;
159       const uint8_t *uuid = &uuid_lc->uuid[0];
160       internal_memcpy(uuid_output, uuid, kModuleUUIDSize);
161       return;
162     }
163
164     current_lc =
165         (const load_command *)(((char *)current_lc) + current_lc->cmdsize);
166   }
167 }
168
169 bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
170                                char filename[], uptr filename_size,
171                                uptr *protection, ModuleArch *arch, u8 *uuid) {
172   for (; current_image_ >= 0; current_image_--) {
173     const mach_header* hdr = _dyld_get_image_header(current_image_);
174     if (!hdr) continue;
175     if (current_load_cmd_count_ < 0) {
176       // Set up for this image;
177       current_load_cmd_count_ = hdr->ncmds;
178       current_magic_ = hdr->magic;
179       current_filetype_ = hdr->filetype;
180       current_arch_ = ModuleArchFromCpuType(hdr->cputype, hdr->cpusubtype);
181       switch (current_magic_) {
182 #ifdef MH_MAGIC_64
183         case MH_MAGIC_64: {
184           current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header_64);
185           break;
186         }
187 #endif
188         case MH_MAGIC: {
189           current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header);
190           break;
191         }
192         default: {
193           continue;
194         }
195       }
196     }
197
198     FindUUID((const load_command *)current_load_cmd_addr_, &current_uuid_[0]);
199
200     for (; current_load_cmd_count_ >= 0; current_load_cmd_count_--) {
201       switch (current_magic_) {
202         // current_magic_ may be only one of MH_MAGIC, MH_MAGIC_64.
203 #ifdef MH_MAGIC_64
204         case MH_MAGIC_64: {
205           if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
206                   start, end, offset, filename, filename_size, arch, uuid,
207                   protection))
208             return true;
209           break;
210         }
211 #endif
212         case MH_MAGIC: {
213           if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
214                   start, end, offset, filename, filename_size, arch, uuid,
215                   protection))
216             return true;
217           break;
218         }
219       }
220     }
221     // If we get here, no more load_cmd's in this image talk about
222     // segments.  Go on to the next image.
223   }
224   return false;
225 }
226
227 void MemoryMappingLayout::DumpListOfModules(
228     InternalMmapVector<LoadedModule> *modules) {
229   Reset();
230   uptr cur_beg, cur_end, prot;
231   ModuleArch cur_arch;
232   u8 cur_uuid[kModuleUUIDSize];
233   InternalScopedString module_name(kMaxPathLength);
234   for (uptr i = 0; Next(&cur_beg, &cur_end, 0, module_name.data(),
235                         module_name.size(), &prot, &cur_arch, &cur_uuid[0]);
236        i++) {
237     const char *cur_name = module_name.data();
238     if (cur_name[0] == '\0')
239       continue;
240     LoadedModule *cur_module = nullptr;
241     if (!modules->empty() &&
242         0 == internal_strcmp(cur_name, modules->back().full_name())) {
243       cur_module = &modules->back();
244     } else {
245       modules->push_back(LoadedModule());
246       cur_module = &modules->back();
247       cur_module->set(cur_name, cur_beg, cur_arch, cur_uuid);
248     }
249     cur_module->addAddressRange(cur_beg, cur_end, prot & kProtectionExecute);
250   }
251 }
252
253 }  // namespace __sanitizer
254
255 #endif  // SANITIZER_MAC