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