13cab2bb3Spatrick //===- FuzzerExtFunctionsDlsym.cpp - Interface to external functions ------===//
23cab2bb3Spatrick //
33cab2bb3Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
43cab2bb3Spatrick // See https://llvm.org/LICENSE.txt for license information.
53cab2bb3Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63cab2bb3Spatrick //
73cab2bb3Spatrick //===----------------------------------------------------------------------===//
83cab2bb3Spatrick // Implementation for operating systems that support dlsym(). We only use it on
93cab2bb3Spatrick // Apple platforms for now. We don't use this approach on Linux because it
103cab2bb3Spatrick // requires that clients of LibFuzzer pass ``--export-dynamic`` to the linker.
113cab2bb3Spatrick // That is a complication we don't wish to expose to clients right now.
123cab2bb3Spatrick //===----------------------------------------------------------------------===//
13*1f9cb04fSpatrick #include "FuzzerPlatform.h"
143cab2bb3Spatrick #if LIBFUZZER_APPLE
153cab2bb3Spatrick
163cab2bb3Spatrick #include "FuzzerExtFunctions.h"
173cab2bb3Spatrick #include "FuzzerIO.h"
183cab2bb3Spatrick #include <dlfcn.h>
193cab2bb3Spatrick
203cab2bb3Spatrick using namespace fuzzer;
213cab2bb3Spatrick
223cab2bb3Spatrick template <typename T>
GetFnPtr(const char * FnName,bool WarnIfMissing)233cab2bb3Spatrick static T GetFnPtr(const char *FnName, bool WarnIfMissing) {
243cab2bb3Spatrick dlerror(); // Clear any previous errors.
253cab2bb3Spatrick void *Fn = dlsym(RTLD_DEFAULT, FnName);
263cab2bb3Spatrick if (Fn == nullptr) {
273cab2bb3Spatrick if (WarnIfMissing) {
283cab2bb3Spatrick const char *ErrorMsg = dlerror();
293cab2bb3Spatrick Printf("WARNING: Failed to find function \"%s\".", FnName);
303cab2bb3Spatrick if (ErrorMsg)
313cab2bb3Spatrick Printf(" Reason %s.", ErrorMsg);
323cab2bb3Spatrick Printf("\n");
333cab2bb3Spatrick }
343cab2bb3Spatrick }
353cab2bb3Spatrick return reinterpret_cast<T>(Fn);
363cab2bb3Spatrick }
373cab2bb3Spatrick
383cab2bb3Spatrick namespace fuzzer {
393cab2bb3Spatrick
ExternalFunctions()403cab2bb3Spatrick ExternalFunctions::ExternalFunctions() {
413cab2bb3Spatrick #define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
423cab2bb3Spatrick this->NAME = GetFnPtr<decltype(ExternalFunctions::NAME)>(#NAME, WARN)
433cab2bb3Spatrick
443cab2bb3Spatrick #include "FuzzerExtFunctions.def"
453cab2bb3Spatrick
463cab2bb3Spatrick #undef EXT_FUNC
473cab2bb3Spatrick }
483cab2bb3Spatrick
493cab2bb3Spatrick } // namespace fuzzer
503cab2bb3Spatrick
513cab2bb3Spatrick #endif // LIBFUZZER_APPLE
52