1 //===-- sanitizer_fuchsia.cpp ---------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
14 #include "sanitizer_fuchsia.h"
20 # include <zircon/errors.h>
21 # include <zircon/process.h>
22 # include <zircon/syscalls.h>
23 # include <zircon/utc.h>
25 # include "sanitizer_common.h"
26 # include "sanitizer_interface_internal.h"
27 # include "sanitizer_libc.h"
28 # include "sanitizer_mutex.h"
30 namespace __sanitizer
{
32 void NORETURN
internal__exit(int exitcode
) { _zx_process_exit(exitcode
); }
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?
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
);
46 zx_handle_t utc_clock
= _zx_utc_reference_get();
47 CHECK_NE(utc_clock
, ZX_HANDLE_INVALID
);
49 zx_status_t status
= _zx_clock_read(utc_clock
, &time
);
50 CHECK_EQ(status
, ZX_OK
);
54 u64
MonotonicNanoTime() { return _zx_clock_get_monotonic(); }
56 uptr
internal_getpid() {
57 zx_info_handle_basic_t info
;
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
);
67 int internal_dlinfo(void *handle
, int request
, void *p
) { UNIMPLEMENTED(); }
69 uptr
GetThreadSelf() { return reinterpret_cast<uptr
>(thrd_current()); }
71 tid_t
GetTid() { return GetThreadSelf(); }
73 void Abort() { abort(); }
75 int Atexit(void (*function
)(void)) { return atexit(function
); }
77 void GetThreadStackTopAndBottom(bool, uptr
*stack_top
, uptr
*stack_bottom
) {
79 CHECK_EQ(pthread_getattr_np(pthread_self(), &attr
), 0);
82 CHECK_EQ(pthread_attr_getstack(&attr
, &base
, &size
), 0);
83 CHECK_EQ(pthread_attr_destroy(&attr
), 0);
85 *stack_bottom
= reinterpret_cast<uptr
>(base
);
86 *stack_top
= *stack_bottom
+ size
;
89 void InitializePlatformEarly() {}
91 void CheckMPROTECT() {}
92 void PlatformPrepareForSandboxing(void *args
) {}
93 void DisableCoreDumperIfNecessary() {}
94 void InstallDeadlySignalHandlers(SignalHandlerType handler
) {}
95 void SetAlternateSignalStack() {}
96 void UnsetAlternateSignalStack() {}
99 bool SignalContext::IsStackOverflow() const { return false; }
100 void SignalContext::DumpAllRegisters(void *context
) { UNIMPLEMENTED(); }
101 const char *SignalContext::Describe() const { UNIMPLEMENTED(); }
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
);
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
);
115 uptr
GetPageSize() { return _zx_system_get_page_size(); }
117 uptr
GetMmapGranularity() { return _zx_system_get_page_size(); }
119 sanitizer_shadow_bounds_t ShadowBounds
;
121 void InitShadowBounds() { ShadowBounds
= __sanitizer_shadow_bounds(); }
123 uptr
GetMaxUserVirtualAddress() {
125 return ShadowBounds
.memory_limit
- 1;
128 uptr
GetMaxVirtualAddress() { return GetMaxUserVirtualAddress(); }
130 bool ErrorIsOOM(error_t err
) { return err
== ZX_ERR_NO_MEMORY
; }
132 static void *DoAnonymousMmapOrDie(uptr size
, const char *mem_type
,
133 bool raw_report
, bool die_for_nomem
) {
134 size
= RoundUpTo(size
, GetPageSize());
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
,
144 _zx_object_set_property(vmo
, ZX_PROP_NAME
, mem_type
,
145 internal_strlen(mem_type
));
147 // TODO(mcgrathr): Maybe allocate a VMAR for all sanitizer heap and use that?
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
);
154 if (status
!= ZX_OK
) {
155 if (status
!= ZX_ERR_NO_MEMORY
|| die_for_nomem
)
156 ReportMmapFailureAndDie(size
, mem_type
, "zx_vmar_map", status
,
161 IncreaseTotalMmap(size
);
163 return reinterpret_cast<void *>(addr
);
166 void *MmapOrDie(uptr size
, const char *mem_type
, bool raw_report
) {
167 return DoAnonymousMmapOrDie(size
, mem_type
, raw_report
, true);
170 void *MmapNoReserveOrDie(uptr size
, const char *mem_type
) {
171 return MmapOrDie(size
, mem_type
);
174 void *MmapOrDieOnFatalError(uptr size
, const char *mem_type
) {
175 return DoAnonymousMmapOrDie(size
, mem_type
, false, false);
178 uptr
ReservedAddressRange::Init(uptr init_size
, const char *name
,
180 init_size
= RoundUpTo(init_size
, GetPageSize());
181 DCHECK_EQ(os_handle_
, ZX_HANDLE_INVALID
);
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
);
189 ReportMmapFailureAndDie(init_size
, name
, "zx_vmar_allocate", status
);
190 base_
= reinterpret_cast<void *>(base
);
195 return reinterpret_cast<uptr
>(base_
);
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());
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
);
209 _zx_object_set_property(vmo
, ZX_PROP_NAME
, name
, internal_strlen(name
));
210 DCHECK_GE(base
+ size_
, map_size
+ offset
);
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
);
223 IncreaseTotalMmap(map_size
);
227 uptr
ReservedAddressRange::Map(uptr fixed_addr
, uptr map_size
,
229 return DoMmapFixedOrDie(os_handle_
, fixed_addr
, map_size
, base_
,
230 name
? name
: name_
, false);
233 uptr
ReservedAddressRange::MapOrDie(uptr fixed_addr
, uptr map_size
,
235 return DoMmapFixedOrDie(os_handle_
, fixed_addr
, map_size
, base_
,
236 name
? name
: name_
, true);
239 void UnmapOrDieVmar(void *addr
, uptr size
, zx_handle_t target_vmar
) {
242 size
= RoundUpTo(size
, GetPageSize());
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);
252 DecreaseTotalMmap(size
);
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_
)) {
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
);
268 CHECK_EQ(addr
+ size
, reinterpret_cast<uptr
>(base_
) + size_
);
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
);
275 // This should never be called.
276 void *MmapFixedNoAccess(uptr fixed_addr
, uptr size
, const char *name
) {
280 bool MprotectNoAccess(uptr addr
, uptr size
) {
281 return _zx_vmar_protect(_zx_vmar_root_self(), 0, addr
, size
) == ZX_OK
;
284 bool MprotectReadOnly(uptr addr
, uptr size
) {
285 return _zx_vmar_protect(_zx_vmar_root_self(), ZX_VM_PERM_READ
, addr
, size
) ==
289 bool MprotectReadWrite(uptr addr
, uptr size
) {
290 return _zx_vmar_protect(_zx_vmar_root_self(),
291 ZX_VM_PERM_READ
| ZX_VM_PERM_WRITE
, addr
,
295 void *MmapAlignedOrDieOnFatalError(uptr size
, uptr alignment
,
296 const char *mem_type
) {
297 CHECK_GE(size
, GetPageSize());
298 CHECK(IsPowerOfTwo(size
));
299 CHECK(IsPowerOfTwo(alignment
));
302 zx_status_t status
= _zx_vmo_create(size
, 0, &vmo
);
303 if (status
!= ZX_OK
) {
304 if (status
!= ZX_ERR_NO_MEMORY
)
305 ReportMmapFailureAndDie(size
, mem_type
, "zx_vmo_create", status
, false);
308 _zx_object_set_property(vmo
, ZX_PROP_NAME
, mem_type
,
309 internal_strlen(mem_type
));
311 // TODO(mcgrathr): Maybe allocate a VMAR for all sanitizer heap and use that?
313 // Map a larger size to get a chunk of address space big enough that
314 // it surely contains an aligned region of the requested size. Then
315 // overwrite the aligned middle portion with a mapping from the
316 // beginning of the VMO, and unmap the excess before and after.
317 size_t map_size
= size
+ alignment
;
320 _zx_vmar_map(_zx_vmar_root_self(), ZX_VM_PERM_READ
| ZX_VM_PERM_WRITE
, 0,
321 vmo
, 0, map_size
, &addr
);
322 if (status
== ZX_OK
) {
323 uintptr_t map_addr
= addr
;
324 uintptr_t map_end
= map_addr
+ map_size
;
325 addr
= RoundUpTo(map_addr
, alignment
);
326 uintptr_t end
= addr
+ size
;
327 if (addr
!= map_addr
) {
329 status
= _zx_object_get_info(_zx_vmar_root_self(), ZX_INFO_VMAR
, &info
,
330 sizeof(info
), NULL
, NULL
);
331 if (status
== ZX_OK
) {
333 status
= _zx_vmar_map(
334 _zx_vmar_root_self(),
335 ZX_VM_PERM_READ
| ZX_VM_PERM_WRITE
| ZX_VM_SPECIFIC_OVERWRITE
,
336 addr
- info
.base
, vmo
, 0, size
, &new_addr
);
338 CHECK_EQ(new_addr
, addr
);
341 if (status
== ZX_OK
&& addr
!= map_addr
)
342 status
= _zx_vmar_unmap(_zx_vmar_root_self(), map_addr
, addr
- map_addr
);
343 if (status
== ZX_OK
&& end
!= map_end
)
344 status
= _zx_vmar_unmap(_zx_vmar_root_self(), end
, map_end
- end
);
346 _zx_handle_close(vmo
);
348 if (status
!= ZX_OK
) {
349 if (status
!= ZX_ERR_NO_MEMORY
)
350 ReportMmapFailureAndDie(size
, mem_type
, "zx_vmar_map", status
, false);
354 IncreaseTotalMmap(size
);
356 return reinterpret_cast<void *>(addr
);
359 void UnmapOrDie(void *addr
, uptr size
) {
360 UnmapOrDieVmar(addr
, size
, _zx_vmar_root_self());
363 void ReleaseMemoryPagesToOS(uptr beg
, uptr end
) {
364 uptr beg_aligned
= RoundUpTo(beg
, GetPageSize());
365 uptr end_aligned
= RoundDownTo(end
, GetPageSize());
366 if (beg_aligned
< end_aligned
) {
367 zx_handle_t root_vmar
= _zx_vmar_root_self();
368 CHECK_NE(root_vmar
, ZX_HANDLE_INVALID
);
370 _zx_vmar_op_range(root_vmar
, ZX_VMAR_OP_DECOMMIT
, beg_aligned
,
371 end_aligned
- beg_aligned
, nullptr, 0);
372 CHECK_EQ(status
, ZX_OK
);
376 void DumpProcessMap() {
377 // TODO(mcgrathr): write it
381 bool IsAccessibleMemoryRange(uptr beg
, uptr size
) {
382 // TODO(mcgrathr): Figure out a better way.
384 zx_status_t status
= _zx_vmo_create(size
, 0, &vmo
);
385 if (status
== ZX_OK
) {
386 status
= _zx_vmo_write(vmo
, reinterpret_cast<const void *>(beg
), 0, size
);
387 _zx_handle_close(vmo
);
389 return status
== ZX_OK
;
392 // FIXME implement on this platform.
393 void GetMemoryProfile(fill_profile_f cb
, uptr
*stats
) {}
395 bool ReadFileToBuffer(const char *file_name
, char **buff
, uptr
*buff_size
,
396 uptr
*read_len
, uptr max_len
, error_t
*errno_p
) {
397 *errno_p
= ZX_ERR_NOT_SUPPORTED
;
401 void RawWrite(const char *buffer
) {
402 constexpr size_t size
= 128;
403 static _Thread_local
char line
[size
];
404 static _Thread_local
size_t lastLineEnd
= 0;
405 static _Thread_local
size_t cur
= 0;
409 if (lastLineEnd
== 0)
411 __sanitizer_log_write(line
, lastLineEnd
);
412 internal_memmove(line
, line
+ lastLineEnd
, cur
- lastLineEnd
);
413 cur
= cur
- lastLineEnd
;
417 lastLineEnd
= cur
+ 1;
418 line
[cur
++] = *buffer
++;
420 // Flush all complete lines before returning.
421 if (lastLineEnd
!= 0) {
422 __sanitizer_log_write(line
, lastLineEnd
);
423 internal_memmove(line
, line
+ lastLineEnd
, cur
- lastLineEnd
);
424 cur
= cur
- lastLineEnd
;
429 void CatastrophicErrorWrite(const char *buffer
, uptr length
) {
430 __sanitizer_log_write(buffer
, length
);
434 char **StoredEnviron
;
436 char **GetArgv() { return StoredArgv
; }
437 char **GetEnviron() { return StoredEnviron
; }
439 const char *GetEnv(const char *name
) {
441 uptr NameLen
= internal_strlen(name
);
442 for (char **Env
= StoredEnviron
; *Env
!= 0; Env
++) {
443 if (internal_strncmp(*Env
, name
, NameLen
) == 0 && (*Env
)[NameLen
] == '=')
444 return (*Env
) + NameLen
+ 1;
450 uptr
ReadBinaryName(/*out*/ char *buf
, uptr buf_len
) {
451 const char *argv0
= "<UNKNOWN>";
452 if (StoredArgv
&& StoredArgv
[0]) {
453 argv0
= StoredArgv
[0];
455 internal_strncpy(buf
, argv0
, buf_len
);
456 return internal_strlen(buf
);
459 uptr
ReadLongProcessName(/*out*/ char *buf
, uptr buf_len
) {
460 return ReadBinaryName(buf
, buf_len
);
463 uptr MainThreadStackBase
, MainThreadStackSize
;
465 bool GetRandom(void *buffer
, uptr length
, bool blocking
) {
466 CHECK_LE(length
, ZX_CPRNG_DRAW_MAX_LEN
);
467 _zx_cprng_draw(buffer
, length
);
471 u32
GetNumberOfCPUs() { return zx_system_get_num_cpus(); }
473 uptr
GetRSS() { UNIMPLEMENTED(); }
475 void *internal_start_thread(void *(*func
)(void *arg
), void *arg
) { return 0; }
476 void internal_join_thread(void *th
) {}
478 void InitializePlatformCommonFlags(CommonFlags
*cf
) {}
480 } // namespace __sanitizer
482 using namespace __sanitizer
;
485 void __sanitizer_startup_hook(int argc
, char **argv
, char **envp
,
486 void *stack_base
, size_t stack_size
) {
487 __sanitizer::StoredArgv
= argv
;
488 __sanitizer::StoredEnviron
= envp
;
489 __sanitizer::MainThreadStackBase
= reinterpret_cast<uintptr_t>(stack_base
);
490 __sanitizer::MainThreadStackSize
= stack_size
;
493 void __sanitizer_set_report_path(const char *path
) {
494 // Handle the initialization code in each sanitizer, but no other calls.
495 // This setting is never consulted on Fuchsia.
496 DCHECK_EQ(path
, common_flags()->log_path
);
499 void __sanitizer_set_report_fd(void *fd
) {
500 UNREACHABLE("not available on Fuchsia");
503 const char *__sanitizer_get_report_path() {
504 UNREACHABLE("not available on Fuchsia");
508 #endif // SANITIZER_FUCHSIA