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 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
289                                    const char *mem_type) {
290   CHECK_GE(size, GetPageSize());
291   CHECK(IsPowerOfTwo(size));
292   CHECK(IsPowerOfTwo(alignment));
293 
294   zx_handle_t vmo;
295   zx_status_t status = _zx_vmo_create(size, 0, &vmo);
296   if (status != ZX_OK) {
297     if (status != ZX_ERR_NO_MEMORY)
298       ReportMmapFailureAndDie(size, mem_type, "zx_vmo_create", status, false);
299     return nullptr;
300   }
301   _zx_object_set_property(vmo, ZX_PROP_NAME, mem_type,
302                           internal_strlen(mem_type));
303 
304   // TODO(mcgrathr): Maybe allocate a VMAR for all sanitizer heap and use that?
305 
306   // Map a larger size to get a chunk of address space big enough that
307   // it surely contains an aligned region of the requested size.  Then
308   // overwrite the aligned middle portion with a mapping from the
309   // beginning of the VMO, and unmap the excess before and after.
310   size_t map_size = size + alignment;
311   uintptr_t addr;
312   status =
313       _zx_vmar_map(_zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0,
314                    vmo, 0, map_size, &addr);
315   if (status == ZX_OK) {
316     uintptr_t map_addr = addr;
317     uintptr_t map_end = map_addr + map_size;
318     addr = RoundUpTo(map_addr, alignment);
319     uintptr_t end = addr + size;
320     if (addr != map_addr) {
321       zx_info_vmar_t info;
322       status = _zx_object_get_info(_zx_vmar_root_self(), ZX_INFO_VMAR, &info,
323                                    sizeof(info), NULL, NULL);
324       if (status == ZX_OK) {
325         uintptr_t new_addr;
326         status = _zx_vmar_map(
327             _zx_vmar_root_self(),
328             ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_SPECIFIC_OVERWRITE,
329             addr - info.base, vmo, 0, size, &new_addr);
330         if (status == ZX_OK)
331           CHECK_EQ(new_addr, addr);
332       }
333     }
334     if (status == ZX_OK && addr != map_addr)
335       status = _zx_vmar_unmap(_zx_vmar_root_self(), map_addr, addr - map_addr);
336     if (status == ZX_OK && end != map_end)
337       status = _zx_vmar_unmap(_zx_vmar_root_self(), end, map_end - end);
338   }
339   _zx_handle_close(vmo);
340 
341   if (status != ZX_OK) {
342     if (status != ZX_ERR_NO_MEMORY)
343       ReportMmapFailureAndDie(size, mem_type, "zx_vmar_map", status, false);
344     return nullptr;
345   }
346 
347   IncreaseTotalMmap(size);
348 
349   return reinterpret_cast<void *>(addr);
350 }
351 
352 void UnmapOrDie(void *addr, uptr size) {
353   UnmapOrDieVmar(addr, size, _zx_vmar_root_self());
354 }
355 
356 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
357   uptr beg_aligned = RoundUpTo(beg, GetPageSize());
358   uptr end_aligned = RoundDownTo(end, GetPageSize());
359   if (beg_aligned < end_aligned) {
360     zx_handle_t root_vmar = _zx_vmar_root_self();
361     CHECK_NE(root_vmar, ZX_HANDLE_INVALID);
362     zx_status_t status =
363         _zx_vmar_op_range(root_vmar, ZX_VMAR_OP_DECOMMIT, beg_aligned,
364                           end_aligned - beg_aligned, nullptr, 0);
365     CHECK_EQ(status, ZX_OK);
366   }
367 }
368 
369 void DumpProcessMap() {
370   // TODO(mcgrathr): write it
371   return;
372 }
373 
374 bool IsAccessibleMemoryRange(uptr beg, uptr size) {
375   // TODO(mcgrathr): Figure out a better way.
376   zx_handle_t vmo;
377   zx_status_t status = _zx_vmo_create(size, 0, &vmo);
378   if (status == ZX_OK) {
379     status = _zx_vmo_write(vmo, reinterpret_cast<const void *>(beg), 0, size);
380     _zx_handle_close(vmo);
381   }
382   return status == ZX_OK;
383 }
384 
385 // FIXME implement on this platform.
386 void GetMemoryProfile(fill_profile_f cb, uptr *stats) {}
387 
388 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
389                       uptr *read_len, uptr max_len, error_t *errno_p) {
390   *errno_p = ZX_ERR_NOT_SUPPORTED;
391   return false;
392 }
393 
394 void RawWrite(const char *buffer) {
395   constexpr size_t size = 128;
396   static _Thread_local char line[size];
397   static _Thread_local size_t lastLineEnd = 0;
398   static _Thread_local size_t cur = 0;
399 
400   while (*buffer) {
401     if (cur >= size) {
402       if (lastLineEnd == 0)
403         lastLineEnd = size;
404       __sanitizer_log_write(line, lastLineEnd);
405       internal_memmove(line, line + lastLineEnd, cur - lastLineEnd);
406       cur = cur - lastLineEnd;
407       lastLineEnd = 0;
408     }
409     if (*buffer == '\n')
410       lastLineEnd = cur + 1;
411     line[cur++] = *buffer++;
412   }
413   // Flush all complete lines before returning.
414   if (lastLineEnd != 0) {
415     __sanitizer_log_write(line, lastLineEnd);
416     internal_memmove(line, line + lastLineEnd, cur - lastLineEnd);
417     cur = cur - lastLineEnd;
418     lastLineEnd = 0;
419   }
420 }
421 
422 void CatastrophicErrorWrite(const char *buffer, uptr length) {
423   __sanitizer_log_write(buffer, length);
424 }
425 
426 char **StoredArgv;
427 char **StoredEnviron;
428 
429 char **GetArgv() { return StoredArgv; }
430 char **GetEnviron() { return StoredEnviron; }
431 
432 const char *GetEnv(const char *name) {
433   if (StoredEnviron) {
434     uptr NameLen = internal_strlen(name);
435     for (char **Env = StoredEnviron; *Env != 0; Env++) {
436       if (internal_strncmp(*Env, name, NameLen) == 0 && (*Env)[NameLen] == '=')
437         return (*Env) + NameLen + 1;
438     }
439   }
440   return nullptr;
441 }
442 
443 uptr ReadBinaryName(/*out*/ char *buf, uptr buf_len) {
444   const char *argv0 = "<UNKNOWN>";
445   if (StoredArgv && StoredArgv[0]) {
446     argv0 = StoredArgv[0];
447   }
448   internal_strncpy(buf, argv0, buf_len);
449   return internal_strlen(buf);
450 }
451 
452 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
453   return ReadBinaryName(buf, buf_len);
454 }
455 
456 uptr MainThreadStackBase, MainThreadStackSize;
457 
458 bool GetRandom(void *buffer, uptr length, bool blocking) {
459   CHECK_LE(length, ZX_CPRNG_DRAW_MAX_LEN);
460   _zx_cprng_draw(buffer, length);
461   return true;
462 }
463 
464 u32 GetNumberOfCPUs() { return zx_system_get_num_cpus(); }
465 
466 uptr GetRSS() { UNIMPLEMENTED(); }
467 
468 void *internal_start_thread(void *(*func)(void *arg), void *arg) { return 0; }
469 void internal_join_thread(void *th) {}
470 
471 void InitializePlatformCommonFlags(CommonFlags *cf) {}
472 
473 }  // namespace __sanitizer
474 
475 using namespace __sanitizer;
476 
477 extern "C" {
478 void __sanitizer_startup_hook(int argc, char **argv, char **envp,
479                               void *stack_base, size_t stack_size) {
480   __sanitizer::StoredArgv = argv;
481   __sanitizer::StoredEnviron = envp;
482   __sanitizer::MainThreadStackBase = reinterpret_cast<uintptr_t>(stack_base);
483   __sanitizer::MainThreadStackSize = stack_size;
484 }
485 
486 void __sanitizer_set_report_path(const char *path) {
487   // Handle the initialization code in each sanitizer, but no other calls.
488   // This setting is never consulted on Fuchsia.
489   DCHECK_EQ(path, common_flags()->log_path);
490 }
491 
492 void __sanitizer_set_report_fd(void *fd) {
493   UNREACHABLE("not available on Fuchsia");
494 }
495 
496 const char *__sanitizer_get_report_path() {
497   UNREACHABLE("not available on Fuchsia");
498 }
499 }  // extern "C"
500 
501 #endif  // SANITIZER_FUCHSIA
502