]> wimlib.net Git - wimlib/blob - src/win32.c
Win32 apply
[wimlib] / src / win32.c
1 #include "config.h"
2
3 #if defined(__CYGWIN__) || defined(__WIN32__)
4 #include <windows.h>
5 #       ifdef ERROR
6 #               undef ERROR
7 #       endif
8
9 #include "wimlib_internal.h"
10
11
12 #ifdef ENABLE_ERROR_MESSAGES
13 void win32_error(u32 err_code)
14 {
15         char *buffer;
16         DWORD nchars;
17         nchars = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
18                                 NULL, err_code, 0,
19                                 (char*)&buffer, 0, NULL);
20         if (nchars == 0) {
21                 ERROR("Error printing error message! "
22                       "Computer will self-destruct in 3 seconds.");
23         } else {
24                 ERROR("Win32 error: %s", buffer);
25                 LocalFree(buffer);
26         }
27 }
28 #else
29 #define win32_error(err_code)
30 #endif
31
32 void *win32_open_file(const void *path)
33 {
34         return CreateFileW((const wchar_t*)path,
35                            GENERIC_READ | READ_CONTROL,
36                            FILE_SHARE_READ,
37                            NULL, /* lpSecurityAttributes */
38                            OPEN_EXISTING,
39                            FILE_FLAG_BACKUP_SEMANTICS |
40                                    FILE_FLAG_OPEN_REPARSE_POINT,
41                            NULL /* hTemplateFile */);
42 }
43                 
44 int win32_read_file(const char *filename,
45                     void *handle, u64 offset, size_t size, u8 *buf)
46 {
47         HANDLE h = handle;
48         DWORD err;
49         DWORD bytesRead;
50         LARGE_INTEGER liOffset = {.QuadPart = offset};
51         
52         wimlib_assert(size <= 0xffffffff);
53
54         if (SetFilePointerEx(h, liOffset, NULL, FILE_BEGIN))
55                 if (ReadFile(h, buf, size, &bytesRead, NULL) && bytesRead == size)
56                         return 0;
57         err = GetLastError();
58         ERROR("Error reading \"%s\"", filename);
59         win32_error(err);
60         return WIMLIB_ERR_READ;
61 }
62
63 void win32_close_file(void *handle)
64 {
65         CloseHandle((HANDLE)handle);
66 }
67
68 #endif /* __CYGWIN__ || __WIN32__ */