1 //=== FuzzerExtWindows.cpp - Interface to external functions --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // Implementation of FuzzerExtFunctions for Windows. Uses alternatename when
10 // compiled with MSVC. Uses weak aliases when compiled with clang. Unfortunately
11 // the method each compiler supports is not supported by the other.
12 //===----------------------------------------------------------------------===//
13 #include "FuzzerDefs.h"
14 #if LIBFUZZER_WINDOWS
15
16 #include "FuzzerExtFunctions.h"
17 #include "FuzzerIO.h"
18
19 using namespace fuzzer;
20
21 // Intermediate macro to ensure the parameter is expanded before stringified.
22 #define STRINGIFY_(A) #A
23 #define STRINGIFY(A) STRINGIFY_(A)
24
25 #if LIBFUZZER_MSVC
26 // Copied from compiler-rt/lib/sanitizer_common/sanitizer_win_defs.h
27 #if defined(_M_IX86) || defined(__i386__)
28 #define WIN_SYM_PREFIX "_"
29 #else
30 #define WIN_SYM_PREFIX
31 #endif
32
33 // Declare external functions as having alternativenames, so that we can
34 // determine if they are not defined.
35 #define EXTERNAL_FUNC(Name, Default) \
36 __pragma(comment(linker, "/alternatename:" WIN_SYM_PREFIX STRINGIFY( \
37 Name) "=" WIN_SYM_PREFIX STRINGIFY(Default)))
38 #else
39 // Declare external functions as weak to allow them to default to a specified
40 // function if not defined explicitly. We must use weak symbols because clang's
41 // support for alternatename is not 100%, see
42 // https://bugs.llvm.org/show_bug.cgi?id=40218 for more details.
43 #define EXTERNAL_FUNC(Name, Default) \
44 __attribute__((weak, alias(STRINGIFY(Default))))
45 #endif // LIBFUZZER_MSVC
46
47 extern "C" {
48 #define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
49 RETURN_TYPE NAME##Def FUNC_SIG { \
50 Printf("ERROR: Function \"%s\" not defined.\n", #NAME); \
51 exit(1); \
52 } \
53 EXTERNAL_FUNC(NAME, NAME##Def) RETURN_TYPE NAME FUNC_SIG;
54
55 #include "FuzzerExtFunctions.def"
56
57 #undef EXT_FUNC
58 }
59
60 template <typename T>
GetFnPtr(T * Fun,T * FunDef,const char * FnName,bool WarnIfMissing)61 static T *GetFnPtr(T *Fun, T *FunDef, const char *FnName, bool WarnIfMissing) {
62 if (Fun == FunDef) {
63 if (WarnIfMissing)
64 Printf("WARNING: Failed to find function \"%s\".\n", FnName);
65 return nullptr;
66 }
67 return Fun;
68 }
69
70 namespace fuzzer {
71
ExternalFunctions()72 ExternalFunctions::ExternalFunctions() {
73 #define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
74 this->NAME = GetFnPtr<decltype(::NAME)>(::NAME, ::NAME##Def, #NAME, WARN);
75
76 #include "FuzzerExtFunctions.def"
77
78 #undef EXT_FUNC
79 }
80
81 } // namespace fuzzer
82
83 #endif // LIBFUZZER_WINDOWS
84