1 //===- FuzzerExtFunctionsDlsym.cpp - Interface to external functions ------===//
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 // Implementation for operating systems that support dlsym(). We only use it on
9 // Apple platforms for now. We don't use this approach on Linux because it
10 // requires that clients of LibFuzzer pass ``--export-dynamic`` to the linker.
11 // That is a complication we don't wish to expose to clients right now.
12 //===----------------------------------------------------------------------===//
13 #include "FuzzerPlatform.h"
14 #if LIBFUZZER_APPLE
15 
16 #include "FuzzerExtFunctions.h"
17 #include "FuzzerIO.h"
18 #include <dlfcn.h>
19 
20 using namespace fuzzer;
21 
22 template <typename T>
GetFnPtr(const char * FnName,bool WarnIfMissing)23 static T GetFnPtr(const char *FnName, bool WarnIfMissing) {
24   dlerror(); // Clear any previous errors.
25   void *Fn = dlsym(RTLD_DEFAULT, FnName);
26   if (Fn == nullptr) {
27     if (WarnIfMissing) {
28       const char *ErrorMsg = dlerror();
29       Printf("WARNING: Failed to find function \"%s\".", FnName);
30       if (ErrorMsg)
31         Printf(" Reason %s.", ErrorMsg);
32       Printf("\n");
33     }
34   }
35   static_assert(sizeof(T) == sizeof(Fn), "Bad cast of dlsym() pointer");
36   return reinterpret_cast<T>(Fn);
37 }
38 
39 namespace fuzzer {
40 
ExternalFunctions()41 ExternalFunctions::ExternalFunctions() {
42 #define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN)                            \
43   this->NAME = GetFnPtr<decltype(ExternalFunctions::NAME)>(#NAME, WARN)
44 
45 #include "FuzzerExtFunctions.def"
46 
47 #undef EXT_FUNC
48 }
49 
50 } // namespace fuzzer
51 
52 #endif // LIBFUZZER_APPLE
53