1 //===-- interception.h ------------------------------------------*- C++ -*-===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is a part of AddressSanitizer, an address sanity checker.
9 //
10 // Machinery for providing replacements/wrappers for system functions.
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef INTERCEPTION_H
14 #define INTERCEPTION_H
15 
16 #if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__APPLE__) && \
17     !defined(__NetBSD__) && !defined(_WIN32) && !defined(__Fuchsia__)
18 # error "Interception doesn't work on this operating system."
19 #endif
20 
21 #include "sanitizer_common/sanitizer_internal_defs.h"
22 
23 // These typedefs should be used only in the interceptor definitions to replace
24 // the standard system types (e.g. SSIZE_T instead of ssize_t)
25 typedef __sanitizer::uptr    SIZE_T;
26 typedef __sanitizer::sptr    SSIZE_T;
27 typedef __sanitizer::sptr    PTRDIFF_T;
28 typedef __sanitizer::s64     INTMAX_T;
29 typedef __sanitizer::OFF_T   OFF_T;
30 typedef __sanitizer::OFF64_T OFF64_T;
31 
32 // How to add an interceptor:
33 // Suppose you need to wrap/replace system function (generally, from libc):
34 //      int foo(const char *bar, double baz);
35 // You'll need to:
36 //      1) define INTERCEPTOR(int, foo, const char *bar, double baz) { ... } in
37 //         your source file. See the notes below for cases when
38 //         INTERCEPTOR_WITH_SUFFIX(...) should be used instead.
39 //      2) Call "INTERCEPT_FUNCTION(foo)" prior to the first call of "foo".
40 //         INTERCEPT_FUNCTION(foo) evaluates to "true" iff the function was
41 //         intercepted successfully.
42 // You can access original function by calling REAL(foo)(bar, baz).
43 // By default, REAL(foo) will be visible only inside your interceptor, and if
44 // you want to use it in other parts of RTL, you'll need to:
45 //      3a) add DECLARE_REAL(int, foo, const char*, double) to a
46 //          header file.
47 // However, if the call "INTERCEPT_FUNCTION(foo)" and definition for
48 // INTERCEPTOR(..., foo, ...) are in different files, you'll instead need to:
49 //      3b) add DECLARE_REAL_AND_INTERCEPTOR(int, foo, const char*, double)
50 //          to a header file.
51 
52 // Notes: 1. Things may not work properly if macro INTERCEPTOR(...) {...} or
53 //           DECLARE_REAL(...) are located inside namespaces.
54 //        2. On Mac you can also use: "OVERRIDE_FUNCTION(foo, zoo)" to
55 //           effectively redirect calls from "foo" to "zoo". In this case
56 //           you aren't required to implement
57 //           INTERCEPTOR(int, foo, const char *bar, double baz) {...}
58 //           but instead you'll have to add
59 //           DECLARE_REAL(int, foo, const char *bar, double baz) in your
60 //           source file (to define a pointer to overriden function).
61 //        3. Some Mac functions have symbol variants discriminated by
62 //           additional suffixes, e.g. _$UNIX2003 (see
63 //           https://developer.apple.com/library/mac/#releasenotes/Darwin/SymbolVariantsRelNotes/index.html
64 //           for more details). To intercept such functions you need to use the
65 //           INTERCEPTOR_WITH_SUFFIX(...) macro.
66 
67 // How it works:
68 // To replace system functions on Linux we just need to declare functions
69 // with same names in our library and then obtain the real function pointers
70 // using dlsym().
71 // There is one complication. A user may also intercept some of the functions
72 // we intercept. To resolve this we declare our interceptors with __interceptor_
73 // prefix, and then make actual interceptors weak aliases to __interceptor_
74 // functions.
75 //
76 // This is not so on Mac OS, where the two-level namespace makes
77 // our replacement functions invisible to other libraries. This may be overcomed
78 // using the DYLD_FORCE_FLAT_NAMESPACE, but some errors loading the shared
79 // libraries in Chromium were noticed when doing so.
80 // Instead we create a dylib containing a __DATA,__interpose section that
81 // associates library functions with their wrappers. When this dylib is
82 // preloaded before an executable using DYLD_INSERT_LIBRARIES, it routes all
83 // the calls to interposed functions done through stubs to the wrapper
84 // functions.
85 // As it's decided at compile time which functions are to be intercepted on Mac,
86 // INTERCEPT_FUNCTION() is effectively a no-op on this system.
87 
88 #if defined(__APPLE__)
89 #include <sys/cdefs.h>  // For __DARWIN_ALIAS_C().
90 
91 // Just a pair of pointers.
92 struct interpose_substitution {
93   const __sanitizer::uptr replacement;
94   const __sanitizer::uptr original;
95 };
96 
97 // For a function foo() create a global pair of pointers { wrap_foo, foo } in
98 // the __DATA,__interpose section.
99 // As a result all the calls to foo() will be routed to wrap_foo() at runtime.
100 #define INTERPOSER(func_name) __attribute__((used)) \
101 const interpose_substitution substitution_##func_name[] \
102     __attribute__((section("__DATA, __interpose"))) = { \
103     { reinterpret_cast<const uptr>(WRAP(func_name)), \
104       reinterpret_cast<const uptr>(func_name) } \
105 }
106 
107 // For a function foo() and a wrapper function bar() create a global pair
108 // of pointers { bar, foo } in the __DATA,__interpose section.
109 // As a result all the calls to foo() will be routed to bar() at runtime.
110 #define INTERPOSER_2(func_name, wrapper_name) __attribute__((used)) \
111 const interpose_substitution substitution_##func_name[] \
112     __attribute__((section("__DATA, __interpose"))) = { \
113     { reinterpret_cast<const uptr>(wrapper_name), \
114       reinterpret_cast<const uptr>(func_name) } \
115 }
116 
117 # define WRAP(x) wrap_##x
118 # define WRAPPER_NAME(x) "wrap_"#x
119 # define INTERCEPTOR_ATTRIBUTE
120 # define DECLARE_WRAPPER(ret_type, func, ...)
121 
122 #elif defined(_WIN32)
123 # define WRAP(x) __asan_wrap_##x
124 # define WRAPPER_NAME(x) "__asan_wrap_"#x
125 # define INTERCEPTOR_ATTRIBUTE __declspec(dllexport)
126 # define DECLARE_WRAPPER(ret_type, func, ...) \
127     extern "C" ret_type func(__VA_ARGS__);
128 # define DECLARE_WRAPPER_WINAPI(ret_type, func, ...) \
129     extern "C" __declspec(dllimport) ret_type __stdcall func(__VA_ARGS__);
130 #elif defined(__FreeBSD__) || defined(__NetBSD__)
131 # define WRAP(x) __interceptor_ ## x
132 # define WRAPPER_NAME(x) "__interceptor_" #x
133 # define INTERCEPTOR_ATTRIBUTE __attribute__((visibility("default")))
134 // FreeBSD's dynamic linker (incompliantly) gives non-weak symbols higher
135 // priority than weak ones so weak aliases won't work for indirect calls
136 // in position-independent (-fPIC / -fPIE) mode.
137 # define DECLARE_WRAPPER(ret_type, func, ...) \
138      extern "C" ret_type func(__VA_ARGS__) \
139      __attribute__((alias("__interceptor_" #func), visibility("default")));
140 #elif !defined(__Fuchsia__)
141 # define WRAP(x) __interceptor_ ## x
142 # define WRAPPER_NAME(x) "__interceptor_" #x
143 # define INTERCEPTOR_ATTRIBUTE __attribute__((visibility("default")))
144 # define DECLARE_WRAPPER(ret_type, func, ...) \
145     extern "C" ret_type func(__VA_ARGS__) \
146     __attribute__((weak, alias("__interceptor_" #func), visibility("default")));
147 #endif
148 
149 #if defined(__Fuchsia__)
150 // There is no general interception at all on Fuchsia.
151 // Sanitizer runtimes just define functions directly to preempt them,
152 // and have bespoke ways to access the underlying libc functions.
153 # include <zircon/sanitizer.h>
154 # define INTERCEPTOR_ATTRIBUTE __attribute__((visibility("default")))
155 # define REAL(x) __unsanitized_##x
156 # define DECLARE_REAL(ret_type, func, ...)
157 #elif !defined(__APPLE__)
158 # define PTR_TO_REAL(x) real_##x
159 # define REAL(x) __interception::PTR_TO_REAL(x)
160 # define FUNC_TYPE(x) x##_f
161 
162 # define DECLARE_REAL(ret_type, func, ...) \
163     typedef ret_type (*FUNC_TYPE(func))(__VA_ARGS__); \
164     namespace __interception { \
165       extern FUNC_TYPE(func) PTR_TO_REAL(func); \
166     }
167 # define ASSIGN_REAL(dst, src) REAL(dst) = REAL(src)
168 #else  // __APPLE__
169 # define REAL(x) x
170 # define DECLARE_REAL(ret_type, func, ...) \
171     extern "C" ret_type func(__VA_ARGS__);
172 # define ASSIGN_REAL(x, y)
173 #endif  // __APPLE__
174 
175 #if !defined(__Fuchsia__)
176 #define DECLARE_REAL_AND_INTERCEPTOR(ret_type, func, ...) \
177   DECLARE_REAL(ret_type, func, __VA_ARGS__) \
178   extern "C" ret_type WRAP(func)(__VA_ARGS__);
179 #else
180 #define DECLARE_REAL_AND_INTERCEPTOR(ret_type, func, ...)
181 #endif
182 
183 // Generally, you don't need to use DEFINE_REAL by itself, as INTERCEPTOR
184 // macros does its job. In exceptional cases you may need to call REAL(foo)
185 // without defining INTERCEPTOR(..., foo, ...). For example, if you override
186 // foo with an interceptor for other function.
187 #if !defined(__APPLE__) && !defined(__Fuchsia__)
188 # define DEFINE_REAL(ret_type, func, ...) \
189     typedef ret_type (*FUNC_TYPE(func))(__VA_ARGS__); \
190     namespace __interception { \
191       FUNC_TYPE(func) PTR_TO_REAL(func); \
192     }
193 #else
194 # define DEFINE_REAL(ret_type, func, ...)
195 #endif
196 
197 #if defined(__Fuchsia__)
198 
199 // We need to define the __interceptor_func name just to get
200 // sanitizer_common/scripts/gen_dynamic_list.py to export func.
201 // But we don't need to export __interceptor_func to get that.
202 #define INTERCEPTOR(ret_type, func, ...)                                \
203   extern "C"[[ gnu::alias(#func), gnu::visibility("hidden") ]] ret_type \
204       __interceptor_##func(__VA_ARGS__);                                \
205   extern "C" INTERCEPTOR_ATTRIBUTE ret_type func(__VA_ARGS__)
206 
207 #elif !defined(__APPLE__)
208 
209 #define INTERCEPTOR(ret_type, func, ...) \
210   DEFINE_REAL(ret_type, func, __VA_ARGS__) \
211   DECLARE_WRAPPER(ret_type, func, __VA_ARGS__) \
212   extern "C" \
213   INTERCEPTOR_ATTRIBUTE \
214   ret_type WRAP(func)(__VA_ARGS__)
215 
216 // We don't need INTERCEPTOR_WITH_SUFFIX on non-Darwin for now.
217 #define INTERCEPTOR_WITH_SUFFIX(ret_type, func, ...) \
218   INTERCEPTOR(ret_type, func, __VA_ARGS__)
219 
220 #else  // __APPLE__
221 
222 #define INTERCEPTOR_ZZZ(suffix, ret_type, func, ...) \
223   extern "C" ret_type func(__VA_ARGS__) suffix; \
224   extern "C" ret_type WRAP(func)(__VA_ARGS__); \
225   INTERPOSER(func); \
226   extern "C" INTERCEPTOR_ATTRIBUTE ret_type WRAP(func)(__VA_ARGS__)
227 
228 #define INTERCEPTOR(ret_type, func, ...) \
229   INTERCEPTOR_ZZZ(/*no symbol variants*/, ret_type, func, __VA_ARGS__)
230 
231 #define INTERCEPTOR_WITH_SUFFIX(ret_type, func, ...) \
232   INTERCEPTOR_ZZZ(__DARWIN_ALIAS_C(func), ret_type, func, __VA_ARGS__)
233 
234 // Override |overridee| with |overrider|.
235 #define OVERRIDE_FUNCTION(overridee, overrider) \
236   INTERPOSER_2(overridee, WRAP(overrider))
237 #endif
238 
239 #if defined(_WIN32)
240 # define INTERCEPTOR_WINAPI(ret_type, func, ...) \
241     typedef ret_type (__stdcall *FUNC_TYPE(func))(__VA_ARGS__); \
242     namespace __interception { \
243       FUNC_TYPE(func) PTR_TO_REAL(func); \
244     } \
245     extern "C" \
246     INTERCEPTOR_ATTRIBUTE \
247     ret_type __stdcall WRAP(func)(__VA_ARGS__)
248 #endif
249 
250 // ISO C++ forbids casting between pointer-to-function and pointer-to-object,
251 // so we use casting via an integral type __interception::uptr,
252 // assuming that system is POSIX-compliant. Using other hacks seem
253 // challenging, as we don't even pass function type to
254 // INTERCEPT_FUNCTION macro, only its name.
255 namespace __interception {
256 #if defined(_WIN64)
257 typedef unsigned long long uptr;  // NOLINT
258 #else
259 typedef unsigned long uptr;  // NOLINT
260 #endif  // _WIN64
261 }  // namespace __interception
262 
263 #define INCLUDED_FROM_INTERCEPTION_LIB
264 
265 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
266 # include "interception_linux.h"
267 # define INTERCEPT_FUNCTION(func) INTERCEPT_FUNCTION_LINUX_OR_FREEBSD(func)
268 # define INTERCEPT_FUNCTION_VER(func, symver) \
269     INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver)
270 #elif defined(__APPLE__)
271 # include "interception_mac.h"
272 # define INTERCEPT_FUNCTION(func) INTERCEPT_FUNCTION_MAC(func)
273 # define INTERCEPT_FUNCTION_VER(func, symver) \
274     INTERCEPT_FUNCTION_VER_MAC(func, symver)
275 #elif defined(_WIN32)
276 # include "interception_win.h"
277 # define INTERCEPT_FUNCTION(func) INTERCEPT_FUNCTION_WIN(func)
278 # define INTERCEPT_FUNCTION_VER(func, symver) \
279     INTERCEPT_FUNCTION_VER_WIN(func, symver)
280 #endif
281 
282 #undef INCLUDED_FROM_INTERCEPTION_LIB
283 
284 #endif  // INTERCEPTION_H
285