1//===- FuzzerExtFunctionsDlsym.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 for operating systems that support dlsym(). We only use it on
10// Apple platforms for now. We don't use this approach on Linux because it
11// requires that clients of LibFuzzer pass ``--export-dynamic`` to the linker.
12// That is a complication we don't wish to expose to clients right now.
13//===----------------------------------------------------------------------===//
14#include "FuzzerDefs.h"
15#if LIBFUZZER_APPLE
16
17#include "FuzzerExtFunctions.h"
18#include "FuzzerIO.h"
19#include <dlfcn.h>
20
21using namespace fuzzer;
22
23template <typename T>
24static T GetFnPtr(const char *FnName, bool WarnIfMissing) {
25  dlerror(); // Clear any previous errors.
26  void *Fn = dlsym(RTLD_DEFAULT, FnName);
27  if (Fn == nullptr) {
28    if (WarnIfMissing) {
29      const char *ErrorMsg = dlerror();
30      Printf("WARNING: Failed to find function \"%s\".", FnName);
31      if (ErrorMsg)
32        Printf(" Reason %s.", ErrorMsg);
33      Printf("\n");
34    }
35  }
36  return reinterpret_cast<T>(Fn);
37}
38
39namespace fuzzer {
40
41ExternalFunctions::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