1//===-- sanitizer_dl.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 has helper functions that depend on libc's dynamic loading
10// introspection.
11//
12//===----------------------------------------------------------------------===//
13
14#include "sanitizer_dl.h"
15
16#include "sanitizer_common/sanitizer_platform.h"
17
18#if SANITIZER_GLIBC
19# include <dlfcn.h>
20#endif
21
22namespace __sanitizer {
23extern const char *SanitizerToolName;
24
25const char *DladdrSelfFName(void) {
26 // go-tsan can't link libdl before it was merged into glibc 2.34.
27#if SANITIZER_GLIBC && !SANITIZER_GO
28 Dl_info info;
29 int ret = dladdr(address: (void *)&SanitizerToolName, info: &info);
30 if (ret) {
31 return info.dli_fname;
32 }
33#endif
34
35 return nullptr;
36}
37
38char* DladdrElfHeaderBase(void* ld, char* addr) {
39 // go-tsan can't link libdl before it was merged into glibc 2.34.
40#if SANITIZER_GLIBC && !SANITIZER_GO
41 Dl_info info;
42 if (dladdr(address: ld, info: &info) && info.dli_fbase)
43 addr = (char*)info.dli_fbase;
44#endif // SANITIZER_GLIBC
45 return addr;
46}
47
48void ClearDlerror() {
49#if SANITIZER_GLIBC && !SANITIZER_GO
50 // Starting with glibc 2.34
51 // (https://sourceware.org/git/?p=glibc.git;h=fada9018199c), failed dlfcn
52 // calls store a per-thread error struct in TLS (__libc_dlerror_result)
53 // instead of a pthread_key_t, and free it in __libc_thread_freeres() after
54 // pthread TSD destructors have already unregistered the thread from the
55 // sanitizer. Clear dlerror() while the thread is still tracked so that LSan
56 // does not report the pending error buffer as a leak if a leak check runs
57 // before __libc_thread_freeres().
58 dlerror();
59 dlerror();
60#endif
61}
62
63} // namespace __sanitizer
64