Path: blob/main/contrib/llvm-project/compiler-rt/lib/interception/interception.h
35262 views
//===-- interception.h ------------------------------------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//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//===----------------------------------------------------------------------===//1213#ifndef INTERCEPTION_H14#define INTERCEPTION_H1516#include "sanitizer_common/sanitizer_asm.h"17#include "sanitizer_common/sanitizer_internal_defs.h"1819#if !SANITIZER_LINUX && !SANITIZER_FREEBSD && !SANITIZER_APPLE && \20!SANITIZER_NETBSD && !SANITIZER_WINDOWS && !SANITIZER_FUCHSIA && \21!SANITIZER_SOLARIS22# error "Interception doesn't work on this operating system."23#endif2425// These typedefs should be used only in the interceptor definitions to replace26// the standard system types (e.g. SSIZE_T instead of ssize_t)27typedef __sanitizer::uptr SIZE_T;28typedef __sanitizer::sptr SSIZE_T;29typedef __sanitizer::sptr PTRDIFF_T;30typedef __sanitizer::s64 INTMAX_T;31typedef __sanitizer::u64 UINTMAX_T;32typedef __sanitizer::OFF_T OFF_T;33typedef __sanitizer::OFF64_T OFF64_T;3435// How to add an interceptor:36// Suppose you need to wrap/replace system function (generally, from libc):37// int foo(const char *bar, double baz);38// You'll need to:39// 1) define INTERCEPTOR(int, foo, const char *bar, double baz) { ... } in40// your source file. See the notes below for cases when41// INTERCEPTOR_WITH_SUFFIX(...) should be used instead.42// 2) Call "INTERCEPT_FUNCTION(foo)" prior to the first call of "foo".43// INTERCEPT_FUNCTION(foo) evaluates to "true" iff the function was44// intercepted successfully.45// You can access original function by calling REAL(foo)(bar, baz).46// By default, REAL(foo) will be visible only inside your interceptor, and if47// you want to use it in other parts of RTL, you'll need to:48// 3a) add DECLARE_REAL(int, foo, const char*, double) to a49// header file.50// However, if the call "INTERCEPT_FUNCTION(foo)" and definition for51// INTERCEPTOR(..., foo, ...) are in different files, you'll instead need to:52// 3b) add DECLARE_REAL_AND_INTERCEPTOR(int, foo, const char*, double)53// to a header file.5455// Notes: 1. Things may not work properly if macro INTERCEPTOR(...) {...} or56// DECLARE_REAL(...) are located inside namespaces.57// 2. On Mac you can also use: "OVERRIDE_FUNCTION(foo, zoo)" to58// effectively redirect calls from "foo" to "zoo". In this case59// you aren't required to implement60// INTERCEPTOR(int, foo, const char *bar, double baz) {...}61// but instead you'll have to add62// DECLARE_REAL(int, foo, const char *bar, double baz) in your63// source file (to define a pointer to overriden function).64// 3. Some Mac functions have symbol variants discriminated by65// additional suffixes, e.g. _$UNIX2003 (see66// https://developer.apple.com/library/mac/#releasenotes/Darwin/SymbolVariantsRelNotes/index.html67// for more details). To intercept such functions you need to use the68// INTERCEPTOR_WITH_SUFFIX(...) macro.6970// How it works on Linux71// ---------------------72//73// To replace system functions on Linux we just need to declare functions with74// the same names in our library and then obtain the real function pointers75// using dlsym().76//77// There is one complication: a user may also intercept some of the functions we78// intercept. To allow for up to 3 interceptors (including ours) of a given79// function "func", the interceptor implementation is in ___interceptor_func,80// which is aliased by a weak function __interceptor_func, which in turn is81// aliased (via a trampoline) by weak wrapper function "func".82//83// Most user interceptors should define a foreign interceptor as follows:84//85// - provide a non-weak function "func" that performs interception;86// - if __interceptor_func exists, call it to perform the real functionality;87// - if it does not exist, figure out the real function and call it instead.88//89// In rare cases, a foreign interceptor (of another dynamic analysis runtime)90// may be defined as follows (on supported architectures):91//92// - provide a non-weak function __interceptor_func that performs interception;93// - if ___interceptor_func exists, call it to perform the real functionality;94// - if it does not exist, figure out the real function and call it instead;95// - provide a weak function "func" that is an alias to __interceptor_func.96//97// With this protocol, sanitizer interceptors, foreign user interceptors, and98// foreign interceptors of other dynamic analysis runtimes, or any combination99// thereof, may co-exist simultaneously.100//101// How it works on Mac OS102// ----------------------103//104// This is not so on Mac OS, where the two-level namespace makes our replacement105// functions invisible to other libraries. This may be overcomed using the106// DYLD_FORCE_FLAT_NAMESPACE, but some errors loading the shared libraries in107// Chromium were noticed when doing so.108//109// Instead we create a dylib containing a __DATA,__interpose section that110// associates library functions with their wrappers. When this dylib is111// preloaded before an executable using DYLD_INSERT_LIBRARIES, it routes all the112// calls to interposed functions done through stubs to the wrapper functions.113//114// As it's decided at compile time which functions are to be intercepted on Mac,115// INTERCEPT_FUNCTION() is effectively a no-op on this system.116117#if SANITIZER_APPLE118#include <sys/cdefs.h> // For __DARWIN_ALIAS_C().119120// Just a pair of pointers.121struct interpose_substitution {122const __sanitizer::uptr replacement;123const __sanitizer::uptr original;124};125126// For a function foo() create a global pair of pointers { wrap_foo, foo } in127// the __DATA,__interpose section.128// As a result all the calls to foo() will be routed to wrap_foo() at runtime.129#define INTERPOSER(func_name) __attribute__((used)) \130const interpose_substitution substitution_##func_name[] \131__attribute__((section("__DATA, __interpose"))) = { \132{ reinterpret_cast<const uptr>(WRAP(func_name)), \133reinterpret_cast<const uptr>(func_name) } \134}135136// For a function foo() and a wrapper function bar() create a global pair137// of pointers { bar, foo } in the __DATA,__interpose section.138// As a result all the calls to foo() will be routed to bar() at runtime.139#define INTERPOSER_2(func_name, wrapper_name) __attribute__((used)) \140const interpose_substitution substitution_##func_name[] \141__attribute__((section("__DATA, __interpose"))) = { \142{ reinterpret_cast<const uptr>(wrapper_name), \143reinterpret_cast<const uptr>(func_name) } \144}145146# define WRAP(x) wrap_##x147# define TRAMPOLINE(x) WRAP(x)148# define INTERCEPTOR_ATTRIBUTE149# define DECLARE_WRAPPER(ret_type, func, ...)150151#elif SANITIZER_WINDOWS152# define WRAP(x) __asan_wrap_##x153# define TRAMPOLINE(x) WRAP(x)154# define INTERCEPTOR_ATTRIBUTE __declspec(dllexport)155# define DECLARE_WRAPPER(ret_type, func, ...) \156extern "C" ret_type func(__VA_ARGS__);157# define DECLARE_WRAPPER_WINAPI(ret_type, func, ...) \158extern "C" __declspec(dllimport) ret_type __stdcall func(__VA_ARGS__);159#elif !SANITIZER_FUCHSIA // LINUX, FREEBSD, NETBSD, SOLARIS160# define INTERCEPTOR_ATTRIBUTE __attribute__((visibility("default")))161# if ASM_INTERCEPTOR_TRAMPOLINE_SUPPORT162// Weak aliases of weak aliases do not work, therefore we need to set up a163// trampoline function. The function "func" is a weak alias to the trampoline164// (so that we may check if "func" was overridden), which calls the weak165// function __interceptor_func, which in turn aliases the actual interceptor166// implementation ___interceptor_func:167//168// [wrapper "func": weak] --(alias)--> [TRAMPOLINE(func)]169// |170// +--------(tail call)-------+171// |172// v173// [__interceptor_func: weak] --(alias)--> [WRAP(func)]174//175// We use inline assembly to define most of this, because not all compilers176// support functions with the "naked" attribute with every architecture.177# define WRAP(x) ___interceptor_ ## x178# define TRAMPOLINE(x) __interceptor_trampoline_ ## x179# if SANITIZER_FREEBSD || SANITIZER_NETBSD180// FreeBSD's dynamic linker (incompliantly) gives non-weak symbols higher181// priority than weak ones so weak aliases won't work for indirect calls182// in position-independent (-fPIC / -fPIE) mode.183# define __ASM_WEAK_WRAPPER(func) ".globl " #func "\n"184# else185# define __ASM_WEAK_WRAPPER(func) ".weak " #func "\n"186# endif // SANITIZER_FREEBSD || SANITIZER_NETBSD187# if defined(__arm__) || defined(__aarch64__)188# define ASM_TYPE_FUNCTION_STR "%function"189# else190# define ASM_TYPE_FUNCTION_STR "@function"191# endif192// Keep trampoline implementation in sync with sanitizer_common/sanitizer_asm.h193# define DECLARE_WRAPPER(ret_type, func, ...) \194extern "C" ret_type func(__VA_ARGS__); \195extern "C" ret_type TRAMPOLINE(func)(__VA_ARGS__); \196extern "C" ret_type __interceptor_##func(__VA_ARGS__) \197INTERCEPTOR_ATTRIBUTE __attribute__((weak)) ALIAS(WRAP(func)); \198asm( \199".text\n" \200__ASM_WEAK_WRAPPER(func) \201".set " #func ", " SANITIZER_STRINGIFY(TRAMPOLINE(func)) "\n" \202".globl " SANITIZER_STRINGIFY(TRAMPOLINE(func)) "\n" \203".type " SANITIZER_STRINGIFY(TRAMPOLINE(func)) ", " \204ASM_TYPE_FUNCTION_STR "\n" \205SANITIZER_STRINGIFY(TRAMPOLINE(func)) ":\n" \206C_ASM_STARTPROC "\n" \207C_ASM_TAIL_CALL(SANITIZER_STRINGIFY(TRAMPOLINE(func)), \208"__interceptor_" \209SANITIZER_STRINGIFY(ASM_PREEMPTIBLE_SYM(func))) "\n" \210C_ASM_ENDPROC "\n" \211".size " SANITIZER_STRINGIFY(TRAMPOLINE(func)) ", " \212".-" SANITIZER_STRINGIFY(TRAMPOLINE(func)) "\n" \213);214# else // ASM_INTERCEPTOR_TRAMPOLINE_SUPPORT215// Some architectures cannot implement efficient interceptor trampolines with216// just a plain jump due to complexities of resolving a preemptible symbol. In217// those cases, revert to just this scheme:218//219// [wrapper "func": weak] --(alias)--> [WRAP(func)]220//221# define WRAP(x) __interceptor_ ## x222# define TRAMPOLINE(x) WRAP(x)223# if SANITIZER_FREEBSD || SANITIZER_NETBSD224# define __ATTRIBUTE_WEAK_WRAPPER225# else226# define __ATTRIBUTE_WEAK_WRAPPER __attribute__((weak))227# endif // SANITIZER_FREEBSD || SANITIZER_NETBSD228# define DECLARE_WRAPPER(ret_type, func, ...) \229extern "C" ret_type func(__VA_ARGS__) \230INTERCEPTOR_ATTRIBUTE __ATTRIBUTE_WEAK_WRAPPER ALIAS(WRAP(func));231# endif // ASM_INTERCEPTOR_TRAMPOLINE_SUPPORT232#endif233234#if SANITIZER_FUCHSIA235// There is no general interception at all on Fuchsia.236// Sanitizer runtimes just define functions directly to preempt them,237// and have bespoke ways to access the underlying libc functions.238# include <zircon/sanitizer.h>239# define INTERCEPTOR_ATTRIBUTE __attribute__((visibility("default")))240# define REAL(x) __unsanitized_##x241# define DECLARE_REAL(ret_type, func, ...)242#elif !SANITIZER_APPLE243# define PTR_TO_REAL(x) real_##x244# define REAL(x) __interception::PTR_TO_REAL(x)245# define FUNC_TYPE(x) x##_type246247# define DECLARE_REAL(ret_type, func, ...) \248typedef ret_type (*FUNC_TYPE(func))(__VA_ARGS__); \249namespace __interception { \250extern FUNC_TYPE(func) PTR_TO_REAL(func); \251}252# define ASSIGN_REAL(dst, src) REAL(dst) = REAL(src)253#else // SANITIZER_APPLE254# define REAL(x) x255# define DECLARE_REAL(ret_type, func, ...) \256extern "C" ret_type func(__VA_ARGS__);257# define ASSIGN_REAL(x, y)258#endif // SANITIZER_APPLE259260#if !SANITIZER_FUCHSIA261# define DECLARE_REAL_AND_INTERCEPTOR(ret_type, func, ...) \262DECLARE_REAL(ret_type, func, __VA_ARGS__) \263extern "C" ret_type TRAMPOLINE(func)(__VA_ARGS__); \264extern "C" ret_type WRAP(func)(__VA_ARGS__);265// Declare an interceptor and its wrapper defined in a different translation266// unit (ex. asm).267# define DECLARE_EXTERN_INTERCEPTOR_AND_WRAPPER(ret_type, func, ...) \268extern "C" ret_type TRAMPOLINE(func)(__VA_ARGS__); \269extern "C" ret_type WRAP(func)(__VA_ARGS__); \270extern "C" ret_type func(__VA_ARGS__);271#else272# define DECLARE_REAL_AND_INTERCEPTOR(ret_type, func, ...)273# define DECLARE_EXTERN_INTERCEPTOR_AND_WRAPPER(ret_type, func, ...)274#endif275276// Generally, you don't need to use DEFINE_REAL by itself, as INTERCEPTOR277// macros does its job. In exceptional cases you may need to call REAL(foo)278// without defining INTERCEPTOR(..., foo, ...). For example, if you override279// foo with an interceptor for other function.280#if !SANITIZER_APPLE && !SANITIZER_FUCHSIA281# define DEFINE_REAL(ret_type, func, ...) \282typedef ret_type (*FUNC_TYPE(func))(__VA_ARGS__); \283namespace __interception { \284FUNC_TYPE(func) PTR_TO_REAL(func); \285}286#else287# define DEFINE_REAL(ret_type, func, ...)288#endif289290#if SANITIZER_FUCHSIA291292// We need to define the __interceptor_func name just to get293// sanitizer_common/scripts/gen_dynamic_list.py to export func.294// But we don't need to export __interceptor_func to get that.295#define INTERCEPTOR(ret_type, func, ...) \296extern "C"[[ gnu::alias(#func), gnu::visibility("hidden") ]] ret_type \297__interceptor_##func(__VA_ARGS__); \298extern "C" INTERCEPTOR_ATTRIBUTE ret_type func(__VA_ARGS__)299300#elif !SANITIZER_APPLE301302#define INTERCEPTOR(ret_type, func, ...) \303DEFINE_REAL(ret_type, func, __VA_ARGS__) \304DECLARE_WRAPPER(ret_type, func, __VA_ARGS__) \305extern "C" INTERCEPTOR_ATTRIBUTE ret_type WRAP(func)(__VA_ARGS__)306307// We don't need INTERCEPTOR_WITH_SUFFIX on non-Darwin for now.308#define INTERCEPTOR_WITH_SUFFIX(ret_type, func, ...) \309INTERCEPTOR(ret_type, func, __VA_ARGS__)310311#else // SANITIZER_APPLE312313#define INTERCEPTOR_ZZZ(suffix, ret_type, func, ...) \314extern "C" ret_type func(__VA_ARGS__) suffix; \315extern "C" ret_type WRAP(func)(__VA_ARGS__); \316INTERPOSER(func); \317extern "C" INTERCEPTOR_ATTRIBUTE ret_type WRAP(func)(__VA_ARGS__)318319#define INTERCEPTOR(ret_type, func, ...) \320INTERCEPTOR_ZZZ(/*no symbol variants*/, ret_type, func, __VA_ARGS__)321322#define INTERCEPTOR_WITH_SUFFIX(ret_type, func, ...) \323INTERCEPTOR_ZZZ(__DARWIN_ALIAS_C(func), ret_type, func, __VA_ARGS__)324325// Override |overridee| with |overrider|.326#define OVERRIDE_FUNCTION(overridee, overrider) \327INTERPOSER_2(overridee, WRAP(overrider))328#endif329330#if SANITIZER_WINDOWS331# define INTERCEPTOR_WINAPI(ret_type, func, ...) \332typedef ret_type (__stdcall *FUNC_TYPE(func))(__VA_ARGS__); \333namespace __interception { \334FUNC_TYPE(func) PTR_TO_REAL(func); \335} \336extern "C" INTERCEPTOR_ATTRIBUTE ret_type __stdcall WRAP(func)(__VA_ARGS__)337#endif338339// ISO C++ forbids casting between pointer-to-function and pointer-to-object,340// so we use casting via an integral type __interception::uptr,341// assuming that system is POSIX-compliant. Using other hacks seem342// challenging, as we don't even pass function type to343// INTERCEPT_FUNCTION macro, only its name.344namespace __interception {345#if defined(_WIN64)346typedef unsigned long long uptr;347#else348typedef unsigned long uptr;349#endif // _WIN64350351#if defined(__ELF__) && !SANITIZER_FUCHSIA352// The use of interceptors makes many sanitizers unusable for static linking.353// Define a function, if called, will cause a linker error (undefined _DYNAMIC).354// However, -static-pie (which is not common) cannot be detected at link time.355extern uptr kDynamic[] asm("_DYNAMIC");356inline void DoesNotSupportStaticLinking() {357[[maybe_unused]] volatile auto x = &kDynamic;358}359#else360inline void DoesNotSupportStaticLinking() {}361#endif362} // namespace __interception363364#define INCLUDED_FROM_INTERCEPTION_LIB365366#if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD || \367SANITIZER_SOLARIS368369# include "interception_linux.h"370# define INTERCEPT_FUNCTION(func) INTERCEPT_FUNCTION_LINUX_OR_FREEBSD(func)371# define INTERCEPT_FUNCTION_VER(func, symver) \372INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver)373#elif SANITIZER_APPLE374# include "interception_mac.h"375# define INTERCEPT_FUNCTION(func) INTERCEPT_FUNCTION_MAC(func)376# define INTERCEPT_FUNCTION_VER(func, symver) \377INTERCEPT_FUNCTION_VER_MAC(func, symver)378#elif SANITIZER_WINDOWS379# include "interception_win.h"380# define INTERCEPT_FUNCTION(func) INTERCEPT_FUNCTION_WIN(func)381# define INTERCEPT_FUNCTION_VER(func, symver) \382INTERCEPT_FUNCTION_VER_WIN(func, symver)383#endif384385#undef INCLUDED_FROM_INTERCEPTION_LIB386387#endif // INTERCEPTION_H388389390