imports.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "nssm.h"
  2. imports_t imports;
  3. /*
  4. Try to set up function pointers.
  5. In this first implementation it is not an error if we can't load them
  6. because we aren't currently trying to load any functions which we
  7. absolutely need. If we later add some indispensible imports we can
  8. return non-zero here to force an application exit.
  9. */
  10. HMODULE get_dll(const TCHAR *dll, unsigned long *error) {
  11. *error = 0;
  12. HMODULE ret = LoadLibrary(dll);
  13. if (! ret) {
  14. *error = GetLastError();
  15. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_LOADLIBRARY_FAILED, dll, error_string(*error), 0);
  16. }
  17. return ret;
  18. }
  19. FARPROC get_import(HMODULE library, const char *function, unsigned long *error) {
  20. *error = 0;
  21. FARPROC ret = GetProcAddress(library, function);
  22. if (! ret) {
  23. *error = GetLastError();
  24. TCHAR *function_name;
  25. #ifdef UNICODE
  26. size_t buflen;
  27. mbstowcs_s(&buflen, NULL, 0, function, _TRUNCATE);
  28. function_name = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, buflen * sizeof(TCHAR));
  29. if (function_name) mbstowcs_s(&buflen, function_name, buflen * sizeof(TCHAR), function, _TRUNCATE);
  30. #else
  31. function_name = (TCHAR *) function;
  32. #endif
  33. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_GETPROCADDRESS_FAILED, function_name, error_string(*error), 0);
  34. #ifdef UNICODE
  35. if (function_name) HeapFree(GetProcessHeap(), 0, function_name);
  36. #endif
  37. }
  38. return ret;
  39. }
  40. int get_imports() {
  41. unsigned long error;
  42. ZeroMemory(&imports, sizeof(imports));
  43. imports.kernel32 = get_dll(_T("kernel32.dll"), &error);
  44. if (imports.kernel32) {
  45. imports.AttachConsole = (AttachConsole_ptr) get_import(imports.kernel32, "AttachConsole", &error);
  46. if (! imports.AttachConsole) {
  47. if (error != ERROR_PROC_NOT_FOUND) return 2;
  48. }
  49. imports.SleepConditionVariableCS = (SleepConditionVariableCS_ptr) get_import(imports.kernel32, "SleepConditionVariableCS", &error);
  50. if (! imports.SleepConditionVariableCS) {
  51. if (error != ERROR_PROC_NOT_FOUND) return 3;
  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. return 0;
  60. }
  61. void free_imports() {
  62. if (imports.kernel32) FreeLibrary(imports.kernel32);
  63. ZeroMemory(&imports, sizeof(imports));
  64. }