All Classes Files Functions Enumerations Enumerator Pages
shim/utils.hpp
1 /*
2  * Copyright (c) 2021-2025, NVIDIA CORPORATION.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17 
18 #include <dlfcn.h>
19 #include <sys/utsname.h>
20 #include <string>
21 #include <vector>
22 
23 namespace kvikio {
24 
25 // Macros used for defining symbol visibility.
26 // Since KvikIO declares global default values in headers, we rely on the linker to disambiguate
27 // inline and static methods that have (or return) static references. To do this, the relevant
28 // function/method must have `__attribute__((visibility("default")))`. If not, then if KvikIO is
29 // used in two different DSOs, the function will appear twice, and there will be two static objects.
30 // See <https://gcc.gnu.org/wiki/Visibility> and <https://github.com/rapidsai/kvikio/issues/442>.
31 #if (defined(__GNUC__) || defined(__clang__)) && !defined(__MINGW32__) && !defined(__MINGW64__)
32 #define KVIKIO_EXPORT __attribute__((visibility("default")))
33 #define KVIKIO_HIDDEN __attribute__((visibility("hidden")))
34 #else
35 #define KVIKIO_EXPORT
36 #define KVIKIO_HIDDEN
37 #endif
38 
39 #define KVIKIO_STRINGIFY_DETAIL(x) #x
40 #define KVIKIO_STRINGIFY(x) KVIKIO_STRINGIFY_DETAIL(x)
41 
48 void* load_library(std::string const& name, int mode = RTLD_LAZY | RTLD_LOCAL | RTLD_NODELETE);
49 
56 void* load_library(std::vector<std::string> const& names,
57  int mode = RTLD_LAZY | RTLD_LOCAL | RTLD_NODELETE);
58 
67 template <typename T>
68 void get_symbol(T& handle, void* lib, std::string const& name)
69 {
70  ::dlerror(); // Clear old errors
71  // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
72  handle = reinterpret_cast<T>(::dlsym(lib, name.c_str()));
73  const char* err = ::dlerror();
74  if (err != nullptr) { throw std::runtime_error(err); }
75 }
76 
84 [[nodiscard]] bool is_running_in_wsl() noexcept;
85 
95 [[nodiscard]] bool run_udev_readable() noexcept;
96 
97 } // namespace kvikio