10b57cec5SDimitry Andric //===- FuzzerExtFunctionsDlsym.cpp - Interface to external functions ------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // Implementation for operating systems that support dlsym(). We only use it on 90b57cec5SDimitry Andric // Apple platforms for now. We don't use this approach on Linux because it 100b57cec5SDimitry Andric // requires that clients of LibFuzzer pass ``--export-dynamic`` to the linker. 110b57cec5SDimitry Andric // That is a complication we don't wish to expose to clients right now. 120b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 13*5ffd83dbSDimitry Andric #include "FuzzerPlatform.h" 140b57cec5SDimitry Andric #if LIBFUZZER_APPLE 150b57cec5SDimitry Andric 160b57cec5SDimitry Andric #include "FuzzerExtFunctions.h" 170b57cec5SDimitry Andric #include "FuzzerIO.h" 180b57cec5SDimitry Andric #include <dlfcn.h> 190b57cec5SDimitry Andric 200b57cec5SDimitry Andric using namespace fuzzer; 210b57cec5SDimitry Andric 220b57cec5SDimitry Andric template <typename T> 230b57cec5SDimitry Andric static T GetFnPtr(const char *FnName, bool WarnIfMissing) { 240b57cec5SDimitry Andric dlerror(); // Clear any previous errors. 250b57cec5SDimitry Andric void *Fn = dlsym(RTLD_DEFAULT, FnName); 260b57cec5SDimitry Andric if (Fn == nullptr) { 270b57cec5SDimitry Andric if (WarnIfMissing) { 280b57cec5SDimitry Andric const char *ErrorMsg = dlerror(); 290b57cec5SDimitry Andric Printf("WARNING: Failed to find function \"%s\".", FnName); 300b57cec5SDimitry Andric if (ErrorMsg) 310b57cec5SDimitry Andric Printf(" Reason %s.", ErrorMsg); 320b57cec5SDimitry Andric Printf("\n"); 330b57cec5SDimitry Andric } 340b57cec5SDimitry Andric } 350b57cec5SDimitry Andric return reinterpret_cast<T>(Fn); 360b57cec5SDimitry Andric } 370b57cec5SDimitry Andric 380b57cec5SDimitry Andric namespace fuzzer { 390b57cec5SDimitry Andric 400b57cec5SDimitry Andric ExternalFunctions::ExternalFunctions() { 410b57cec5SDimitry Andric #define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \ 420b57cec5SDimitry Andric this->NAME = GetFnPtr<decltype(ExternalFunctions::NAME)>(#NAME, WARN) 430b57cec5SDimitry Andric 440b57cec5SDimitry Andric #include "FuzzerExtFunctions.def" 450b57cec5SDimitry Andric 460b57cec5SDimitry Andric #undef EXT_FUNC 470b57cec5SDimitry Andric } 480b57cec5SDimitry Andric 490b57cec5SDimitry Andric } // namespace fuzzer 500b57cec5SDimitry Andric 510b57cec5SDimitry Andric #endif // LIBFUZZER_APPLE 52