1/** 2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16#ifndef LIBPANDABASE_OS_LIBRARY_LOADER_H 17#define LIBPANDABASE_OS_LIBRARY_LOADER_H 18 19#ifdef PANDA_TARGET_UNIX 20#include <dlfcn.h> 21#elif defined PANDA_TARGET_WINDOWS 22// No platform-specific includes 23#else 24#error "Unsupported platform" 25#endif 26 27#include "os/error.h" 28#include "utils/expected.h" 29 30#include <string_view> 31 32namespace panda::os::library_loader { 33class LibraryHandle; 34 35Expected<LibraryHandle, Error> Load(std::string_view filename); 36 37Expected<void *, Error> ResolveSymbol(const LibraryHandle &handle, std::string_view name); 38 39void CloseHandle(void *handle); 40 41class LibraryHandle { 42public: 43 explicit LibraryHandle(void *handle) : handle_(handle) {} 44 45 LibraryHandle(LibraryHandle &&handle) noexcept 46 { 47 handle_ = handle.handle_; 48 handle.handle_ = nullptr; 49 } 50 51 LibraryHandle &operator=(LibraryHandle &&handle) noexcept 52 { 53 handle_ = handle.handle_; 54 handle.handle_ = nullptr; 55 return *this; 56 } 57 58 bool IsValid() const 59 { 60 return handle_ != nullptr; 61 } 62 63 void *GetNativeHandle() const 64 { 65 return handle_; 66 } 67 68 ~LibraryHandle() 69 { 70 if (handle_ != nullptr) { 71 CloseHandle(handle_); 72 } 73 } 74 75private: 76 void *handle_; 77 78 NO_COPY_SEMANTIC(LibraryHandle); 79}; 80} // namespace panda::os::library_loader 81 82#endif // LIBPANDABASE_OS_LIBRARY_LOADER_H 83