shared_library.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. // Copyright 2014 Renato Tegon Forti, Antony Polukhin.
  2. // Copyright Antony Polukhin, 2015-2025.
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt
  6. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. #ifndef BOOST_DLL_SHARED_LIBRARY_HPP
  8. #define BOOST_DLL_SHARED_LIBRARY_HPP
  9. /// \file boost/dll/shared_library.hpp
  10. /// \brief Contains the boost::dll::shared_library class, core class for all the
  11. /// DLL/DSO operations.
  12. #include <boost/dll/config.hpp>
  13. #include <boost/predef/os.h>
  14. #include <boost/core/enable_if.hpp>
  15. #include <boost/core/explicit_operator_bool.hpp>
  16. #include <boost/dll/detail/system_error.hpp>
  17. #include <boost/dll/detail/aggressive_ptr_cast.hpp>
  18. #if BOOST_OS_WINDOWS
  19. # include <boost/dll/detail/windows/shared_library_impl.hpp>
  20. #else
  21. # include <boost/dll/detail/posix/shared_library_impl.hpp>
  22. #endif
  23. #include <type_traits>
  24. #include <utility> // std::move
  25. #ifdef BOOST_HAS_PRAGMA_ONCE
  26. # pragma once
  27. #endif
  28. namespace boost { namespace dll {
  29. /*!
  30. * \brief This class can be used to load a
  31. * Dynamic link libraries (DLL's) or Shared Libraries, also know
  32. * as dynamic shared objects (DSO's) and get their exported
  33. * symbols (functions and variables).
  34. *
  35. * shared_library instances share reference count to an actual loaded DLL/DSO, so it
  36. * is safe and memory efficient to have multiple instances of shared_library referencing the same DLL/DSO
  37. * even if those instances were loaded using different paths (relative + absolute) referencing the same object.
  38. *
  39. * On Linux/POSIX link with library "dl". "-fvisibility=hidden" flag is also recommended for use on Linux/POSIX.
  40. */
  41. class shared_library
  42. /// @cond
  43. : private boost::dll::detail::shared_library_impl
  44. /// @endcond
  45. {
  46. typedef boost::dll::detail::shared_library_impl base_t;
  47. public:
  48. #ifdef BOOST_DLL_DOXYGEN
  49. typedef platform_specific native_handle_t;
  50. #else
  51. typedef shared_library_impl::native_handle_t native_handle_t;
  52. #endif
  53. /*!
  54. * Creates in anstance that does not reference any DLL/DSO.
  55. *
  56. * \post this->is_loaded() returns false.
  57. * \throw Nothing.
  58. */
  59. shared_library() noexcept = default;
  60. /*!
  61. * Copy constructor that increments the reference count of an underlying shared library.
  62. * Same as calling constructor with `lib.location()` parameter.
  63. *
  64. * \param lib A library to copy.
  65. * \post lib == *this
  66. * \throw \forcedlinkfs{system_error}, std::bad_alloc in case of insufficient memory.
  67. */
  68. shared_library(const shared_library& lib)
  69. : base_t()
  70. {
  71. assign(lib);
  72. }
  73. /*!
  74. * Copy constructor that increments the reference count of an underlying shared library.
  75. * Same as calling constructor with `lib.location(), ec` parameters.
  76. *
  77. * \param lib A shared library to copy.
  78. * \param ec Variable that will be set to the result of the operation.
  79. * \post lib == *this
  80. * \throw std::bad_alloc in case of insufficient memory.
  81. */
  82. shared_library(const shared_library& lib, std::error_code& ec)
  83. : base_t()
  84. {
  85. assign(lib, ec);
  86. }
  87. /*!
  88. * Move constructor. Does not invalidate existing symbols and functions loaded from lib.
  89. *
  90. * \param lib A shared library to move from.
  91. * \post lib.is_loaded() returns false, this->is_loaded() return true.
  92. * \throw Nothing.
  93. */
  94. shared_library(shared_library&& lib) noexcept
  95. : base_t(std::move(lib))
  96. {}
  97. /*!
  98. * Loads a library by specified path with a specified mode.
  99. *
  100. * \param lib_path Library file name. Can handle std::string, const char*, std::wstring,
  101. * const wchar_t* or \forcedlinkfs{path}.
  102. * \param mode A mode that will be used on library load.
  103. * \throw \forcedlinkfs{system_error}, std::bad_alloc in case of insufficient memory.
  104. */
  105. explicit shared_library(const boost::dll::fs::path& lib_path, load_mode::type mode = load_mode::default_mode) {
  106. shared_library::load(lib_path, mode);
  107. }
  108. /*!
  109. * Loads a library by specified path with a specified mode.
  110. *
  111. * \param lib_path Library file name. Can handle std::string, const char*, std::wstring,
  112. * const wchar_t* or \forcedlinkfs{path}.
  113. * \param mode A mode that will be used on library load.
  114. * \param ec Variable that will be set to the result of the operation.
  115. * \throw std::bad_alloc in case of insufficient memory.
  116. */
  117. shared_library(const boost::dll::fs::path& lib_path, std::error_code& ec, load_mode::type mode = load_mode::default_mode) {
  118. shared_library::load(lib_path, mode, ec);
  119. }
  120. //! \overload shared_library(const boost::dll::fs::path& lib_path, std::error_code& ec, load_mode::type mode = load_mode::default_mode)
  121. shared_library(const boost::dll::fs::path& lib_path, load_mode::type mode, std::error_code& ec) {
  122. shared_library::load(lib_path, mode, ec);
  123. }
  124. /*!
  125. * Takes ownership of a loaded library.
  126. *
  127. * \param handle The native handle.
  128. */
  129. explicit shared_library(native_handle_t handle) noexcept
  130. : base_t(handle)
  131. {}
  132. /*!
  133. * Assignment operator. If this->is_loaded() then calls this->unload(). Does not invalidate existing symbols and functions loaded from lib.
  134. *
  135. * \param lib A shared library to assign from.
  136. * \post lib == *this
  137. * \throw \forcedlinkfs{system_error}, std::bad_alloc in case of insufficient memory.
  138. */
  139. shared_library& operator=(const shared_library& lib) {
  140. std::error_code ec;
  141. assign(lib, ec);
  142. if (ec) {
  143. boost::dll::detail::report_error(ec, "boost::dll::shared_library::operator= failed");
  144. }
  145. return *this;
  146. }
  147. /*!
  148. * Move assignment operator. If this->is_loaded() then calls this->unload(). Does not invalidate existing symbols and functions loaded from lib.
  149. *
  150. * \param lib A library to move from.
  151. * \post lib.is_loaded() returns false.
  152. * \throw Nothing.
  153. */
  154. shared_library& operator=(shared_library&& lib) noexcept {
  155. if (lib.native() != native()) {
  156. swap(lib);
  157. }
  158. return *this;
  159. }
  160. /*!
  161. * Destroys the object by calling `unload()`. If library was loaded multiple times
  162. * by different instances, the actual DLL/DSO won't be unloaded until
  163. * there is at least one instance that references the DLL/DSO.
  164. *
  165. * \throw Nothing.
  166. */
  167. ~shared_library() = default;
  168. /*!
  169. * Makes *this share the same shared object as lib. If *this is loaded, then unloads it.
  170. *
  171. * \post lib.location() == this->location(), lib == *this
  172. * \param lib A library to copy.
  173. * \param ec Variable that will be set to the result of the operation.
  174. * \throw std::bad_alloc in case of insufficient memory.
  175. */
  176. shared_library& assign(const shared_library& lib, std::error_code& ec) {
  177. ec.clear();
  178. if (native() == lib.native()) {
  179. return *this;
  180. }
  181. if (!lib) {
  182. unload();
  183. return *this;
  184. }
  185. boost::dll::fs::path loc = lib.location(ec);
  186. if (ec) {
  187. return *this;
  188. }
  189. shared_library copy(loc, ec);
  190. if (ec) {
  191. return *this;
  192. }
  193. swap(copy);
  194. return *this;
  195. }
  196. /*!
  197. * Makes *this share the same shared object as lib. If *this is loaded, then unloads it.
  198. *
  199. * \param lib A library instance to assign from.
  200. * \post lib.location() == this->location()
  201. * \throw \forcedlinkfs{system_error}, std::bad_alloc in case of insufficient memory.
  202. */
  203. shared_library& assign(const shared_library& lib) {
  204. std::error_code ec;
  205. assign(lib, ec);
  206. if (ec) {
  207. boost::dll::detail::report_error(ec, "boost::dll::shared_library::assign() failed");
  208. }
  209. return *this;
  210. }
  211. /*!
  212. * Loads a library by specified path with a specified mode.
  213. *
  214. * Note that if some library is already loaded in this instance, load will
  215. * call unload() and then load the new provided library.
  216. *
  217. * \param lib_path Library file name. Can handle std::string, const char*, std::wstring,
  218. * const wchar_t* or \forcedlinkfs{path}.
  219. * \param mode A mode that will be used on library load.
  220. * \throw \forcedlinkfs{system_error}, std::bad_alloc in case of insufficient memory.
  221. *
  222. */
  223. void load(const boost::dll::fs::path& lib_path, load_mode::type mode = load_mode::default_mode) {
  224. std::error_code ec;
  225. base_t::load(lib_path, mode, ec);
  226. if (ec) {
  227. boost::dll::detail::report_error(ec, "boost::dll::shared_library::load() failed");
  228. }
  229. }
  230. /*!
  231. * Loads a library by specified path with a specified mode.
  232. *
  233. * Note that if some library is already loaded in this instance, load will
  234. * call unload() and then load the new provided library.
  235. *
  236. * \param lib_path Library file name. Can handle std::string, const char*, std::wstring,
  237. * const wchar_t* or \forcedlinkfs{path}.
  238. * \param ec Variable that will be set to the result of the operation.
  239. * \param mode A mode that will be used on library load.
  240. * \throw std::bad_alloc in case of insufficient memory.
  241. */
  242. void load(const boost::dll::fs::path& lib_path, std::error_code& ec, load_mode::type mode = load_mode::default_mode) {
  243. ec.clear();
  244. base_t::load(lib_path, mode, ec);
  245. }
  246. //! \overload void load(const boost::dll::fs::path& lib_path, std::error_code& ec, load_mode::type mode = load_mode::default_mode)
  247. void load(const boost::dll::fs::path& lib_path, load_mode::type mode, std::error_code& ec) {
  248. ec.clear();
  249. base_t::load(lib_path, mode, ec);
  250. }
  251. /*!
  252. * Unloads a shared library. If library was loaded multiple times
  253. * by different instances, the actual DLL/DSO won't be unloaded until
  254. * there is at least one instance that references the DLL/DSO.
  255. *
  256. * \post this->is_loaded() returns false.
  257. * \throw Nothing.
  258. */
  259. void unload() noexcept {
  260. base_t::unload();
  261. }
  262. /*!
  263. * Check if an library is loaded.
  264. *
  265. * \return true if a library has been loaded.
  266. * \throw Nothing.
  267. */
  268. bool is_loaded() const noexcept {
  269. return base_t::is_loaded();
  270. }
  271. /*!
  272. * Check if an library is loaded.
  273. *
  274. * \return true if a library has been loaded.
  275. * \throw Nothing.
  276. */
  277. explicit operator bool() const noexcept {
  278. return is_loaded();
  279. }
  280. /*!
  281. * Search for a given symbol on loaded library. Works for all symbols, including alias names.
  282. *
  283. * \param symbol_name Null-terminated symbol name. Can handle std::string, char*, const char*.
  284. * \return `true` if the loaded library contains a symbol with a given name.
  285. * \throw Nothing.
  286. */
  287. bool has(const char* symbol_name) const noexcept {
  288. std::error_code ec;
  289. return is_loaded() && !!base_t::symbol_addr(symbol_name, ec) && !ec;
  290. }
  291. //! \overload bool has(const char* symbol_name) const
  292. bool has(const std::string& symbol_name) const noexcept {
  293. return has(symbol_name.c_str());
  294. }
  295. /*!
  296. * Returns reference to the symbol (function or variable) with the given name from the loaded library.
  297. * This call will always succeed and throw nothing if call to `has(const char* )`
  298. * member function with the same symbol name returned `true`.
  299. *
  300. * \b Example:
  301. * \code
  302. * int& i0 = lib.get<int>("integer_name");
  303. * int& i1 = *lib.get<int*>("integer_alias_name");
  304. * \endcode
  305. *
  306. * \tparam T Type of the symbol that we are going to import. Must be explicitly specified.
  307. * \param symbol_name Null-terminated symbol name. Can handle std::string, char*, const char*.
  308. * \return Reference to the symbol.
  309. * \throw \forcedlinkfs{system_error} if symbol does not exist or if the DLL/DSO was not loaded.
  310. */
  311. template <typename T>
  312. inline typename std::enable_if<std::is_member_pointer<T>::value || std::is_reference<T>::value, T>::type get(const std::string& symbol_name) const {
  313. return get<T>(symbol_name.c_str());
  314. }
  315. //! \overload T& get(const std::string& symbol_name) const
  316. template <typename T>
  317. inline typename std::enable_if<!(std::is_member_pointer<T>::value || std::is_reference<T>::value), T&>::type get(const std::string& symbol_name) const {
  318. return get<T>(symbol_name.c_str());
  319. }
  320. //! \overload T& get(const std::string& symbol_name) const
  321. template <typename T>
  322. inline typename std::enable_if<std::is_member_pointer<T>::value || std::is_reference<T>::value, T>::type get(const char* symbol_name) const {
  323. return boost::dll::detail::aggressive_ptr_cast<T>(
  324. get_void(symbol_name)
  325. );
  326. }
  327. //! \overload T& get(const std::string& symbol_name) const
  328. template <typename T>
  329. inline typename std::enable_if<!(std::is_member_pointer<T>::value || std::is_reference<T>::value), T&>::type get(const char* symbol_name) const {
  330. return *boost::dll::detail::aggressive_ptr_cast<T*>(
  331. get_void(symbol_name)
  332. );
  333. }
  334. /*!
  335. * Returns a symbol (function or variable) from a shared library by alias name of the symbol.
  336. *
  337. * \b Example:
  338. * \code
  339. * int& i = lib.get_alias<int>("integer_alias_name");
  340. * \endcode
  341. *
  342. * \tparam T Type of the symbol that we are going to import. Must be explicitly specified..
  343. * \param alias_name Null-terminated alias symbol name. Can handle std::string, char*, const char*.
  344. * \throw \forcedlinkfs{system_error} if symbol does not exist or if the DLL/DSO was not loaded.
  345. */
  346. template <typename T>
  347. inline T& get_alias(const char* alias_name) const {
  348. return *get<T*>(alias_name);
  349. }
  350. //! \overload T& get_alias(const char* alias_name) const
  351. template <typename T>
  352. inline T& get_alias(const std::string& alias_name) const {
  353. return *get<T*>(alias_name.c_str());
  354. }
  355. private:
  356. /// @cond
  357. // get_void is required to reduce binary size: it does not depend on a template
  358. // parameter and will be instantiated only once.
  359. void* get_void(const char* sb) const {
  360. std::error_code ec;
  361. if (!is_loaded()) {
  362. ec = std::make_error_code(
  363. std::errc::bad_file_descriptor
  364. );
  365. // report_error() calls dlsym, do not use it here!
  366. boost::throw_exception(
  367. boost::dll::fs::system_error(
  368. ec, "boost::dll::shared_library::get() failed: no library was loaded"
  369. )
  370. );
  371. }
  372. void* const ret = base_t::symbol_addr(sb, ec);
  373. if (ec || !ret) {
  374. boost::dll::detail::report_error(ec, "boost::dll::shared_library::get() failed");
  375. }
  376. return ret;
  377. }
  378. /// @endcond
  379. public:
  380. /*!
  381. * Returns the native handler of the loaded library.
  382. *
  383. * \return Platform-specific handle.
  384. */
  385. native_handle_t native() const noexcept {
  386. return base_t::native();
  387. }
  388. /*!
  389. * Returns full path and name of this shared object.
  390. *
  391. * \b Example:
  392. * \code
  393. * shared_library lib("test_lib.dll");
  394. * filesystem::path full_path = lib.location(); // C:\Windows\System32\test_lib.dll
  395. * \endcode
  396. *
  397. * \return Full path to the shared library.
  398. * \throw \forcedlinkfs{system_error}, std::bad_alloc.
  399. */
  400. boost::dll::fs::path location() const {
  401. std::error_code ec;
  402. if (!is_loaded()) {
  403. ec = std::make_error_code(
  404. std::errc::bad_file_descriptor
  405. );
  406. boost::throw_exception(
  407. boost::dll::fs::system_error(
  408. ec, "boost::dll::shared_library::location() failed (no library was loaded)"
  409. )
  410. );
  411. }
  412. boost::dll::fs::path full_path = base_t::full_module_path(ec);
  413. if (ec) {
  414. boost::dll::detail::report_error(ec, "boost::dll::shared_library::location() failed");
  415. }
  416. return full_path;
  417. }
  418. /*!
  419. * Returns full path and name of shared module.
  420. *
  421. * \b Example:
  422. * \code
  423. * shared_library lib("test_lib.dll");
  424. * filesystem::path full_path = lib.location(); // C:\Windows\System32\test_lib.dll
  425. * \endcode
  426. *
  427. * \param ec Variable that will be set to the result of the operation.
  428. * \return Full path to the shared library.
  429. * \throw std::bad_alloc.
  430. */
  431. boost::dll::fs::path location(std::error_code& ec) const {
  432. if (!is_loaded()) {
  433. ec = std::make_error_code(
  434. std::errc::bad_file_descriptor
  435. );
  436. return boost::dll::fs::path();
  437. }
  438. ec.clear();
  439. return base_t::full_module_path(ec);
  440. }
  441. /*!
  442. * Returns suffix of shared module:
  443. * in a call to load() or the constructor/load.
  444. *
  445. * \return The suffix od shared module: ".dll" (Windows), ".so" (Unix/Linux/BSD), ".dylib" (MacOS/IOS)
  446. */
  447. static boost::dll::fs::path suffix() {
  448. return base_t::suffix();
  449. }
  450. /*!
  451. * Returns the decorated path to a shared module name, i.e. with needed prefix/suffix added.
  452. *
  453. * \b Recommendations: Use `load` with `load_mode::append_decorations` instead of constructing the decorated path via `decorate()` and loading by it.
  454. *
  455. * For instance, for a path like "path/to/boost" it returns :
  456. * - path/to/libboost.so on posix platforms
  457. * - path/to/libboost.dylib on OSX
  458. * - path/to/boost.dll on Windows
  459. *
  460. * Method handles both relative and absolute paths.
  461. *
  462. * - Windows note: `decorate()` does not prepend "lib" to the decorated path. Use `load` with `load_mode::append_decorations` for MinGW compatibility purpose.
  463. * - Posix note: if the initial module name is already prepended with lib, only the suffix() is appended to the path
  464. *
  465. * \param sl the module name and path to decorate - for instance : /usr/lib/boost
  466. *
  467. * \return The decorated unportable path that may not exists in the filesystem or could be wrong due to platform specifics.
  468. */
  469. static boost::dll::fs::path decorate(const boost::dll::fs::path& sl) {
  470. return base_t::decorate(sl);
  471. }
  472. /*!
  473. * Swaps two libraries. Does not invalidate existing symbols and functions loaded from libraries.
  474. *
  475. * \param rhs Library to swap with.
  476. * \throw Nothing.
  477. */
  478. void swap(shared_library& rhs) noexcept {
  479. base_t::swap(rhs);
  480. }
  481. };
  482. /// Very fast equality check that compares the actual DLL/DSO objects. Throws nothing.
  483. inline bool operator==(const shared_library& lhs, const shared_library& rhs) noexcept {
  484. return lhs.native() == rhs.native();
  485. }
  486. /// Very fast inequality check that compares the actual DLL/DSO objects. Throws nothing.
  487. inline bool operator!=(const shared_library& lhs, const shared_library& rhs) noexcept {
  488. return lhs.native() != rhs.native();
  489. }
  490. /// Compare the actual DLL/DSO objects without any guarantee to be stable between runs. Throws nothing.
  491. inline bool operator<(const shared_library& lhs, const shared_library& rhs) noexcept {
  492. return lhs.native() < rhs.native();
  493. }
  494. /// Swaps two shared libraries. Does not invalidate symbols and functions loaded from libraries. Throws nothing.
  495. inline void swap(shared_library& lhs, shared_library& rhs) noexcept {
  496. lhs.swap(rhs);
  497. }
  498. }} // boost::dll
  499. #endif // BOOST_DLL_SHARED_LIBRARY_HPP