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