bactria  0.0.1
The bactria library is a header-only C++14 library for profiling and tracing.
POSIX.hpp
Go to the documentation of this file.
1 /* Copyright 2021 Jan Stephan
2  *
3  * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
4  * the European Commission - subsequent versions of the EUPL (the “Licence”).
5  * You may not use this work except in compliance with the Licence.
6  * You may obtain a copy of the Licence at:
7  *
8  * http://ec.europa.eu/idabc/eupl.html
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the Licence is distributed on an “AS IS” basis, WITHOUT
12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13  * Licence permissions and limitations under the Licence.
14  */
15 
23 #pragma once
24 
25 #ifndef _WIN32
26 
27 # include <dlfcn.h>
28 
29 # include <cstdio>
30 # include <cstdlib>
31 # include <stdexcept>
32 # include <string>
33 
34 namespace bactria
35 {
36  namespace system
37  {
44  using plugin_handle_t = void*;
45 
57  [[nodiscard, gnu::always_inline]] inline auto open_plugin(const char* path)
58  {
59  auto handle = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
60  if(handle != nullptr)
61  return handle;
62 
63  throw std::runtime_error{dlerror()};
64  }
65 
79  template<typename Sig>
80  [[gnu::always_inline]] inline auto load_func(plugin_handle_t handle, Sig& ptr, const char* name)
81  {
82  if(ptr == nullptr)
83  {
84  ptr = reinterpret_cast<Sig>(dlsym(handle, name));
85  if(ptr == nullptr)
86  throw std::runtime_error{dlerror()};
87  }
88  }
89 
99  [[gnu::always_inline]] inline auto close_plugin(plugin_handle_t handle) noexcept
100  {
101  if(handle == nullptr)
102  return;
103 
104  auto err = dlclose(handle);
105  if(err != 0)
106  {
107  auto errstr = dlerror();
108  if(errstr != nullptr)
109  std::fprintf(stderr, "WARNING: Error while closing plugin library: %s\n", errstr);
110  else
111  std::fprintf(stderr, "WARNING: Unknown error while closing plugin library.\n");
112  }
113  }
114  } // namespace system
115 } // namespace bactria
116 
117 #endif // _WIN32
bactria::system::load_func
auto load_func(plugin_handle_t handle, Sig &ptr, const char *name)
The POSIX-specific function loader.
Definition: POSIX.hpp:80
bactria::system::open_plugin
auto open_plugin(const char *path)
The POSIX-specific plugin loader.
Definition: POSIX.hpp:57
bactria::system::plugin_handle_t
void * plugin_handle_t
The POSIX-specific handle type.
Definition: POSIX.hpp:44
bactria::system::close_plugin
auto close_plugin(plugin_handle_t handle) noexcept
The POSIX-specific plugin unloader.
Definition: POSIX.hpp:99