1 //===-- sanitizer_fuchsia.cpp ---------------------------------------------===//
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 // This file is shared between AddressSanitizer and other sanitizer
10 // run-time libraries and implements Fuchsia-specific functions from
11 // sanitizer_common.h.
12 //===----------------------------------------------------------------------===//
13 
14 #include "sanitizer_fuchsia.h"
15 #if SANITIZER_FUCHSIA
16 
17 #  include <pthread.h>
18 #  include <stdlib.h>
19 #  include <unistd.h>
20 #  include <zircon/errors.h>
21 #  include <zircon/process.h>
22 #  include <zircon/syscalls.h>
23 #  include <zircon/utc.h>
24 
25 #  include "sanitizer_common.h"
26 #  include "sanitizer_interface_internal.h"
27 #  include "sanitizer_libc.h"
28 #  include "sanitizer_mutex.h"
29 
30 namespace __sanitizer {
31 
32 void NORETURN internal__exit(int exitcode) { _zx_process_exit(exitcode); }
33 
34 uptr internal_sched_yield() {
35   zx_status_t status = _zx_thread_legacy_yield(0u);
36   CHECK_EQ(status, ZX_OK);
37   return 0;  // Why doesn't this return void?
38 }
39 
40 void internal_usleep(u64 useconds) {
41   zx_status_t status = _zx_nanosleep(_zx_deadline_after(ZX_USEC(useconds)));
42   CHECK_EQ(status, ZX_OK);
43 }
44 
45 u64 NanoTime() {
46   zx_handle_t utc_clock = _zx_utc_reference_get();
47   CHECK_NE(utc_clock, ZX_HANDLE_INVALID);
48   zx_time_t time;
49   zx_status_t status = _zx_clock_read(utc_clock, &time);
50   CHECK_EQ(status, ZX_OK);
51   return time;
52 }
53 
54 u64 MonotonicNanoTime() { return _zx_clock_get_monotonic(); }
55 
56 uptr internal_getpid() {
57   zx_info_handle_basic_t info;
58   zx_status_t status =
59       _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &info,
60                           sizeof(info), NULL, NULL);
61   CHECK_EQ(status, ZX_OK);
62   uptr pid = static_cast<uptr>(info.koid);
63   CHECK_EQ(pid, info.koid);
64   return pid;
65 }
66 
67 int internal_dlinfo(void *handle, int request, void *p) { UNIMPLEMENTED(); }
68 
69 uptr GetThreadSelf() { return reinterpret_cast<uptr>(thrd_current()); }
70 
71 tid_t GetTid() { return GetThreadSelf(); }
72 
73 void Abort() { abort(); }
74 
75 int Atexit(void (*function)(void)) { return atexit(function); }
76 
77 void GetThreadStackTopAndBottom(bool, uptr *stack_top, uptr *stack_bottom) {
78   pthread_attr_t attr;
79   CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
80   void *base;
81   size_t size;
82   CHECK_EQ(pthread_attr_getstack(&attr, &base, &size), 0);
83   CHECK_EQ(pthread_attr_destroy(&attr), 0);
84 
85   *stack_bottom = reinterpret_cast<uptr>(base);
86   *stack_top = *stack_bottom + size;
87 }
88 
89 void InitializePlatformEarly() {}
90 void CheckASLR() {}
91 void CheckMPROTECT() {}
92 void PlatformPrepareForSandboxing(void *args) {}
93 void DisableCoreDumperIfNecessary() {}
94 void InstallDeadlySignalHandlers(SignalHandlerType handler) {}
95 void SetAlternateSignalStack() {}
96 void UnsetAlternateSignalStack() {}
97 void InitTlsSize() {}
98 
99 bool SignalContext::IsStackOverflow() const { return false; }
100 void SignalContext::DumpAllRegisters(void *context) { UNIMPLEMENTED(); }
101 const char *SignalContext::Describe() const { UNIMPLEMENTED(); }
102 
103 void FutexWait(atomic_uint32_t *p, u32 cmp) {
104   zx_status_t status = _zx_futex_wait(reinterpret_cast<zx_futex_t *>(p), cmp,
105                                       ZX_HANDLE_INVALID, ZX_TIME_INFINITE);
106   if (status != ZX_ERR_BAD_STATE)  // Normal race.
107     CHECK_EQ(status, ZX_OK);
108 }
109 
110 void FutexWake(atomic_uint32_t *p, u32 count) {
111   zx_status_t status = _zx_futex_wake(reinterpret_cast<zx_futex_t *>(p), count);
112   CHECK_EQ(status, ZX_OK);
113 }
114 
115 uptr GetPageSize() { return _zx_system_get_page_size(); }
116 
117 uptr GetMmapGranularity() { return _zx_system_get_page_size(); }
118 
119 sanitizer_shadow_bounds_t ShadowBounds;
120 
121 void InitShadowBounds() { ShadowBounds = __sanitizer_shadow_bounds(); }
122 
123 uptr GetMaxUserVirtualAddress() {
124   InitShadowBounds();
125   return ShadowBounds.memory_limit - 1;
126 }
127 
128 uptr GetMaxVirtualAddress() { return GetMaxUserVirtualAddress(); }
129 
130 bool ErrorIsOOM(error_t err) { return err == ZX_ERR_NO_MEMORY; }
131 
132 static void *DoAnonymousMmapOrDie(uptr size, const char *mem_type,
133                                   bool raw_report, bool die_for_nomem) {
134   size = RoundUpTo(size, GetPageSize());
135 
136   zx_handle_t vmo;
137   zx_status_t status = _zx_vmo_create(size, 0, &vmo);
138   if (status != ZX_OK) {
139     if (status != ZX_ERR_NO_MEMORY || die_for_nomem)
140       ReportMmapFailureAndDie(size, mem_type, "zx_vmo_create", status,
141                               raw_report);
142     return nullptr;
143   }
144   _zx_object_set_property(vmo, ZX_PROP_NAME, mem_type,
145                           internal_strlen(mem_type));
146 
147   // TODO(mcgrathr): Maybe allocate a VMAR for all sanitizer heap and use that?
148   uintptr_t addr;
149   status =
150       _zx_vmar_map(_zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0,
151                    vmo, 0, size, &addr);
152   _zx_handle_close(vmo);
153 
154   if (status != ZX_OK) {
155     if (status != ZX_ERR_NO_MEMORY || die_for_nomem)
156       ReportMmapFailureAndDie(size, mem_type, "zx_vmar_map", status,
157                               raw_report);
158     return nullptr;
159   }
160 
161   IncreaseTotalMmap(size);
162 
163   return reinterpret_cast<void *>(addr);
164 }
165 
166 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
167   return DoAnonymousMmapOrDie(size, mem_type, raw_report, true);
168 }
169 
170 void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
171   return MmapOrDie(size, mem_type);
172 }
173 
174 void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
175   return DoAnonymousMmapOrDie(size, mem_type, false, false);
176 }
177 
178 uptr ReservedAddressRange::Init(uptr init_size, const char *name,
179                                 uptr fixed_addr) {
180   init_size = RoundUpTo(init_size, GetPageSize());
181   DCHECK_EQ(os_handle_, ZX_HANDLE_INVALID);
182   uintptr_t base;
183   zx_handle_t vmar;
184   zx_status_t status = _zx_vmar_allocate(
185       _zx_vmar_root_self(),
186       ZX_VM_CAN_MAP_READ | ZX_VM_CAN_MAP_WRITE | ZX_VM_CAN_MAP_SPECIFIC, 0,
187       init_size, &vmar, &base);
188   if (status != ZX_OK)
189     ReportMmapFailureAndDie(init_size, name, "zx_vmar_allocate", status);
190   base_ = reinterpret_cast<void *>(base);
191   size_ = init_size;
192   name_ = name;
193   os_handle_ = vmar;
194 
195   return reinterpret_cast<uptr>(base_);
196 }
197 
198 static uptr DoMmapFixedOrDie(zx_handle_t vmar, uptr fixed_addr, uptr map_size,
199                              void *base, const char *name, bool die_for_nomem) {
200   uptr offset = fixed_addr - reinterpret_cast<uptr>(base);
201   map_size = RoundUpTo(map_size, GetPageSize());
202   zx_handle_t vmo;
203   zx_status_t status = _zx_vmo_create(map_size, 0, &vmo);
204   if (status != ZX_OK) {
205     if (status != ZX_ERR_NO_MEMORY || die_for_nomem)
206       ReportMmapFailureAndDie(map_size, name, "zx_vmo_create", status);
207     return 0;
208   }
209   _zx_object_set_property(vmo, ZX_PROP_NAME, name, internal_strlen(name));
210   DCHECK_GE(base + size_, map_size + offset);
211   uintptr_t addr;
212 
213   status =
214       _zx_vmar_map(vmar, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_SPECIFIC,
215                    offset, vmo, 0, map_size, &addr);
216   _zx_handle_close(vmo);
217   if (status != ZX_OK) {
218     if (status != ZX_ERR_NO_MEMORY || die_for_nomem) {
219       ReportMmapFailureAndDie(map_size, name, "zx_vmar_map", status);
220     }
221     return 0;
222   }
223   IncreaseTotalMmap(map_size);
224   return addr;
225 }
226 
227 uptr ReservedAddressRange::Map(uptr fixed_addr, uptr map_size,
228                                const char *name) {
229   return DoMmapFixedOrDie(os_handle_, fixed_addr, map_size, base_, name_,
230                           false);
231 }
232 
233 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr map_size,
234                                     const char *name) {
235   return DoMmapFixedOrDie(os_handle_, fixed_addr, map_size, base_, name_, true);
236 }
237 
238 void UnmapOrDieVmar(void *addr, uptr size, zx_handle_t target_vmar) {
239   if (!addr || !size)
240     return;
241   size = RoundUpTo(size, GetPageSize());
242 
243   zx_status_t status =
244       _zx_vmar_unmap(target_vmar, reinterpret_cast<uintptr_t>(addr), size);
245   if (status != ZX_OK) {
246     Report("ERROR: %s failed to deallocate 0x%zx (%zd) bytes at address %p\n",
247            SanitizerToolName, size, size, addr);
248     CHECK("unable to unmap" && 0);
249   }
250 
251   DecreaseTotalMmap(size);
252 }
253 
254 void ReservedAddressRange::Unmap(uptr addr, uptr size) {
255   CHECK_LE(size, size_);
256   const zx_handle_t vmar = static_cast<zx_handle_t>(os_handle_);
257   if (addr == reinterpret_cast<uptr>(base_)) {
258     if (size == size_) {
259       // Destroying the vmar effectively unmaps the whole mapping.
260       _zx_vmar_destroy(vmar);
261       _zx_handle_close(vmar);
262       os_handle_ = static_cast<uptr>(ZX_HANDLE_INVALID);
263       DecreaseTotalMmap(size);
264       return;
265     }
266   } else {
267     CHECK_EQ(addr + size, reinterpret_cast<uptr>(base_) + size_);
268   }
269   // Partial unmapping does not affect the fact that the initial range is still
270   // reserved, and the resulting unmapped memory can't be reused.
271   UnmapOrDieVmar(reinterpret_cast<void *>(addr), size, vmar);
272 }
273 
274 // This should never be called.
275 void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
276   UNIMPLEMENTED();
277 }
278 
279 bool MprotectNoAccess(uptr addr, uptr size) {
280   return _zx_vmar_protect(_zx_vmar_root_self(), 0, addr, size) == ZX_OK;
281 }
282 
283 bool MprotectReadOnly(uptr addr, uptr size) {
284   return _zx_vmar_protect(_zx_vmar_root_self(), ZX_VM_PERM_READ, addr, size) ==
285          ZX_OK;
286 }
287 
288 bool MprotectReadWrite(uptr addr, uptr size) {
289   return _zx_vmar_protect(_zx_vmar_root_self(),
290                           ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, addr,
291                           size) == ZX_OK;
292 }
293 
294 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
295                                    const char *mem_type) {
296   CHECK_GE(size, GetPageSize());
297   CHECK(IsPowerOfTwo(size));
298   CHECK(IsPowerOfTwo(alignment));
299 
300   zx_handle_t vmo;
301   zx_status_t status = _zx_vmo_create(size, 0, &vmo);
302   if (status != ZX_OK) {
303     if (status != ZX_ERR_NO_MEMORY)
304       ReportMmapFailureAndDie(size, mem_type, "zx_vmo_create", status, false);
305     return nullptr;
306   }
307   _zx_object_set_property(vmo, ZX_PROP_NAME, mem_type,
308                           internal_strlen(mem_type));
309 
310   // TODO(mcgrathr): Maybe allocate a VMAR for all sanitizer heap and use that?
311 
312   // Map a larger size to get a chunk of address space big enough that
313   // it surely contains an aligned region of the requested size.  Then
314   // overwrite the aligned middle portion with a mapping from the
315   // beginning of the VMO, and unmap the excess before and after.
316   size_t map_size = size + alignment;
317   uintptr_t addr;
318   status =
319       _zx_vmar_map(_zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0,
320                    vmo, 0, map_size, &addr);
321   if (status == ZX_OK) {
322     uintptr_t map_addr = addr;
323     uintptr_t map_end = map_addr + map_size;
324     addr = RoundUpTo(map_addr, alignment);
325     uintptr_t end = addr + size;
326     if (addr != map_addr) {
327       zx_info_vmar_t info;
328       status = _zx_object_get_info(_zx_vmar_root_self(), ZX_INFO_VMAR, &info,
329                                    sizeof(info), NULL, NULL);
330       if (status == ZX_OK) {
331         uintptr_t new_addr;
332         status = _zx_vmar_map(
333             _zx_vmar_root_self(),
334             ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_SPECIFIC_OVERWRITE,
335             addr - info.base, vmo, 0, size, &new_addr);
336         if (status == ZX_OK)
337           CHECK_EQ(new_addr, addr);
338       }
339     }
340     if (status == ZX_OK && addr != map_addr)
341       status = _zx_vmar_unmap(_zx_vmar_root_self(), map_addr, addr - map_addr);
342     if (status == ZX_OK && end != map_end)
343       status = _zx_vmar_unmap(_zx_vmar_root_self(), end, map_end - end);
344   }
345   _zx_handle_close(vmo);
346 
347   if (status != ZX_OK) {
348     if (status != ZX_ERR_NO_MEMORY)
349       ReportMmapFailureAndDie(size, mem_type, "zx_vmar_map", status, false);
350     return nullptr;
351   }
352 
353   IncreaseTotalMmap(size);
354 
355   return reinterpret_cast<void *>(addr);
356 }
357 
358 void UnmapOrDie(void *addr, uptr size) {
359   UnmapOrDieVmar(addr, size, _zx_vmar_root_self());
360 }
361 
362 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
363   uptr beg_aligned = RoundUpTo(beg, GetPageSize());
364   uptr end_aligned = RoundDownTo(end, GetPageSize());
365   if (beg_aligned < end_aligned) {
366     zx_handle_t root_vmar = _zx_vmar_root_self();
367     CHECK_NE(root_vmar, ZX_HANDLE_INVALID);
368     zx_status_t status =
369         _zx_vmar_op_range(root_vmar, ZX_VMAR_OP_DECOMMIT, beg_aligned,
370                           end_aligned - beg_aligned, nullptr, 0);
371     CHECK_EQ(status, ZX_OK);
372   }
373 }
374 
375 void DumpProcessMap() {
376   // TODO(mcgrathr): write it
377   return;
378 }
379 
380 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
381   // TODO(mcgrathr): Figure out a better way.
382   zx_handle_t vmo;
383   zx_status_t status = _zx_vmo_create(size, 0, &vmo);
384   if (status == ZX_OK) {
385     status = _zx_vmo_write(vmo, reinterpret_cast<const void *>(beg), 0, size);
386     _zx_handle_close(vmo);
387   }
388   return status == ZX_OK;
389 }
390 
391 // FIXME implement on this platform.
392 void GetMemoryProfile(fill_profile_f cb, uptr *stats) {}
393 
394 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
395                       uptr *read_len, uptr max_len, error_t *errno_p) {
396   *errno_p = ZX_ERR_NOT_SUPPORTED;
397   return false;
398 }
399 
400 void RawWrite(const char *buffer) {
401   constexpr size_t size = 128;
402   static _Thread_local char line[size];
403   static _Thread_local size_t lastLineEnd = 0;
404   static _Thread_local size_t cur = 0;
405 
406   while (*buffer) {
407     if (cur >= size) {
408       if (lastLineEnd == 0)
409         lastLineEnd = size;
410       __sanitizer_log_write(line, lastLineEnd);
411       internal_memmove(line, line + lastLineEnd, cur - lastLineEnd);
412       cur = cur - lastLineEnd;
413       lastLineEnd = 0;
414     }
415     if (*buffer == '\n')
416       lastLineEnd = cur + 1;
417     line[cur++] = *buffer++;
418   }
419   // Flush all complete lines before returning.
420   if (lastLineEnd != 0) {
421     __sanitizer_log_write(line, lastLineEnd);
422     internal_memmove(line, line + lastLineEnd, cur - lastLineEnd);
423     cur = cur - lastLineEnd;
424     lastLineEnd = 0;
425   }
426 }
427 
428 void CatastrophicErrorWrite(const char *buffer, uptr length) {
429   __sanitizer_log_write(buffer, length);
430 }
431 
432 char **StoredArgv;
433 char **StoredEnviron;
434 
435 char **GetArgv() { return StoredArgv; }
436 char **GetEnviron() { return StoredEnviron; }
437 
438 const char *GetEnv(const char *name) {
439   if (StoredEnviron) {
440     uptr NameLen = internal_strlen(name);
441     for (char **Env = StoredEnviron; *Env != 0; Env++) {
442       if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
443         return (*Env) + NameLen + 1;
444     }
445   }
446   return nullptr;
447 }
448 
449 uptr ReadBinaryName(/*out*/ char *buf, uptr buf_len) {
450   const char *argv0 = "<UNKNOWN>";
451   if (StoredArgv && StoredArgv[0]) {
452     argv0 = StoredArgv[0];
453   }
454   internal_strncpy(buf, argv0, buf_len);
455   return internal_strlen(buf);
456 }
457 
458 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
459   return ReadBinaryName(buf, buf_len);
460 }
461 
462 uptr MainThreadStackBase, MainThreadStackSize;
463 
464 bool GetRandom(void *buffer, uptr length, bool blocking) {
465   CHECK_LE(length, ZX_CPRNG_DRAW_MAX_LEN);
466   _zx_cprng_draw(buffer, length);
467   return true;
468 }
469 
470 u32 GetNumberOfCPUs() { return zx_system_get_num_cpus(); }
471 
472 uptr GetRSS() { UNIMPLEMENTED(); }
473 
474 void *internal_start_thread(void *(*func)(void *arg), void *arg) { return 0; }
475 void internal_join_thread(void *th) {}
476 
477 void InitializePlatformCommonFlags(CommonFlags *cf) {}
478 
479 }  // namespace __sanitizer
480 
481 using namespace __sanitizer;
482 
483 extern "C" {
484 void __sanitizer_startup_hook(int argc, char **argv, char **envp,
485                               void *stack_base, size_t stack_size) {
486   __sanitizer::StoredArgv = argv;
487   __sanitizer::StoredEnviron = envp;
488   __sanitizer::MainThreadStackBase = reinterpret_cast<uintptr_t>(stack_base);
489   __sanitizer::MainThreadStackSize = stack_size;
490 }
491 
492 void __sanitizer_set_report_path(const char *path) {
493   // Handle the initialization code in each sanitizer, but no other calls.
494   // This setting is never consulted on Fuchsia.
495   DCHECK_EQ(path, common_flags()->log_path);
496 }
497 
498 void __sanitizer_set_report_fd(void *fd) {
499   UNREACHABLE("not available on Fuchsia");
500 }
501 
502 const char *__sanitizer_get_report_path() {
503   UNREACHABLE("not available on Fuchsia");
504 }
505 }  // extern "C"
506 
507 #endif  // SANITIZER_FUCHSIA
508