Assorted spelling fixes.
[wine] / dlls / kernel32 / tests / loader.c
1 /*
2  * Unit test suite for the PE loader.
3  *
4  * Copyright 2006,2011 Dmitry Timoshkov
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22 #include <assert.h>
23
24 #include "ntstatus.h"
25 #define WIN32_NO_STATUS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winternl.h"
29 #include "wine/test.h"
30
31 #define ALIGN_SIZE(size, alignment) (((size) + (alignment - 1)) & ~((alignment - 1)))
32
33 static NTSTATUS (WINAPI *pNtMapViewOfSection)(HANDLE, HANDLE, PVOID *, ULONG, SIZE_T, const LARGE_INTEGER *, SIZE_T *, ULONG, ULONG, ULONG);
34 static NTSTATUS (WINAPI *pNtUnmapViewOfSection)(HANDLE, PVOID);
35
36 static PVOID RVAToAddr(DWORD_PTR rva, HMODULE module)
37 {
38     if (rva == 0)
39         return NULL;
40     return ((char*) module) + rva;
41 }
42
43 static const struct
44 {
45     WORD e_magic;      /* 00: MZ Header signature */
46     WORD unused[29];
47     DWORD e_lfanew;    /* 3c: Offset to extended header */
48 } dos_header =
49 {
50     IMAGE_DOS_SIGNATURE, { 0 }, sizeof(dos_header)
51 };
52
53 static IMAGE_NT_HEADERS nt_header =
54 {
55     IMAGE_NT_SIGNATURE, /* Signature */
56     {
57 #if defined __i386__
58       IMAGE_FILE_MACHINE_I386, /* Machine */
59 #elif defined __x86_64__
60       IMAGE_FILE_MACHINE_AMD64, /* Machine */
61 #elif defined __powerpc__
62       IMAGE_FILE_MACHINE_POWERPC, /* Machine */
63 #elif defined __sparc__
64       IMAGE_FILE_MACHINE_SPARC, /* Machine */
65 #elif defined __arm__
66       IMAGE_FILE_MACHINE_ARMV7, /* Machine */
67 #else
68 # error You must specify the machine type
69 #endif
70       1, /* NumberOfSections */
71       0, /* TimeDateStamp */
72       0, /* PointerToSymbolTable */
73       0, /* NumberOfSymbols */
74       sizeof(IMAGE_OPTIONAL_HEADER), /* SizeOfOptionalHeader */
75       IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL /* Characteristics */
76     },
77     { IMAGE_NT_OPTIONAL_HDR_MAGIC, /* Magic */
78       1, /* MajorLinkerVersion */
79       0, /* MinorLinkerVersion */
80       0, /* SizeOfCode */
81       0, /* SizeOfInitializedData */
82       0, /* SizeOfUninitializedData */
83       0, /* AddressOfEntryPoint */
84       0x10, /* BaseOfCode, also serves as e_lfanew in the truncated MZ header */
85 #ifndef _WIN64
86       0, /* BaseOfData */
87 #endif
88       0x10000000, /* ImageBase */
89       0, /* SectionAlignment */
90       0, /* FileAlignment */
91       4, /* MajorOperatingSystemVersion */
92       0, /* MinorOperatingSystemVersion */
93       1, /* MajorImageVersion */
94       0, /* MinorImageVersion */
95       4, /* MajorSubsystemVersion */
96       0, /* MinorSubsystemVersion */
97       0, /* Win32VersionValue */
98       sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000, /* SizeOfImage */
99       sizeof(dos_header) + sizeof(nt_header), /* SizeOfHeaders */
100       0, /* CheckSum */
101       IMAGE_SUBSYSTEM_WINDOWS_CUI, /* Subsystem */
102       0, /* DllCharacteristics */
103       0, /* SizeOfStackReserve */
104       0, /* SizeOfStackCommit */
105       0, /* SizeOfHeapReserve */
106       0, /* SizeOfHeapCommit */
107       0, /* LoaderFlags */
108       0, /* NumberOfRvaAndSizes */
109       { { 0 } } /* DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] */
110     }
111 };
112
113 static IMAGE_SECTION_HEADER section =
114 {
115     ".rodata", /* Name */
116     { 0x10 }, /* Misc */
117     0, /* VirtualAddress */
118     0x0a, /* SizeOfRawData */
119     0, /* PointerToRawData */
120     0, /* PointerToRelocations */
121     0, /* PointerToLinenumbers */
122     0, /* NumberOfRelocations */
123     0, /* NumberOfLinenumbers */
124     IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, /* Characteristics */
125 };
126
127 static void test_Loader(void)
128 {
129     static const struct test_data
130     {
131         const void *dos_header;
132         DWORD size_of_dos_header;
133         WORD number_of_sections, size_of_optional_header;
134         DWORD section_alignment, file_alignment;
135         DWORD size_of_image, size_of_headers;
136         DWORD errors[4]; /* 0 means LoadLibrary should succeed */
137     } td[] =
138     {
139         { &dos_header, sizeof(dos_header),
140           1, 0, 0, 0, 0, 0,
141           { ERROR_BAD_EXE_FORMAT }
142         },
143         { &dos_header, sizeof(dos_header),
144           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
145           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0xe00,
146           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
147           { ERROR_BAD_EXE_FORMAT } /* XP doesn't like too small image size */
148         },
149         { &dos_header, sizeof(dos_header),
150           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
151           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
152           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
153           { ERROR_SUCCESS }
154         },
155         { &dos_header, sizeof(dos_header),
156           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
157           0x1f00,
158           0x1000,
159           { ERROR_SUCCESS }
160         },
161         { &dos_header, sizeof(dos_header),
162           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x200, 0x200,
163           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x200,
164           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
165           { ERROR_SUCCESS, ERROR_INVALID_ADDRESS } /* vista is more strict */
166         },
167         { &dos_header, sizeof(dos_header),
168           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x200, 0x1000,
169           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
170           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
171           { ERROR_BAD_EXE_FORMAT } /* XP doesn't like alignments */
172         },
173         { &dos_header, sizeof(dos_header),
174           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x200,
175           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
176           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
177           { ERROR_SUCCESS }
178         },
179         { &dos_header, sizeof(dos_header),
180           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x200,
181           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
182           0x200,
183           { ERROR_SUCCESS }
184         },
185         /* Mandatory are all fields up to SizeOfHeaders, everything else
186          * is really optional (at least that's true for XP).
187          */
188         { &dos_header, sizeof(dos_header),
189           1, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
190           sizeof(dos_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum) + sizeof(IMAGE_SECTION_HEADER) + 0x10,
191           sizeof(dos_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum) + sizeof(IMAGE_SECTION_HEADER),
192           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT, ERROR_INVALID_ADDRESS,
193             ERROR_NOACCESS }
194         },
195         { &dos_header, sizeof(dos_header),
196           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
197           0xd0, /* beyond of the end of file */
198           0xc0, /* beyond of the end of file */
199           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
200         },
201         { &dos_header, sizeof(dos_header),
202           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
203           0x1000,
204           0,
205           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
206         },
207         { &dos_header, sizeof(dos_header),
208           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
209           1,
210           0,
211           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
212         },
213 #if 0 /* not power of 2 alignments need more test cases */
214         { &dos_header, sizeof(dos_header),
215           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x300, 0x300,
216           1,
217           0,
218           { ERROR_BAD_EXE_FORMAT } /* alignment is not power of 2 */
219         },
220 #endif
221         { &dos_header, sizeof(dos_header),
222           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 4, 4,
223           1,
224           0,
225           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
226         },
227         { &dos_header, sizeof(dos_header),
228           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 1, 1,
229           1,
230           0,
231           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
232         },
233         { &dos_header, sizeof(dos_header),
234           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
235           0,
236           0,
237           { ERROR_BAD_EXE_FORMAT } /* image size == 0 -> failure */
238         },
239         /* the following data mimics the PE image which upack creates */
240         { &dos_header, 0x10,
241           1, 0x148, 0x1000, 0x200,
242           sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
243           0x200,
244           { ERROR_SUCCESS }
245         },
246         /* Minimal PE image that XP is able to load: 92 bytes */
247         { &dos_header, 0x04,
248           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum),
249           0x04 /* also serves as e_lfanew in the truncated MZ header */, 0x04,
250           1,
251           0,
252           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
253         }
254     };
255     static const char filler[0x1000];
256     static const char section_data[0x10] = "section data";
257     int i;
258     DWORD dummy, file_size, file_align;
259     HANDLE hfile;
260     HMODULE hlib, hlib_as_data_file;
261     SYSTEM_INFO si;
262     char temp_path[MAX_PATH];
263     char dll_name[MAX_PATH];
264     SIZE_T size;
265     BOOL ret;
266
267     GetSystemInfo(&si);
268     trace("system page size 0x%04x\n", si.dwPageSize);
269
270     /* prevent displaying of the "Unable to load this DLL" message box */
271     SetErrorMode(SEM_FAILCRITICALERRORS);
272
273     GetTempPath(MAX_PATH, temp_path);
274
275     for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
276     {
277         GetTempFileName(temp_path, "ldr", 0, dll_name);
278
279         /*trace("creating %s\n", dll_name);*/
280         hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
281         if (hfile == INVALID_HANDLE_VALUE)
282         {
283             ok(0, "could not create %s\n", dll_name);
284             break;
285         }
286
287         SetLastError(0xdeadbeef);
288         ret = WriteFile(hfile, td[i].dos_header, td[i].size_of_dos_header, &dummy, NULL);
289         ok(ret, "WriteFile error %d\n", GetLastError());
290
291         nt_header.FileHeader.NumberOfSections = td[i].number_of_sections;
292         nt_header.FileHeader.SizeOfOptionalHeader = td[i].size_of_optional_header;
293
294         nt_header.OptionalHeader.SectionAlignment = td[i].section_alignment;
295         nt_header.OptionalHeader.FileAlignment = td[i].file_alignment;
296         nt_header.OptionalHeader.SizeOfImage = td[i].size_of_image;
297         nt_header.OptionalHeader.SizeOfHeaders = td[i].size_of_headers;
298         SetLastError(0xdeadbeef);
299         ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
300         ok(ret, "WriteFile error %d\n", GetLastError());
301
302         if (nt_header.FileHeader.SizeOfOptionalHeader)
303         {
304             SetLastError(0xdeadbeef);
305             ret = WriteFile(hfile, &nt_header.OptionalHeader,
306                             min(nt_header.FileHeader.SizeOfOptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER)),
307                             &dummy, NULL);
308             ok(ret, "WriteFile error %d\n", GetLastError());
309             if (nt_header.FileHeader.SizeOfOptionalHeader > sizeof(IMAGE_OPTIONAL_HEADER))
310             {
311                 file_align = nt_header.FileHeader.SizeOfOptionalHeader - sizeof(IMAGE_OPTIONAL_HEADER);
312                 assert(file_align < sizeof(filler));
313                 SetLastError(0xdeadbeef);
314                 ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
315                 ok(ret, "WriteFile error %d\n", GetLastError());
316             }
317         }
318
319         assert(nt_header.FileHeader.NumberOfSections <= 1);
320         if (nt_header.FileHeader.NumberOfSections)
321         {
322             if (nt_header.OptionalHeader.SectionAlignment >= si.dwPageSize)
323             {
324                 section.PointerToRawData = td[i].size_of_dos_header;
325                 section.VirtualAddress = nt_header.OptionalHeader.SectionAlignment;
326                 section.Misc.VirtualSize = section.SizeOfRawData * 10;
327             }
328             else
329             {
330                 section.PointerToRawData = nt_header.OptionalHeader.SizeOfHeaders;
331                 section.VirtualAddress = nt_header.OptionalHeader.SizeOfHeaders;
332                 section.Misc.VirtualSize = 5;
333             }
334
335             SetLastError(0xdeadbeef);
336             ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
337             ok(ret, "WriteFile error %d\n", GetLastError());
338
339             /* section data */
340             SetLastError(0xdeadbeef);
341             ret = WriteFile(hfile, section_data, sizeof(section_data), &dummy, NULL);
342             ok(ret, "WriteFile error %d\n", GetLastError());
343         }
344
345         file_size = GetFileSize(hfile, NULL);
346         CloseHandle(hfile);
347
348         SetLastError(0xdeadbeef);
349         hlib = LoadLibrary(dll_name);
350         if (hlib)
351         {
352             MEMORY_BASIC_INFORMATION info;
353
354             ok( td[i].errors[0] == ERROR_SUCCESS, "%d: should have failed\n", i );
355
356             SetLastError(0xdeadbeef);
357             size = VirtualQuery(hlib, &info, sizeof(info));
358             ok(size == sizeof(info),
359                 "%d: VirtualQuery error %d\n", i, GetLastError());
360             ok(info.BaseAddress == hlib, "%d: %p != %p\n", i, info.BaseAddress, hlib);
361             ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
362             ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
363             ok(info.RegionSize == ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, si.dwPageSize), "%d: got %lx != expected %x\n",
364                i, info.RegionSize, ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, si.dwPageSize));
365             ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
366             if (nt_header.OptionalHeader.SectionAlignment < si.dwPageSize)
367                 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
368             else
369                 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
370             ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
371
372             SetLastError(0xdeadbeef);
373             size = VirtualQuery((char *)hlib + info.RegionSize, &info, sizeof(info));
374             ok(size == sizeof(info),
375                 "%d: VirtualQuery error %d\n", i, GetLastError());
376             if (nt_header.OptionalHeader.SectionAlignment == si.dwPageSize ||
377                 nt_header.OptionalHeader.SectionAlignment == nt_header.OptionalHeader.FileAlignment)
378             {
379                 ok(info.BaseAddress == (char *)hlib + ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, si.dwPageSize), "%d: got %p != expected %p\n",
380                    i, info.BaseAddress, (char *)hlib + ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, si.dwPageSize));
381                 ok(info.AllocationBase == 0, "%d: %p != 0\n", i, info.AllocationBase);
382                 ok(info.AllocationProtect == 0, "%d: %x != 0\n", i, info.AllocationProtect);
383                 /*ok(info.RegionSize == not_practical_value, "%d: %lx != not_practical_value\n", i, info.RegionSize);*/
384                 ok(info.State == MEM_FREE, "%d: %x != MEM_FREE\n", i, info.State);
385                 ok(info.Type == 0, "%d: %x != 0\n", i, info.Type);
386                 ok(info.Protect == PAGE_NOACCESS, "%d: %x != PAGE_NOACCESS\n", i, info.Protect);
387             }
388             else
389             {
390                 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
391                 ok(info.BaseAddress == hlib, "%d: got %p != expected %p\n", i, info.BaseAddress, hlib);
392                 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
393                 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
394                 ok(info.RegionSize == ALIGN_SIZE(file_size, si.dwPageSize), "%d: got %lx != expected %x\n",
395                    i, info.RegionSize, ALIGN_SIZE(file_size, si.dwPageSize));
396                 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
397                 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
398                 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
399             }
400
401             /* header: check the zeroing of alignment */
402             if (nt_header.OptionalHeader.SectionAlignment >= si.dwPageSize)
403             {
404                 const char *start;
405                 int size;
406
407                 start = (const char *)hlib + nt_header.OptionalHeader.SizeOfHeaders;
408                 size = ALIGN_SIZE((ULONG_PTR)start, si.dwPageSize) - (ULONG_PTR)start;
409                 ok(!memcmp(start, filler, size), "%d: header alignment is not cleared\n", i);
410             }
411
412             if (nt_header.FileHeader.NumberOfSections)
413             {
414                 SetLastError(0xdeadbeef);
415                 size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
416                 ok(size == sizeof(info),
417                     "%d: VirtualQuery error %d\n", i, GetLastError());
418                 if (nt_header.OptionalHeader.SectionAlignment < si.dwPageSize)
419                 {
420                     ok(info.BaseAddress == hlib, "%d: got %p != expected %p\n", i, info.BaseAddress, hlib);
421                     ok(info.RegionSize == ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, si.dwPageSize), "%d: got %lx != expected %x\n",
422                        i, info.RegionSize, ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, si.dwPageSize));
423                     ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
424                 }
425                 else
426                 {
427                     ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
428                     ok(info.RegionSize == ALIGN_SIZE(section.Misc.VirtualSize, si.dwPageSize), "%d: got %lx != expected %x\n",
429                        i, info.RegionSize, ALIGN_SIZE(section.Misc.VirtualSize, si.dwPageSize));
430                     ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
431                 }
432                 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
433                 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
434                 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
435                 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
436
437                 if (nt_header.OptionalHeader.SectionAlignment >= si.dwPageSize)
438                     ok(!memcmp((const char *)hlib + section.VirtualAddress + section.PointerToRawData, &nt_header, section.SizeOfRawData), "wrong section data\n");
439                 else
440                     ok(!memcmp((const char *)hlib + section.PointerToRawData, section_data, section.SizeOfRawData), "wrong section data\n");
441
442                 /* check the zeroing of alignment */
443                 if (nt_header.OptionalHeader.SectionAlignment >= si.dwPageSize)
444                 {
445                     const char *start;
446                     int size;
447
448                     start = (const char *)hlib + section.VirtualAddress + section.PointerToRawData + section.SizeOfRawData;
449                     size = ALIGN_SIZE((ULONG_PTR)start, si.dwPageSize) - (ULONG_PTR)start;
450                     ok(memcmp(start, filler, size), "%d: alignment should not be cleared\n", i);
451                 }
452             }
453
454             SetLastError(0xdeadbeef);
455             hlib_as_data_file = LoadLibraryEx(dll_name, 0, LOAD_LIBRARY_AS_DATAFILE);
456             ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
457             ok(hlib_as_data_file == hlib, "hlib_as_file and hlib are different\n");
458
459             SetLastError(0xdeadbeef);
460             ret = FreeLibrary(hlib);
461             ok(ret, "FreeLibrary error %d\n", GetLastError());
462
463             SetLastError(0xdeadbeef);
464             hlib = GetModuleHandle(dll_name);
465             ok(hlib != 0, "GetModuleHandle error %u\n", GetLastError());
466
467             SetLastError(0xdeadbeef);
468             ret = FreeLibrary(hlib_as_data_file);
469             ok(ret, "FreeLibrary error %d\n", GetLastError());
470
471             hlib = GetModuleHandle(dll_name);
472             ok(!hlib, "GetModuleHandle should fail\n");
473
474             SetLastError(0xdeadbeef);
475             hlib_as_data_file = LoadLibraryEx(dll_name, 0, LOAD_LIBRARY_AS_DATAFILE);
476             ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
477             ok((ULONG_PTR)hlib_as_data_file & 1, "hlib_as_data_file is even\n");
478
479             hlib = GetModuleHandle(dll_name);
480             ok(!hlib, "GetModuleHandle should fail\n");
481
482             SetLastError(0xdeadbeef);
483             ret = FreeLibrary(hlib_as_data_file);
484             ok(ret, "FreeLibrary error %d\n", GetLastError());
485         }
486         else
487         {
488             BOOL error_match;
489             int error_index;
490
491             error_match = FALSE;
492             for (error_index = 0;
493                  ! error_match && error_index < sizeof(td[i].errors) / sizeof(DWORD);
494                  error_index++)
495             {
496                 error_match = td[i].errors[error_index] == GetLastError();
497             }
498             ok(error_match, "%d: unexpected error %d\n", i, GetLastError());
499         }
500
501         SetLastError(0xdeadbeef);
502         ret = DeleteFile(dll_name);
503         ok(ret, "DeleteFile error %d\n", GetLastError());
504     }
505 }
506
507 /* Verify linking style of import descriptors */
508 static void test_ImportDescriptors(void)
509 {
510     HMODULE kernel32_module = NULL;
511     PIMAGE_DOS_HEADER d_header;
512     PIMAGE_NT_HEADERS nt_headers;
513     DWORD import_dir_size;
514     DWORD_PTR dir_offset;
515     PIMAGE_IMPORT_DESCRIPTOR import_chunk;
516
517     /* Load kernel32 module */
518     kernel32_module = GetModuleHandleA("kernel32.dll");
519     assert( kernel32_module != NULL );
520
521     /* Get PE header info from module image */
522     d_header = (PIMAGE_DOS_HEADER) kernel32_module;
523     nt_headers = (PIMAGE_NT_HEADERS) (((char*) d_header) +
524             d_header->e_lfanew);
525
526     /* Get size of import entry directory */
527     import_dir_size = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size;
528     if (!import_dir_size)
529     {
530         skip("Unable to continue testing due to missing import directory.\n");
531         return;
532     }
533
534     /* Get address of first import chunk */
535     dir_offset = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
536     import_chunk = RVAToAddr(dir_offset, kernel32_module);
537     ok(import_chunk != 0, "Invalid import_chunk: %p\n", import_chunk);
538     if (!import_chunk) return;
539
540     /* Iterate through import descriptors and verify set name,
541      * OriginalFirstThunk, and FirstThunk.  Core Windows DLLs, such as
542      * kernel32.dll, don't use Borland-style linking, where the table of
543      * imported names is stored directly in FirstThunk and overwritten
544      * by the relocation, instead of being stored in OriginalFirstThunk.
545      * */
546     for (; import_chunk->FirstThunk; import_chunk++)
547     {
548         LPCSTR module_name = RVAToAddr(import_chunk->Name, kernel32_module);
549         PIMAGE_THUNK_DATA name_table = RVAToAddr(
550                 U(*import_chunk).OriginalFirstThunk, kernel32_module);
551         PIMAGE_THUNK_DATA iat = RVAToAddr(
552                 import_chunk->FirstThunk, kernel32_module);
553         ok(module_name != NULL, "Imported module name should not be NULL\n");
554         ok(name_table != NULL,
555                 "Name table for imported module %s should not be NULL\n",
556                 module_name);
557         ok(iat != NULL, "IAT for imported module %s should not be NULL\n",
558                 module_name);
559     }
560 }
561
562 static void test_image_mapping(const char *dll_name, DWORD scn_page_access, BOOL is_dll)
563 {
564     HANDLE hfile, hmap;
565     NTSTATUS status;
566     LARGE_INTEGER offset;
567     SIZE_T size;
568     void *addr1, *addr2;
569     MEMORY_BASIC_INFORMATION info;
570     SYSTEM_INFO si;
571
572     if (!pNtMapViewOfSection) return;
573
574     GetSystemInfo(&si);
575
576     SetLastError(0xdeadbeef);
577     hfile = CreateFile(dll_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
578     ok(hfile != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
579
580     SetLastError(0xdeadbeef);
581     hmap = CreateFileMapping(hfile, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, 0);
582     ok(hmap != 0, "CreateFileMapping error %d\n", GetLastError());
583
584     offset.u.LowPart  = 0;
585     offset.u.HighPart = 0;
586
587     addr1 = NULL;
588     size = 0;
589     status = pNtMapViewOfSection(hmap, GetCurrentProcess(), &addr1, 0, 0, &offset,
590                                  &size, 1 /* ViewShare */, 0, PAGE_READONLY);
591     ok(status == STATUS_SUCCESS, "NtMapViewOfSection error %x\n", status);
592     ok(addr1 != 0, "mapped address should be valid\n");
593
594     SetLastError(0xdeadbeef);
595     size = VirtualQuery((char *)addr1 + section.VirtualAddress, &info, sizeof(info));
596     ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
597     ok(info.BaseAddress == (char *)addr1 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr1 + section.VirtualAddress);
598     ok(info.RegionSize == si.dwPageSize, "got %#lx != expected %#x\n", info.RegionSize, si.dwPageSize);
599     ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
600     ok(info.AllocationBase == addr1, "%p != %p\n", info.AllocationBase, addr1);
601     ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
602     ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
603     ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
604
605     addr2 = NULL;
606     size = 0;
607     status = pNtMapViewOfSection(hmap, GetCurrentProcess(), &addr2, 0, 0, &offset,
608                                  &size, 1 /* ViewShare */, 0, PAGE_READONLY);
609     /* FIXME: remove once Wine is fixed */
610     if (status != STATUS_IMAGE_NOT_AT_BASE)
611     {
612         todo_wine {
613         ok(status == STATUS_IMAGE_NOT_AT_BASE, "expected STATUS_IMAGE_NOT_AT_BASE, got %x\n", status);
614         ok(addr2 != 0, "mapped address should be valid\n");
615         }
616         goto wine_is_broken;
617     }
618     ok(status == STATUS_IMAGE_NOT_AT_BASE, "expected STATUS_IMAGE_NOT_AT_BASE, got %x\n", status);
619     ok(addr2 != 0, "mapped address should be valid\n");
620     ok(addr2 != addr1, "mapped addresses should be different\n");
621
622     SetLastError(0xdeadbeef);
623     size = VirtualQuery((char *)addr2 + section.VirtualAddress, &info, sizeof(info));
624     ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
625     ok(info.BaseAddress == (char *)addr2 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr2 + section.VirtualAddress);
626     ok(info.RegionSize == si.dwPageSize, "got %#lx != expected %#x\n", info.RegionSize, si.dwPageSize);
627     ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
628     ok(info.AllocationBase == addr2, "%p != %p\n", info.AllocationBase, addr2);
629     ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
630     ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
631     ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
632
633     status = pNtUnmapViewOfSection(GetCurrentProcess(), addr2);
634     ok(status == STATUS_SUCCESS, "NtUnmapViewOfSection error %x\n", status);
635
636     addr2 = MapViewOfFile(hmap, 0, 0, 0, 0);
637     ok(addr2 != 0, "mapped address should be valid\n");
638     ok(addr2 != addr1, "mapped addresses should be different\n");
639
640     SetLastError(0xdeadbeef);
641     size = VirtualQuery((char *)addr2 + section.VirtualAddress, &info, sizeof(info));
642     ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
643     ok(info.BaseAddress == (char *)addr2 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr2 + section.VirtualAddress);
644     ok(info.RegionSize == si.dwPageSize, "got %#lx != expected %#x\n", info.RegionSize, si.dwPageSize);
645     ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
646     ok(info.AllocationBase == addr2, "%p != %p\n", info.AllocationBase, addr2);
647     ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
648     ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
649     ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
650
651     UnmapViewOfFile(addr2);
652
653     SetLastError(0xdeadbeef);
654     addr2 = LoadLibrary(dll_name);
655     if (is_dll)
656     {
657         ok(!addr2, "LoadLibrary should fail, is_dll %d\n", is_dll);
658         ok(GetLastError() == ERROR_INVALID_ADDRESS, "expected ERROR_INVALID_ADDRESS, got %d\n", GetLastError());
659     }
660     else
661     {
662         BOOL ret;
663         ok(addr2 != 0, "LoadLibrary error %d, is_dll %d\n", GetLastError(), is_dll);
664         ok(addr2 != addr1, "mapped addresses should be different\n");
665
666         SetLastError(0xdeadbeef);
667         ret = FreeLibrary(addr2);
668         ok(ret, "FreeLibrary error %d\n", GetLastError());
669     }
670
671 wine_is_broken:
672     status = pNtUnmapViewOfSection(GetCurrentProcess(), addr1);
673     ok(status == STATUS_SUCCESS, "NtUnmapViewOfSection error %x\n", status);
674
675     CloseHandle(hmap);
676     CloseHandle(hfile);
677 }
678
679 static BOOL is_mem_writable(DWORD prot)
680 {
681     switch (prot & 0xff)
682     {
683         case PAGE_READWRITE:
684         case PAGE_WRITECOPY:
685         case PAGE_EXECUTE_READWRITE:
686         case PAGE_EXECUTE_WRITECOPY:
687             return TRUE;
688
689         default:
690             return FALSE;
691     }
692 }
693
694 static void test_VirtualProtect(void *base, void *section)
695 {
696     static const struct test_data
697     {
698         DWORD prot_set, prot_get;
699     } td[] =
700     {
701         { 0, 0 }, /* 0x00 */
702         { PAGE_NOACCESS, PAGE_NOACCESS }, /* 0x01 */
703         { PAGE_READONLY, PAGE_READONLY }, /* 0x02 */
704         { PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x03 */
705         { PAGE_READWRITE, PAGE_WRITECOPY }, /* 0x04 */
706         { PAGE_READWRITE | PAGE_NOACCESS, 0 }, /* 0x05 */
707         { PAGE_READWRITE | PAGE_READONLY, 0 }, /* 0x06 */
708         { PAGE_READWRITE | PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x07 */
709         { PAGE_WRITECOPY, PAGE_WRITECOPY }, /* 0x08 */
710         { PAGE_WRITECOPY | PAGE_NOACCESS, 0 }, /* 0x09 */
711         { PAGE_WRITECOPY | PAGE_READONLY, 0 }, /* 0x0a */
712         { PAGE_WRITECOPY | PAGE_NOACCESS | PAGE_READONLY, 0 }, /* 0x0b */
713         { PAGE_WRITECOPY | PAGE_READWRITE, 0 }, /* 0x0c */
714         { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_NOACCESS, 0 }, /* 0x0d */
715         { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_READONLY, 0 }, /* 0x0e */
716         { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x0f */
717
718         { PAGE_EXECUTE, PAGE_EXECUTE }, /* 0x10 */
719         { PAGE_EXECUTE_READ, PAGE_EXECUTE_READ }, /* 0x20 */
720         { PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0x30 */
721         { PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY }, /* 0x40 */
722         { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0x50 */
723         { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0x60 */
724         { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0x70 */
725         { PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_WRITECOPY }, /* 0x80 */
726         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE, 0 }, /* 0x90 */
727         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ, 0 }, /* 0xa0 */
728         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0xb0 */
729         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE, 0 }, /* 0xc0 */
730         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0xd0 */
731         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0xe0 */
732         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 } /* 0xf0 */
733     };
734     DWORD ret, orig_prot, old_prot, rw_prot, exec_prot, i, j;
735     MEMORY_BASIC_INFORMATION info;
736     SYSTEM_INFO si;
737
738     GetSystemInfo(&si);
739     trace("system page size %#x\n", si.dwPageSize);
740
741     SetLastError(0xdeadbeef);
742     ret = VirtualProtect(section, si.dwPageSize, PAGE_NOACCESS, &old_prot);
743     ok(ret, "VirtualProtect error %d\n", GetLastError());
744
745     orig_prot = old_prot;
746
747     for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
748     {
749         SetLastError(0xdeadbeef);
750         ret = VirtualQuery(section, &info, sizeof(info));
751         ok(ret, "VirtualQuery failed %d\n", GetLastError());
752         ok(info.BaseAddress == section, "%d: got %p != expected %p\n", i, info.BaseAddress, section);
753         ok(info.RegionSize == si.dwPageSize, "%d: got %#lx != expected %#x\n", i, info.RegionSize, si.dwPageSize);
754         ok(info.Protect == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, info.Protect);
755         ok(info.AllocationBase == base, "%d: %p != %p\n", i, info.AllocationBase, base);
756         ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
757         ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
758         ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
759
760         old_prot = 0xdeadbeef;
761         SetLastError(0xdeadbeef);
762         ret = VirtualProtect(section, si.dwPageSize, td[i].prot_set, &old_prot);
763         if (td[i].prot_get)
764         {
765             ok(ret, "%d: VirtualProtect error %d, requested prot %#x\n", i, GetLastError(), td[i].prot_set);
766             ok(old_prot == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, old_prot);
767
768             SetLastError(0xdeadbeef);
769             ret = VirtualQuery(section, &info, sizeof(info));
770             ok(ret, "VirtualQuery failed %d\n", GetLastError());
771             ok(info.BaseAddress == section, "%d: got %p != expected %p\n", i, info.BaseAddress, section);
772             ok(info.RegionSize == si.dwPageSize, "%d: got %#lx != expected %#x\n", i, info.RegionSize, si.dwPageSize);
773             ok(info.Protect == td[i].prot_get, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].prot_get);
774             ok(info.AllocationBase == base, "%d: %p != %p\n", i, info.AllocationBase, base);
775             ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
776             ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
777             ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
778         }
779         else
780         {
781             ok(!ret, "%d: VirtualProtect should fail\n", i);
782             ok(GetLastError() == ERROR_INVALID_PARAMETER, "%d: expected ERROR_INVALID_PARAMETER, got %d\n", i, GetLastError());
783         }
784
785         old_prot = 0xdeadbeef;
786         SetLastError(0xdeadbeef);
787         ret = VirtualProtect(section, si.dwPageSize, PAGE_NOACCESS, &old_prot);
788         ok(ret, "%d: VirtualProtect error %d\n", i, GetLastError());
789         if (td[i].prot_get)
790             ok(old_prot == td[i].prot_get, "%d: got %#x != expected %#x\n", i, old_prot, td[i].prot_get);
791         else
792             ok(old_prot == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, old_prot);
793     }
794
795     exec_prot = 0;
796
797     for (i = 0; i <= 4; i++)
798     {
799         rw_prot = 0;
800
801         for (j = 0; j <= 4; j++)
802         {
803             DWORD prot = exec_prot | rw_prot;
804
805             SetLastError(0xdeadbeef);
806             ret = VirtualProtect(section, si.dwPageSize, prot, &old_prot);
807             if ((rw_prot && exec_prot) || (!rw_prot && !exec_prot))
808             {
809                 ok(!ret, "VirtualProtect(%02x) should fail\n", prot);
810                 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
811             }
812             else
813                 ok(ret, "VirtualProtect(%02x) error %d\n", prot, GetLastError());
814
815             rw_prot = 1 << j;
816         }
817
818         exec_prot = 1 << (i + 4);
819     }
820
821     SetLastError(0xdeadbeef);
822     ret = VirtualProtect(section, si.dwPageSize, orig_prot, &old_prot);
823     ok(ret, "VirtualProtect error %d\n", GetLastError());
824 }
825
826 static void test_section_access(void)
827 {
828     static const struct test_data
829     {
830         DWORD scn_file_access, scn_page_access, scn_page_access_after_write;
831     } td[] =
832     {
833         { 0, PAGE_NOACCESS, 0 },
834         { IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
835         { IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
836         { IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
837         { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
838         { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ },
839         { IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
840         { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
841
842         { IMAGE_SCN_CNT_INITIALIZED_DATA, PAGE_NOACCESS, 0 },
843         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
844         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
845         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
846         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
847         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ, 0 },
848         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
849         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
850
851         { IMAGE_SCN_CNT_UNINITIALIZED_DATA, PAGE_NOACCESS, 0 },
852         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
853         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
854         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
855         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
856         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ, 0 },
857         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
858         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE }
859     };
860     static const char filler[0x1000];
861     static const char section_data[0x10] = "section data";
862     char buf[256];
863     int i;
864     DWORD dummy, file_align;
865     HANDLE hfile;
866     HMODULE hlib;
867     SYSTEM_INFO si;
868     char temp_path[MAX_PATH];
869     char dll_name[MAX_PATH];
870     SIZE_T size;
871     MEMORY_BASIC_INFORMATION info;
872     STARTUPINFO sti;
873     PROCESS_INFORMATION pi;
874     DWORD ret;
875
876     GetSystemInfo(&si);
877     trace("system page size %#x\n", si.dwPageSize);
878
879     /* prevent displaying of the "Unable to load this DLL" message box */
880     SetErrorMode(SEM_FAILCRITICALERRORS);
881
882     GetTempPath(MAX_PATH, temp_path);
883
884     for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
885     {
886         GetTempFileName(temp_path, "ldr", 0, dll_name);
887
888         /*trace("creating %s\n", dll_name);*/
889         hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
890         if (hfile == INVALID_HANDLE_VALUE)
891         {
892             ok(0, "could not create %s\n", dll_name);
893             return;
894         }
895
896         SetLastError(0xdeadbeef);
897         ret = WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
898         ok(ret, "WriteFile error %d\n", GetLastError());
899
900         nt_header.FileHeader.NumberOfSections = 1;
901         nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
902         nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_RELOCS_STRIPPED;
903
904         nt_header.OptionalHeader.SectionAlignment = si.dwPageSize;
905         nt_header.OptionalHeader.FileAlignment = 0x200;
906         nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + si.dwPageSize;
907         nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
908         SetLastError(0xdeadbeef);
909         ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
910         ok(ret, "WriteFile error %d\n", GetLastError());
911         SetLastError(0xdeadbeef);
912         ret = WriteFile(hfile, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
913         ok(ret, "WriteFile error %d\n", GetLastError());
914
915         section.SizeOfRawData = sizeof(section_data);
916         section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
917         section.VirtualAddress = nt_header.OptionalHeader.SectionAlignment;
918         section.Misc.VirtualSize = section.SizeOfRawData;
919         section.Characteristics = td[i].scn_file_access;
920         SetLastError(0xdeadbeef);
921         ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
922         ok(ret, "WriteFile error %d\n", GetLastError());
923
924         file_align = nt_header.OptionalHeader.FileAlignment - nt_header.OptionalHeader.SizeOfHeaders;
925         assert(file_align < sizeof(filler));
926         SetLastError(0xdeadbeef);
927         ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
928         ok(ret, "WriteFile error %d\n", GetLastError());
929
930         /* section data */
931         SetLastError(0xdeadbeef);
932         ret = WriteFile(hfile, section_data, sizeof(section_data), &dummy, NULL);
933         ok(ret, "WriteFile error %d\n", GetLastError());
934
935         CloseHandle(hfile);
936
937         SetLastError(0xdeadbeef);
938         hlib = LoadLibrary(dll_name);
939         ok(hlib != 0, "LoadLibrary error %d\n", GetLastError());
940
941         SetLastError(0xdeadbeef);
942         size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
943         ok(size == sizeof(info),
944             "%d: VirtualQuery error %d\n", i, GetLastError());
945         ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
946         ok(info.RegionSize == si.dwPageSize, "%d: got %#lx != expected %#x\n", i, info.RegionSize, si.dwPageSize);
947         ok(info.Protect == td[i].scn_page_access, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access);
948         ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
949         ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
950         ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
951         ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
952         if (info.Protect != PAGE_NOACCESS)
953             ok(!memcmp((const char *)info.BaseAddress, section_data, section.SizeOfRawData), "wrong section data\n");
954
955         test_VirtualProtect(hlib, (char *)hlib + section.VirtualAddress);
956
957         /* Windows changes the WRITECOPY to WRITE protection on an image section write (for a changed page only) */
958         if (is_mem_writable(info.Protect))
959         {
960             char *p = info.BaseAddress;
961             *p = 0xfe;
962             SetLastError(0xdeadbeef);
963             size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
964             ok(size == sizeof(info), "%d: VirtualQuery error %d\n", i, GetLastError());
965             /* FIXME: remove the condition below once Wine is fixed */
966             if (info.Protect == PAGE_WRITECOPY || info.Protect == PAGE_EXECUTE_WRITECOPY)
967                 todo_wine ok(info.Protect == td[i].scn_page_access_after_write, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access_after_write);
968             else
969                 ok(info.Protect == td[i].scn_page_access_after_write, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access_after_write);
970         }
971
972         SetLastError(0xdeadbeef);
973         ret = FreeLibrary(hlib);
974         ok(ret, "FreeLibrary error %d\n", GetLastError());
975
976         test_image_mapping(dll_name, td[i].scn_page_access, TRUE);
977
978         /* reset IMAGE_FILE_DLL otherwise CreateProcess fails */
979         nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_RELOCS_STRIPPED;
980         SetLastError(0xdeadbeef);
981         hfile = CreateFile(dll_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
982         /* LoadLibrary called on an already memory-mapped file in
983          * test_image_mapping() above leads to a file handle leak
984          * under nt4, and inability to overwrite and delete the file
985          * due to sharing violation error. Ignore it and skip the test,
986          * but leave a not deletable temporary file.
987          */
988         ok(hfile != INVALID_HANDLE_VALUE || broken(hfile == INVALID_HANDLE_VALUE) /* nt4 */,
989             "CreateFile error %d\n", GetLastError());
990         if (hfile == INVALID_HANDLE_VALUE) goto nt4_is_broken;
991         SetFilePointer(hfile, sizeof(dos_header), NULL, FILE_BEGIN);
992         SetLastError(0xdeadbeef);
993         ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
994         ok(ret, "WriteFile error %d\n", GetLastError());
995         CloseHandle(hfile);
996
997         memset(&sti, 0, sizeof(sti));
998         sti.cb = sizeof(sti);
999         SetLastError(0xdeadbeef);
1000         ret = CreateProcess(dll_name, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &sti, &pi);
1001         ok(ret, "CreateProcess() error %d\n", GetLastError());
1002
1003         SetLastError(0xdeadbeef);
1004         size = VirtualQueryEx(pi.hProcess, (char *)hlib + section.VirtualAddress, &info, sizeof(info));
1005         ok(size == sizeof(info),
1006             "%d: VirtualQuery error %d\n", i, GetLastError());
1007         ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
1008         ok(info.RegionSize == si.dwPageSize, "%d: got %#lx != expected %#x\n", i, info.RegionSize, si.dwPageSize);
1009         ok(info.Protect == td[i].scn_page_access, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access);
1010         ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
1011         ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1012         ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1013         ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1014         if (info.Protect != PAGE_NOACCESS)
1015         {
1016             SetLastError(0xdeadbeef);
1017             ret = ReadProcessMemory(pi.hProcess, info.BaseAddress, buf, section.SizeOfRawData, NULL);
1018             ok(ret, "ReadProcessMemory() error %d\n", GetLastError());
1019             ok(!memcmp(buf, section_data, section.SizeOfRawData), "wrong section data\n");
1020         }
1021
1022         SetLastError(0xdeadbeef);
1023         ret = TerminateProcess(pi.hProcess, 0);
1024         ok(ret, "TerminateProcess() error %d\n", GetLastError());
1025         ret = WaitForSingleObject(pi.hProcess, 3000);
1026         ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
1027
1028         CloseHandle(pi.hThread);
1029         CloseHandle(pi.hProcess);
1030
1031         test_image_mapping(dll_name, td[i].scn_page_access, FALSE);
1032
1033 nt4_is_broken:
1034         SetLastError(0xdeadbeef);
1035         ret = DeleteFile(dll_name);
1036         ok(ret || broken(!ret) /* nt4 */, "DeleteFile error %d\n", GetLastError());
1037     }
1038 }
1039
1040 START_TEST(loader)
1041 {
1042     pNtMapViewOfSection = (void *)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtMapViewOfSection");
1043     pNtUnmapViewOfSection = (void *)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtUnmapViewOfSection");
1044
1045     test_Loader();
1046     test_ImportDescriptors();
1047     test_section_access();
1048 }