1353944Sdim//===-- sanitizer_procmaps_mac.cpp ----------------------------------------===//
2353944Sdim//
3353944Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353944Sdim// See https://llvm.org/LICENSE.txt for license information.
5353944Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6353944Sdim//
7353944Sdim//===----------------------------------------------------------------------===//
8353944Sdim//
9353944Sdim// Information about the process mappings (Mac-specific parts).
10353944Sdim//===----------------------------------------------------------------------===//
11353944Sdim
12353944Sdim#include "sanitizer_platform.h"
13353944Sdim#if SANITIZER_MAC
14353944Sdim#include "sanitizer_common.h"
15353944Sdim#include "sanitizer_placement_new.h"
16353944Sdim#include "sanitizer_procmaps.h"
17353944Sdim
18353944Sdim#include <mach-o/dyld.h>
19353944Sdim#include <mach-o/loader.h>
20353944Sdim#include <mach/mach.h>
21353944Sdim
22353944Sdim// These are not available in older macOS SDKs.
23353944Sdim#ifndef CPU_SUBTYPE_X86_64_H
24353944Sdim#define CPU_SUBTYPE_X86_64_H  ((cpu_subtype_t)8)   /* Haswell */
25353944Sdim#endif
26353944Sdim#ifndef CPU_SUBTYPE_ARM_V7S
27353944Sdim#define CPU_SUBTYPE_ARM_V7S   ((cpu_subtype_t)11)  /* Swift */
28353944Sdim#endif
29353944Sdim#ifndef CPU_SUBTYPE_ARM_V7K
30353944Sdim#define CPU_SUBTYPE_ARM_V7K   ((cpu_subtype_t)12)
31353944Sdim#endif
32353944Sdim#ifndef CPU_TYPE_ARM64
33353944Sdim#define CPU_TYPE_ARM64        (CPU_TYPE_ARM | CPU_ARCH_ABI64)
34353944Sdim#endif
35353944Sdim
36353944Sdimnamespace __sanitizer {
37353944Sdim
38353944Sdim// Contains information used to iterate through sections.
39353944Sdimstruct MemoryMappedSegmentData {
40353944Sdim  char name[kMaxSegName];
41353944Sdim  uptr nsects;
42353944Sdim  const char *current_load_cmd_addr;
43353944Sdim  u32 lc_type;
44353944Sdim  uptr base_virt_addr;
45353944Sdim  uptr addr_mask;
46353944Sdim};
47353944Sdim
48353944Sdimtemplate <typename Section>
49353944Sdimstatic void NextSectionLoad(LoadedModule *module, MemoryMappedSegmentData *data,
50353944Sdim                            bool isWritable) {
51353944Sdim  const Section *sc = (const Section *)data->current_load_cmd_addr;
52353944Sdim  data->current_load_cmd_addr += sizeof(Section);
53353944Sdim
54353944Sdim  uptr sec_start = (sc->addr & data->addr_mask) + data->base_virt_addr;
55353944Sdim  uptr sec_end = sec_start + sc->size;
56353944Sdim  module->addAddressRange(sec_start, sec_end, /*executable=*/false, isWritable,
57353944Sdim                          sc->sectname);
58353944Sdim}
59353944Sdim
60353944Sdimvoid MemoryMappedSegment::AddAddressRanges(LoadedModule *module) {
61353944Sdim  // Don't iterate over sections when the caller hasn't set up the
62353944Sdim  // data pointer, when there are no sections, or when the segment
63353944Sdim  // is executable. Avoid iterating over executable sections because
64353944Sdim  // it will confuse libignore, and because the extra granularity
65353944Sdim  // of information is not needed by any sanitizers.
66353944Sdim  if (!data_ || !data_->nsects || IsExecutable()) {
67353944Sdim    module->addAddressRange(start, end, IsExecutable(), IsWritable(),
68353944Sdim                            data_ ? data_->name : nullptr);
69353944Sdim    return;
70353944Sdim  }
71353944Sdim
72353944Sdim  do {
73353944Sdim    if (data_->lc_type == LC_SEGMENT) {
74353944Sdim      NextSectionLoad<struct section>(module, data_, IsWritable());
75353944Sdim#ifdef MH_MAGIC_64
76353944Sdim    } else if (data_->lc_type == LC_SEGMENT_64) {
77353944Sdim      NextSectionLoad<struct section_64>(module, data_, IsWritable());
78353944Sdim#endif
79353944Sdim    }
80353944Sdim  } while (--data_->nsects);
81353944Sdim}
82353944Sdim
83353944SdimMemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
84353944Sdim  Reset();
85353944Sdim}
86353944Sdim
87353944SdimMemoryMappingLayout::~MemoryMappingLayout() {
88353944Sdim}
89353944Sdim
90353944Sdimbool MemoryMappingLayout::Error() const {
91353944Sdim  return false;
92353944Sdim}
93353944Sdim
94353944Sdim// More information about Mach-O headers can be found in mach-o/loader.h
95353944Sdim// Each Mach-O image has a header (mach_header or mach_header_64) starting with
96353944Sdim// a magic number, and a list of linker load commands directly following the
97353944Sdim// header.
98353944Sdim// A load command is at least two 32-bit words: the command type and the
99353944Sdim// command size in bytes. We're interested only in segment load commands
100353944Sdim// (LC_SEGMENT and LC_SEGMENT_64), which tell that a part of the file is mapped
101353944Sdim// into the task's address space.
102353944Sdim// The |vmaddr|, |vmsize| and |fileoff| fields of segment_command or
103353944Sdim// segment_command_64 correspond to the memory address, memory size and the
104353944Sdim// file offset of the current memory segment.
105353944Sdim// Because these fields are taken from the images as is, one needs to add
106353944Sdim// _dyld_get_image_vmaddr_slide() to get the actual addresses at runtime.
107353944Sdim
108353944Sdimvoid MemoryMappingLayout::Reset() {
109353944Sdim  // Count down from the top.
110353944Sdim  // TODO(glider): as per man 3 dyld, iterating over the headers with
111353944Sdim  // _dyld_image_count is thread-unsafe. We need to register callbacks for
112353944Sdim  // adding and removing images which will invalidate the MemoryMappingLayout
113353944Sdim  // state.
114353944Sdim  data_.current_image = _dyld_image_count();
115353944Sdim  data_.current_load_cmd_count = -1;
116353944Sdim  data_.current_load_cmd_addr = 0;
117353944Sdim  data_.current_magic = 0;
118353944Sdim  data_.current_filetype = 0;
119353944Sdim  data_.current_arch = kModuleArchUnknown;
120353944Sdim  internal_memset(data_.current_uuid, 0, kModuleUUIDSize);
121353944Sdim}
122353944Sdim
123353944Sdim// The dyld load address should be unchanged throughout process execution,
124353944Sdim// and it is expensive to compute once many libraries have been loaded,
125353944Sdim// so cache it here and do not reset.
126353944Sdimstatic mach_header *dyld_hdr = 0;
127353944Sdimstatic const char kDyldPath[] = "/usr/lib/dyld";
128353944Sdimstatic const int kDyldImageIdx = -1;
129353944Sdim
130353944Sdim// static
131353944Sdimvoid MemoryMappingLayout::CacheMemoryMappings() {
132353944Sdim  // No-op on Mac for now.
133353944Sdim}
134353944Sdim
135353944Sdimvoid MemoryMappingLayout::LoadFromCache() {
136353944Sdim  // No-op on Mac for now.
137353944Sdim}
138353944Sdim
139353944Sdim// _dyld_get_image_header() and related APIs don't report dyld itself.
140353944Sdim// We work around this by manually recursing through the memory map
141353944Sdim// until we hit a Mach header matching dyld instead. These recurse
142353944Sdim// calls are expensive, but the first memory map generation occurs
143353944Sdim// early in the process, when dyld is one of the only images loaded,
144353944Sdim// so it will be hit after only a few iterations.
145353944Sdimstatic mach_header *get_dyld_image_header() {
146353944Sdim  unsigned depth = 1;
147353944Sdim  vm_size_t size = 0;
148353944Sdim  vm_address_t address = 0;
149353944Sdim  kern_return_t err = KERN_SUCCESS;
150353944Sdim  mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
151353944Sdim
152353944Sdim  while (true) {
153353944Sdim    struct vm_region_submap_info_64 info;
154353944Sdim    err = vm_region_recurse_64(mach_task_self(), &address, &size, &depth,
155353944Sdim                               (vm_region_info_t)&info, &count);
156353944Sdim    if (err != KERN_SUCCESS) return nullptr;
157353944Sdim
158353944Sdim    if (size >= sizeof(mach_header) && info.protection & kProtectionRead) {
159353944Sdim      mach_header *hdr = (mach_header *)address;
160353944Sdim      if ((hdr->magic == MH_MAGIC || hdr->magic == MH_MAGIC_64) &&
161353944Sdim          hdr->filetype == MH_DYLINKER) {
162353944Sdim        return hdr;
163353944Sdim      }
164353944Sdim    }
165353944Sdim    address += size;
166353944Sdim  }
167353944Sdim}
168353944Sdim
169353944Sdimconst mach_header *get_dyld_hdr() {
170353944Sdim  if (!dyld_hdr) dyld_hdr = get_dyld_image_header();
171353944Sdim
172353944Sdim  return dyld_hdr;
173353944Sdim}
174353944Sdim
175353944Sdim// Next and NextSegmentLoad were inspired by base/sysinfo.cc in
176353944Sdim// Google Perftools, https://github.com/gperftools/gperftools.
177353944Sdim
178353944Sdim// NextSegmentLoad scans the current image for the next segment load command
179353944Sdim// and returns the start and end addresses and file offset of the corresponding
180353944Sdim// segment.
181353944Sdim// Note that the segment addresses are not necessarily sorted.
182353944Sdimtemplate <u32 kLCSegment, typename SegmentCommand>
183353944Sdimstatic bool NextSegmentLoad(MemoryMappedSegment *segment,
184353944Sdim                            MemoryMappedSegmentData *seg_data,
185353944Sdim                            MemoryMappingLayoutData *layout_data) {
186353944Sdim  const char *lc = layout_data->current_load_cmd_addr;
187353944Sdim  layout_data->current_load_cmd_addr += ((const load_command *)lc)->cmdsize;
188353944Sdim  if (((const load_command *)lc)->cmd == kLCSegment) {
189353944Sdim    const SegmentCommand* sc = (const SegmentCommand *)lc;
190353944Sdim    uptr base_virt_addr, addr_mask;
191353944Sdim    if (layout_data->current_image == kDyldImageIdx) {
192353944Sdim      base_virt_addr = (uptr)get_dyld_hdr();
193353944Sdim      // vmaddr is masked with 0xfffff because on macOS versions < 10.12,
194353944Sdim      // it contains an absolute address rather than an offset for dyld.
195353944Sdim      // To make matters even more complicated, this absolute address
196353944Sdim      // isn't actually the absolute segment address, but the offset portion
197353944Sdim      // of the address is accurate when combined with the dyld base address,
198353944Sdim      // and the mask will give just this offset.
199353944Sdim      addr_mask = 0xfffff;
200353944Sdim    } else {
201353944Sdim      base_virt_addr =
202353944Sdim          (uptr)_dyld_get_image_vmaddr_slide(layout_data->current_image);
203353944Sdim      addr_mask = ~0;
204353944Sdim    }
205353944Sdim
206353944Sdim    segment->start = (sc->vmaddr & addr_mask) + base_virt_addr;
207353944Sdim    segment->end = segment->start + sc->vmsize;
208353944Sdim    // Most callers don't need section information, so only fill this struct
209353944Sdim    // when required.
210353944Sdim    if (seg_data) {
211353944Sdim      seg_data->nsects = sc->nsects;
212353944Sdim      seg_data->current_load_cmd_addr =
213353944Sdim          (const char *)lc + sizeof(SegmentCommand);
214353944Sdim      seg_data->lc_type = kLCSegment;
215353944Sdim      seg_data->base_virt_addr = base_virt_addr;
216353944Sdim      seg_data->addr_mask = addr_mask;
217353944Sdim      internal_strncpy(seg_data->name, sc->segname,
218353944Sdim                       ARRAY_SIZE(seg_data->name));
219353944Sdim    }
220353944Sdim
221353944Sdim    // Return the initial protection.
222353944Sdim    segment->protection = sc->initprot;
223353944Sdim    segment->offset = (layout_data->current_filetype ==
224353944Sdim                       /*MH_EXECUTE*/ 0x2)
225353944Sdim                          ? sc->vmaddr
226353944Sdim                          : sc->fileoff;
227353944Sdim    if (segment->filename) {
228353944Sdim      const char *src = (layout_data->current_image == kDyldImageIdx)
229353944Sdim                            ? kDyldPath
230353944Sdim                            : _dyld_get_image_name(layout_data->current_image);
231353944Sdim      internal_strncpy(segment->filename, src, segment->filename_size);
232353944Sdim    }
233353944Sdim    segment->arch = layout_data->current_arch;
234353944Sdim    internal_memcpy(segment->uuid, layout_data->current_uuid, kModuleUUIDSize);
235353944Sdim    return true;
236353944Sdim  }
237353944Sdim  return false;
238353944Sdim}
239353944Sdim
240353944SdimModuleArch ModuleArchFromCpuType(cpu_type_t cputype, cpu_subtype_t cpusubtype) {
241353944Sdim  cpusubtype = cpusubtype & ~CPU_SUBTYPE_MASK;
242353944Sdim  switch (cputype) {
243353944Sdim    case CPU_TYPE_I386:
244353944Sdim      return kModuleArchI386;
245353944Sdim    case CPU_TYPE_X86_64:
246353944Sdim      if (cpusubtype == CPU_SUBTYPE_X86_64_ALL) return kModuleArchX86_64;
247353944Sdim      if (cpusubtype == CPU_SUBTYPE_X86_64_H) return kModuleArchX86_64H;
248353944Sdim      CHECK(0 && "Invalid subtype of x86_64");
249353944Sdim      return kModuleArchUnknown;
250353944Sdim    case CPU_TYPE_ARM:
251353944Sdim      if (cpusubtype == CPU_SUBTYPE_ARM_V6) return kModuleArchARMV6;
252353944Sdim      if (cpusubtype == CPU_SUBTYPE_ARM_V7) return kModuleArchARMV7;
253353944Sdim      if (cpusubtype == CPU_SUBTYPE_ARM_V7S) return kModuleArchARMV7S;
254353944Sdim      if (cpusubtype == CPU_SUBTYPE_ARM_V7K) return kModuleArchARMV7K;
255353944Sdim      CHECK(0 && "Invalid subtype of ARM");
256353944Sdim      return kModuleArchUnknown;
257353944Sdim    case CPU_TYPE_ARM64:
258353944Sdim      return kModuleArchARM64;
259353944Sdim    default:
260353944Sdim      CHECK(0 && "Invalid CPU type");
261353944Sdim      return kModuleArchUnknown;
262353944Sdim  }
263353944Sdim}
264353944Sdim
265353944Sdimstatic const load_command *NextCommand(const load_command *lc) {
266353944Sdim  return (const load_command *)((const char *)lc + lc->cmdsize);
267353944Sdim}
268353944Sdim
269353944Sdimstatic void FindUUID(const load_command *first_lc, u8 *uuid_output) {
270353944Sdim  for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) {
271353944Sdim    if (lc->cmd != LC_UUID) continue;
272353944Sdim
273353944Sdim    const uuid_command *uuid_lc = (const uuid_command *)lc;
274353944Sdim    const uint8_t *uuid = &uuid_lc->uuid[0];
275353944Sdim    internal_memcpy(uuid_output, uuid, kModuleUUIDSize);
276353944Sdim    return;
277353944Sdim  }
278353944Sdim}
279353944Sdim
280353944Sdimstatic bool IsModuleInstrumented(const load_command *first_lc) {
281353944Sdim  for (const load_command *lc = first_lc; lc->cmd != 0; lc = NextCommand(lc)) {
282353944Sdim    if (lc->cmd != LC_LOAD_DYLIB) continue;
283353944Sdim
284353944Sdim    const dylib_command *dylib_lc = (const dylib_command *)lc;
285353944Sdim    uint32_t dylib_name_offset = dylib_lc->dylib.name.offset;
286353944Sdim    const char *dylib_name = ((const char *)dylib_lc) + dylib_name_offset;
287353944Sdim    dylib_name = StripModuleName(dylib_name);
288353944Sdim    if (dylib_name != 0 && (internal_strstr(dylib_name, "libclang_rt."))) {
289353944Sdim      return true;
290353944Sdim    }
291353944Sdim  }
292353944Sdim  return false;
293353944Sdim}
294353944Sdim
295353944Sdimbool MemoryMappingLayout::Next(MemoryMappedSegment *segment) {
296353944Sdim  for (; data_.current_image >= kDyldImageIdx; data_.current_image--) {
297353944Sdim    const mach_header *hdr = (data_.current_image == kDyldImageIdx)
298353944Sdim                                 ? get_dyld_hdr()
299353944Sdim                                 : _dyld_get_image_header(data_.current_image);
300353944Sdim    if (!hdr) continue;
301353944Sdim    if (data_.current_load_cmd_count < 0) {
302353944Sdim      // Set up for this image;
303353944Sdim      data_.current_load_cmd_count = hdr->ncmds;
304353944Sdim      data_.current_magic = hdr->magic;
305353944Sdim      data_.current_filetype = hdr->filetype;
306353944Sdim      data_.current_arch = ModuleArchFromCpuType(hdr->cputype, hdr->cpusubtype);
307353944Sdim      switch (data_.current_magic) {
308353944Sdim#ifdef MH_MAGIC_64
309353944Sdim        case MH_MAGIC_64: {
310353944Sdim          data_.current_load_cmd_addr =
311353944Sdim              (const char *)hdr + sizeof(mach_header_64);
312353944Sdim          break;
313353944Sdim        }
314353944Sdim#endif
315353944Sdim        case MH_MAGIC: {
316353944Sdim          data_.current_load_cmd_addr = (const char *)hdr + sizeof(mach_header);
317353944Sdim          break;
318353944Sdim        }
319353944Sdim        default: {
320353944Sdim          continue;
321353944Sdim        }
322353944Sdim      }
323353944Sdim      FindUUID((const load_command *)data_.current_load_cmd_addr,
324353944Sdim               data_.current_uuid);
325353944Sdim      data_.current_instrumented = IsModuleInstrumented(
326353944Sdim          (const load_command *)data_.current_load_cmd_addr);
327353944Sdim    }
328353944Sdim
329353944Sdim    for (; data_.current_load_cmd_count >= 0; data_.current_load_cmd_count--) {
330353944Sdim      switch (data_.current_magic) {
331353944Sdim        // data_.current_magic may be only one of MH_MAGIC, MH_MAGIC_64.
332353944Sdim#ifdef MH_MAGIC_64
333353944Sdim        case MH_MAGIC_64: {
334353944Sdim          if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
335353944Sdim                  segment, segment->data_, &data_))
336353944Sdim            return true;
337353944Sdim          break;
338353944Sdim        }
339353944Sdim#endif
340353944Sdim        case MH_MAGIC: {
341353944Sdim          if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
342353944Sdim                  segment, segment->data_, &data_))
343353944Sdim            return true;
344353944Sdim          break;
345353944Sdim        }
346353944Sdim      }
347353944Sdim    }
348353944Sdim    // If we get here, no more load_cmd's in this image talk about
349353944Sdim    // segments.  Go on to the next image.
350353944Sdim  }
351353944Sdim  return false;
352353944Sdim}
353353944Sdim
354353944Sdimvoid MemoryMappingLayout::DumpListOfModules(
355353944Sdim    InternalMmapVectorNoCtor<LoadedModule> *modules) {
356353944Sdim  Reset();
357353944Sdim  InternalScopedString module_name(kMaxPathLength);
358353944Sdim  MemoryMappedSegment segment(module_name.data(), kMaxPathLength);
359353944Sdim  MemoryMappedSegmentData data;
360353944Sdim  segment.data_ = &data;
361353944Sdim  while (Next(&segment)) {
362353944Sdim    if (segment.filename[0] == '\0') continue;
363353944Sdim    LoadedModule *cur_module = nullptr;
364353944Sdim    if (!modules->empty() &&
365353944Sdim        0 == internal_strcmp(segment.filename, modules->back().full_name())) {
366353944Sdim      cur_module = &modules->back();
367353944Sdim    } else {
368353944Sdim      modules->push_back(LoadedModule());
369353944Sdim      cur_module = &modules->back();
370353944Sdim      cur_module->set(segment.filename, segment.start, segment.arch,
371353944Sdim                      segment.uuid, data_.current_instrumented);
372353944Sdim    }
373353944Sdim    segment.AddAddressRanges(cur_module);
374353944Sdim  }
375353944Sdim}
376353944Sdim
377353944Sdim}  // namespace __sanitizer
378353944Sdim
379353944Sdim#endif  // SANITIZER_MAC
380