• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
32 namespace panda::os::library_loader {
33 class LibraryHandle;
34 
35 Expected<LibraryHandle, Error> Load(std::string_view filename);
36 
37 Expected<void *, Error> ResolveSymbol(const LibraryHandle &handle, std::string_view name);
38 
39 void CloseHandle(void *handle);
40 
41 class LibraryHandle {
42 public:
LibraryHandle(void * handle)43     explicit LibraryHandle(void *handle) : handle_(handle) {}
44 
LibraryHandle(LibraryHandle && handle)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 
IsValid()58     bool IsValid() const
59     {
60         return handle_ != nullptr;
61     }
62 
GetNativeHandle()63     void *GetNativeHandle() const
64     {
65         return handle_;
66     }
67 
~LibraryHandle()68     ~LibraryHandle()
69     {
70         if (handle_ != nullptr) {
71             CloseHandle(handle_);
72         }
73     }
74 
75 private:
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