1 /*========================== begin_copyright_notice ============================
2 
3 Copyright (C) 2017-2021 Intel Corporation
4 
5 SPDX-License-Identifier: MIT
6 
7 ============================= end_copyright_notice ===========================*/
8 
9 #pragma once
10 #include <Windows.h>
11 
12 #include "cif/common/library_handle.h"
13 
14 namespace CIF {
15 
RAIIReleaseHelper(HMODULE mod)16 void RAIIReleaseHelper(HMODULE mod) {
17   if (NULL == mod) {
18     return;
19   }
20   FreeLibrary(mod);
21 }
22 
23 using UniquePtrHMODULE_t = std::unique_ptr<std::remove_pointer<HMODULE>::type,
24                                            decltype(&RAIIReleaseHelper)>;
UniquePtrHMODULE(HMODULE mod)25 inline UniquePtrHMODULE_t UniquePtrHMODULE(HMODULE mod) {
26   return UniquePtrHMODULE_t(mod, RAIIReleaseHelper);
27 }
28 
29 class WinLibraryHandle : public LibraryHandle {
30 public:
WinLibraryHandle(HMODULE module,bool ownsHandle)31   WinLibraryHandle(HMODULE module, bool ownsHandle)
32       : module(module), ownsHandle(ownsHandle) {}
~WinLibraryHandle()33   ~WinLibraryHandle() override {
34     if (ownsHandle && (NULL != module)) {
35       FreeLibrary(module);
36     }
37   }
GetFuncPointer(const std::string & funcName)38   void *GetFuncPointer(const std::string &funcName) const override {
39     if (module == NULL) {
40       return nullptr;
41     }
42 
43     return GetProcAddress(module, funcName.c_str());
44   }
45 
46 protected:
47   HMODULE module;
48   bool ownsHandle;
49 };
50 
51 // open based on existing handle - takes ownership over handle
OpenLibrary(UniquePtrHMODULE_t module)52 inline std::unique_ptr<LibraryHandle> OpenLibrary(UniquePtrHMODULE_t module) {
53   std::unique_ptr<LibraryHandle> ret;
54   ret.reset(new WinLibraryHandle(module.release(), true));
55   return ret;
56 }
57 
58 // open based on existing handle - does not take ownership over handle
OpenLibrary(HMODULE module)59 inline std::unique_ptr<LibraryHandle> OpenLibrary(HMODULE module) {
60   std::unique_ptr<LibraryHandle> ret;
61   ret.reset(new WinLibraryHandle(module, false));
62   return ret;
63 }
64 }
65