]> mj.ucw.cz Git - pciutils.git/blob - lib/win32-helpers.c
windows: Deduplicate code and move helper functions to new file win32-helpers.c
[pciutils.git] / lib / win32-helpers.c
1 /*
2  *      The PCI Library -- Win32 helper functions
3  *
4  *      Copyright (c) 2023 Pali Rohár <pali@kernel.org>
5  *
6  *      Can be freely distributed and used under the terms of the GNU GPL v2+
7  *
8  *      SPDX-License-Identifier: GPL-2.0-or-later
9  */
10
11 #include <windows.h>
12 #include <stdio.h> /* for sprintf() */
13
14 #include "win32-helpers.h"
15
16 const char *
17 win32_strerror(DWORD win32_error_id)
18 {
19   /*
20    * Use static buffer which is large enough.
21    * Hopefully no Win32 API error message string is longer than 4 kB.
22    */
23   static char buffer[4096];
24   DWORD len;
25
26   len = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, win32_error_id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, sizeof(buffer), NULL);
27
28   /* FormatMessage() automatically appends ".\r\n" to the error message. */
29   if (len && buffer[len-1] == '\n')
30     buffer[--len] = '\0';
31   if (len && buffer[len-1] == '\r')
32     buffer[--len] = '\0';
33   if (len && buffer[len-1] == '.')
34     buffer[--len] = '\0';
35
36   if (!len)
37     sprintf(buffer, "Unknown Win32 error %lu", win32_error_id);
38
39   return buffer;
40 }
41
42 BOOL
43 win32_is_non_nt_system(void)
44 {
45   OSVERSIONINFOA version;
46   version.dwOSVersionInfoSize = sizeof(version);
47   return GetVersionExA(&version) && version.dwPlatformId < VER_PLATFORM_WIN32_NT;
48 }
49
50 BOOL
51 win32_is_32bit_on_64bit_system(void)
52 {
53   BOOL (WINAPI *MyIsWow64Process)(HANDLE, PBOOL);
54   HMODULE kernel32;
55   BOOL is_wow64;
56
57   /*
58    * Check for 64-bit system via IsWow64Process() function exported
59    * from 32-bit kernel32.dll library available on the 64-bit systems.
60    * Resolve pointer to this function at runtime as this code path is
61    * primary running on 32-bit systems where are not available 64-bit
62    * functions.
63    */
64
65   kernel32 = GetModuleHandle(TEXT("kernel32.dll"));
66   if (!kernel32)
67     return FALSE;
68
69   MyIsWow64Process = (void *)GetProcAddress(kernel32, "IsWow64Process");
70   if (!MyIsWow64Process)
71     return FALSE;
72
73   if (!MyIsWow64Process(GetCurrentProcess(), &is_wow64))
74     return FALSE;
75
76   return is_wow64;
77 }
78
79 BOOL
80 win32_is_32bit_on_win8_64bit_system(void)
81 {
82 #ifdef _WIN64
83   return FALSE;
84 #else
85   OSVERSIONINFOA version;
86
87   /* Check for Windows 8 (NT 6.2). */
88   version.dwOSVersionInfoSize = sizeof(version);
89   if (!GetVersionExA(&version) ||
90       version.dwPlatformId != VER_PLATFORM_WIN32_NT ||
91       version.dwMajorVersion < 6 ||
92       (version.dwMajorVersion == 6 && version.dwMinorVersion < 2))
93     return FALSE;
94
95   return win32_is_32bit_on_64bit_system();
96 #endif
97 }