AttachConsole() isn't available in Windows 2000.
[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   else if (error != ERROR_MOD_NOT_FOUND) return 1;
49
50   return 0;
51 }
52
53 void free_imports() {
54   if (imports.kernel32) FreeLibrary(imports.kernel32);
55   ZeroMemory(&imports, sizeof(imports));
56 }