99661be714d596659f80988f19093837a61ba4e7
[nssm.git] / imports.cpp
1 #include "nssm.h"
2
3 imports_t imports;
4
5 /*
6   Try to set up function pointers.
7   In this first implementation it is not an error if we can't load them
8   because we aren't currently trying to load any functions which we
9   absolutely need.  If we later add some indispensible imports we can
10   return non-zero here to force an application exit.
11 */
12 HMODULE get_dll(const char *dll, unsigned long *error) {
13   *error = 0;
14
15   HMODULE ret = LoadLibrary(dll);
16   if (! ret) {
17     *error = GetLastError();
18     log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_LOADLIBRARY_FAILED, dll, error_string(*error));
19   }
20
21   return ret;
22 }
23
24 FARPROC get_import(HMODULE library, const char *function, unsigned long *error) {
25   *error = 0;
26
27   FARPROC ret = GetProcAddress(library, function);
28   if (! ret) {
29     *error = GetLastError();
30     log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_GETPROCADDRESS_FAILED, function, error_string(*error));
31   }
32
33   return ret;
34 }
35
36 int get_imports() {
37   unsigned long error;
38
39   ZeroMemory(&imports, sizeof(imports));
40
41   imports.kernel32 = get_dll("kernel32.dll", &error);
42   if (imports.kernel32) {
43     imports.AttachConsole = (AttachConsole_ptr) get_import(imports.kernel32, "AttachConsole", &error);
44     if (! imports.AttachConsole) {
45       if (error != ERROR_PROC_NOT_FOUND) return 2;
46     }
47
48     imports.SleepConditionVariableCS = (SleepConditionVariableCS_ptr) get_import(imports.kernel32, "SleepConditionVariableCS", &error);
49     if (! imports.SleepConditionVariableCS) {
50       if (error != ERROR_PROC_NOT_FOUND) return 3;
51     }
52
53     imports.WakeConditionVariable = (WakeConditionVariable_ptr) get_import(imports.kernel32, "WakeConditionVariable", &error);
54     if (! imports.WakeConditionVariable) {
55       if (error != ERROR_PROC_NOT_FOUND) return 4;
56     }
57   }
58   else if (error != ERROR_MOD_NOT_FOUND) return 1;
59
60   return 0;
61 }
62
63 void free_imports() {
64   if (imports.kernel32) FreeLibrary(imports.kernel32);
65   ZeroMemory(&imports, sizeof(imports));
66 }