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