ntdll: Implement the SectionBasicInformation class of NtQuerySection.
[wine.git] / dlls / kernel32 / tests / loader.c
blob7dcc1af92931d5dbc1d15d3555f9175c29bcfb47
1 /*
2 * Unit test suite for the PE loader.
4 * Copyright 2006,2011 Dmitry Timoshkov
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.
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.
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
21 #define NONAMELESSUNION
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <assert.h>
26 #include "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winternl.h"
31 #include "wine/test.h"
32 #include "delayloadhandler.h"
34 /* PROCESS_ALL_ACCESS in Vista+ PSDKs is incompatible with older Windows versions */
35 #define PROCESS_ALL_ACCESS_NT4 (PROCESS_ALL_ACCESS & ~0xf000)
37 #define ALIGN_SIZE(size, alignment) (((size) + (alignment - 1)) & ~((alignment - 1)))
39 struct PROCESS_BASIC_INFORMATION_PRIVATE
41 DWORD_PTR ExitStatus;
42 PPEB PebBaseAddress;
43 DWORD_PTR AffinityMask;
44 DWORD_PTR BasePriority;
45 ULONG_PTR UniqueProcessId;
46 ULONG_PTR InheritedFromUniqueProcessId;
49 static LONG *child_failures;
50 static WORD cb_count;
51 static DWORD page_size;
53 static NTSTATUS (WINAPI *pNtCreateSection)(HANDLE *, ACCESS_MASK, const OBJECT_ATTRIBUTES *,
54 const LARGE_INTEGER *, ULONG, ULONG, HANDLE );
55 static NTSTATUS (WINAPI *pNtQuerySection)(HANDLE, SECTION_INFORMATION_CLASS, void *, ULONG, ULONG *);
56 static NTSTATUS (WINAPI *pNtMapViewOfSection)(HANDLE, HANDLE, PVOID *, ULONG, SIZE_T, const LARGE_INTEGER *, SIZE_T *, ULONG, ULONG, ULONG);
57 static NTSTATUS (WINAPI *pNtUnmapViewOfSection)(HANDLE, PVOID);
58 static NTSTATUS (WINAPI *pNtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
59 static NTSTATUS (WINAPI *pNtSetInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG);
60 static NTSTATUS (WINAPI *pNtTerminateProcess)(HANDLE, DWORD);
61 static void (WINAPI *pLdrShutdownProcess)(void);
62 static BOOLEAN (WINAPI *pRtlDllShutdownInProgress)(void);
63 static NTSTATUS (WINAPI *pNtAllocateVirtualMemory)(HANDLE, PVOID *, ULONG, SIZE_T *, ULONG, ULONG);
64 static NTSTATUS (WINAPI *pNtFreeVirtualMemory)(HANDLE, PVOID *, SIZE_T *, ULONG);
65 static NTSTATUS (WINAPI *pLdrLockLoaderLock)(ULONG, ULONG *, ULONG_PTR *);
66 static NTSTATUS (WINAPI *pLdrUnlockLoaderLock)(ULONG, ULONG_PTR);
67 static void (WINAPI *pRtlAcquirePebLock)(void);
68 static void (WINAPI *pRtlReleasePebLock)(void);
69 static PVOID (WINAPI *pResolveDelayLoadedAPI)(PVOID, PCIMAGE_DELAYLOAD_DESCRIPTOR,
70 PDELAYLOAD_FAILURE_DLL_CALLBACK, PVOID,
71 PIMAGE_THUNK_DATA ThunkAddress,ULONG);
72 static PVOID (WINAPI *pRtlImageDirectoryEntryToData)(HMODULE,BOOL,WORD,ULONG *);
74 static PVOID RVAToAddr(DWORD_PTR rva, HMODULE module)
76 if (rva == 0)
77 return NULL;
78 return ((char*) module) + rva;
81 static IMAGE_DOS_HEADER dos_header;
83 static const IMAGE_NT_HEADERS nt_header_template =
85 IMAGE_NT_SIGNATURE, /* Signature */
87 #if defined __i386__
88 IMAGE_FILE_MACHINE_I386, /* Machine */
89 #elif defined __x86_64__
90 IMAGE_FILE_MACHINE_AMD64, /* Machine */
91 #elif defined __powerpc__
92 IMAGE_FILE_MACHINE_POWERPC, /* Machine */
93 #elif defined __arm__
94 IMAGE_FILE_MACHINE_ARMNT, /* Machine */
95 #elif defined __aarch64__
96 IMAGE_FILE_MACHINE_ARM64, /* Machine */
97 #else
98 # error You must specify the machine type
99 #endif
100 1, /* NumberOfSections */
101 0, /* TimeDateStamp */
102 0, /* PointerToSymbolTable */
103 0, /* NumberOfSymbols */
104 sizeof(IMAGE_OPTIONAL_HEADER), /* SizeOfOptionalHeader */
105 IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL /* Characteristics */
107 { IMAGE_NT_OPTIONAL_HDR_MAGIC, /* Magic */
108 1, /* MajorLinkerVersion */
109 0, /* MinorLinkerVersion */
110 0, /* SizeOfCode */
111 0, /* SizeOfInitializedData */
112 0, /* SizeOfUninitializedData */
113 0, /* AddressOfEntryPoint */
114 0x10, /* BaseOfCode, also serves as e_lfanew in the truncated MZ header */
115 #ifndef _WIN64
116 0, /* BaseOfData */
117 #endif
118 0x10000000, /* ImageBase */
119 0, /* SectionAlignment */
120 0, /* FileAlignment */
121 4, /* MajorOperatingSystemVersion */
122 0, /* MinorOperatingSystemVersion */
123 1, /* MajorImageVersion */
124 0, /* MinorImageVersion */
125 4, /* MajorSubsystemVersion */
126 0, /* MinorSubsystemVersion */
127 0, /* Win32VersionValue */
128 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000, /* SizeOfImage */
129 sizeof(dos_header) + sizeof(nt_header_template), /* SizeOfHeaders */
130 0, /* CheckSum */
131 IMAGE_SUBSYSTEM_WINDOWS_CUI, /* Subsystem */
132 0, /* DllCharacteristics */
133 0, /* SizeOfStackReserve */
134 0, /* SizeOfStackCommit */
135 0, /* SizeOfHeapReserve */
136 0, /* SizeOfHeapCommit */
137 0, /* LoaderFlags */
138 0, /* NumberOfRvaAndSizes */
139 { { 0 } } /* DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] */
143 static IMAGE_SECTION_HEADER section =
145 ".rodata", /* Name */
146 { 0x10 }, /* Misc */
147 0, /* VirtualAddress */
148 0x0a, /* SizeOfRawData */
149 0, /* PointerToRawData */
150 0, /* PointerToRelocations */
151 0, /* PointerToLinenumbers */
152 0, /* NumberOfRelocations */
153 0, /* NumberOfLinenumbers */
154 IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, /* Characteristics */
158 static const char filler[0x1000];
159 static const char section_data[0x10] = "section data";
161 static DWORD create_test_dll( const IMAGE_DOS_HEADER *dos_header, UINT dos_size,
162 const IMAGE_NT_HEADERS *nt_header, const char *dll_name )
164 DWORD dummy, size, file_align;
165 HANDLE hfile;
166 BOOL ret;
168 hfile = CreateFileA(dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0);
169 if (hfile == INVALID_HANDLE_VALUE) return 0;
171 SetLastError(0xdeadbeef);
172 ret = WriteFile(hfile, dos_header, dos_size, &dummy, NULL);
173 ok(ret, "WriteFile error %d\n", GetLastError());
175 SetLastError(0xdeadbeef);
176 ret = WriteFile(hfile, nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
177 ok(ret, "WriteFile error %d\n", GetLastError());
179 if (nt_header->FileHeader.SizeOfOptionalHeader)
181 SetLastError(0xdeadbeef);
182 ret = WriteFile(hfile, &nt_header->OptionalHeader,
183 min(nt_header->FileHeader.SizeOfOptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER)),
184 &dummy, NULL);
185 ok(ret, "WriteFile error %d\n", GetLastError());
186 if (nt_header->FileHeader.SizeOfOptionalHeader > sizeof(IMAGE_OPTIONAL_HEADER))
188 file_align = nt_header->FileHeader.SizeOfOptionalHeader - sizeof(IMAGE_OPTIONAL_HEADER);
189 assert(file_align < sizeof(filler));
190 SetLastError(0xdeadbeef);
191 ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
192 ok(ret, "WriteFile error %d\n", GetLastError());
196 assert(nt_header->FileHeader.NumberOfSections <= 1);
197 if (nt_header->FileHeader.NumberOfSections)
199 if (nt_header->OptionalHeader.SectionAlignment >= page_size)
201 section.PointerToRawData = dos_size;
202 section.VirtualAddress = nt_header->OptionalHeader.SectionAlignment;
203 section.Misc.VirtualSize = section.SizeOfRawData * 10;
205 else
207 section.PointerToRawData = nt_header->OptionalHeader.SizeOfHeaders;
208 section.VirtualAddress = nt_header->OptionalHeader.SizeOfHeaders;
209 section.Misc.VirtualSize = 5;
212 SetLastError(0xdeadbeef);
213 ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
214 ok(ret, "WriteFile error %d\n", GetLastError());
216 /* section data */
217 SetLastError(0xdeadbeef);
218 ret = WriteFile(hfile, section_data, sizeof(section_data), &dummy, NULL);
219 ok(ret, "WriteFile error %d\n", GetLastError());
221 size = GetFileSize(hfile, NULL);
222 CloseHandle(hfile);
223 return size;
226 /* helper to test image section mapping */
227 static NTSTATUS map_image_section( const IMAGE_NT_HEADERS *nt_header )
229 char temp_path[MAX_PATH];
230 char dll_name[MAX_PATH];
231 LARGE_INTEGER size;
232 HANDLE file, map;
233 NTSTATUS status;
235 GetTempPathA(MAX_PATH, temp_path);
236 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
238 size.u.LowPart = create_test_dll( &dos_header, sizeof(dos_header), nt_header, dll_name );
239 ok( size.u.LowPart, "could not create %s\n", dll_name);
240 size.u.HighPart = 0;
242 file = CreateFileA(dll_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
243 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
245 status = pNtCreateSection(&map, STANDARD_RIGHTS_REQUIRED | SECTION_MAP_READ | SECTION_QUERY,
246 NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
247 if (!status)
249 SECTION_BASIC_INFORMATION info;
250 ULONG info_size = 0xdeadbeef;
251 NTSTATUS ret = pNtQuerySection( map, SectionBasicInformation, &info, sizeof(info), &info_size );
252 ok( !ret, "NtQuerySection failed err %x\n", ret );
253 ok( info_size == sizeof(info), "NtQuerySection wrong size %u\n", info_size );
254 ok( info.Attributes == (SEC_IMAGE | SEC_FILE), "NtQuerySection wrong attr %x\n", info.Attributes );
255 ok( info.BaseAddress == NULL, "NtQuerySection wrong base %p\n", info.BaseAddress );
256 todo_wine
257 ok( info.Size.QuadPart == size.QuadPart, "NtQuerySection wrong size %x%08x / %x%08x\n",
258 info.Size.u.HighPart, info.Size.u.LowPart, size.u.HighPart, size.u.LowPart );
260 if (map) CloseHandle( map );
261 CloseHandle( file );
262 DeleteFileA( dll_name );
263 return status;
267 static void test_Loader(void)
269 static const struct test_data
271 DWORD size_of_dos_header;
272 WORD number_of_sections, size_of_optional_header;
273 DWORD section_alignment, file_alignment;
274 DWORD size_of_image, size_of_headers;
275 DWORD errors[4]; /* 0 means LoadLibrary should succeed */
276 } td[] =
278 { sizeof(dos_header),
279 1, 0, 0, 0, 0, 0,
280 { ERROR_BAD_EXE_FORMAT }
282 { sizeof(dos_header),
283 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
284 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0xe00,
285 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
286 { ERROR_BAD_EXE_FORMAT } /* XP doesn't like too small image size */
288 { sizeof(dos_header),
289 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
290 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
291 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
292 { ERROR_SUCCESS }
294 { sizeof(dos_header),
295 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
296 0x1f00,
297 0x1000,
298 { ERROR_SUCCESS }
300 { sizeof(dos_header),
301 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x200, 0x200,
302 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x200,
303 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
304 { ERROR_SUCCESS, ERROR_INVALID_ADDRESS } /* vista is more strict */
306 { sizeof(dos_header),
307 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x200, 0x1000,
308 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
309 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
310 { ERROR_BAD_EXE_FORMAT } /* XP doesn't like alignments */
312 { sizeof(dos_header),
313 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x200,
314 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
315 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
316 { ERROR_SUCCESS }
318 { sizeof(dos_header),
319 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x200,
320 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
321 0x200,
322 { ERROR_SUCCESS }
324 /* Mandatory are all fields up to SizeOfHeaders, everything else
325 * is really optional (at least that's true for XP).
327 { sizeof(dos_header),
328 1, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
329 sizeof(dos_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum) + sizeof(IMAGE_SECTION_HEADER) + 0x10,
330 sizeof(dos_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum) + sizeof(IMAGE_SECTION_HEADER),
331 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT, ERROR_INVALID_ADDRESS,
332 ERROR_NOACCESS }
334 { sizeof(dos_header),
335 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
336 0xd0, /* beyond of the end of file */
337 0xc0, /* beyond of the end of file */
338 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
340 { sizeof(dos_header),
341 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
342 0x1000,
344 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
346 { sizeof(dos_header),
347 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
350 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
352 #if 0 /* not power of 2 alignments need more test cases */
353 { sizeof(dos_header),
354 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x300, 0x300,
357 { ERROR_BAD_EXE_FORMAT } /* alignment is not power of 2 */
359 #endif
360 { sizeof(dos_header),
361 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 4, 4,
364 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
366 { sizeof(dos_header),
367 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 1, 1,
370 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
372 { sizeof(dos_header),
373 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
376 { ERROR_BAD_EXE_FORMAT } /* image size == 0 -> failure */
378 /* the following data mimics the PE image which upack creates */
379 { 0x10,
380 1, 0x148, 0x1000, 0x200,
381 sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
382 0x200,
383 { ERROR_SUCCESS }
385 /* Minimal PE image that XP is able to load: 92 bytes */
386 { 0x04,
387 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum),
388 0x04 /* also serves as e_lfanew in the truncated MZ header */, 0x04,
391 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
393 /* Minimal PE image that Windows7 is able to load: 268 bytes */
394 { 0x04,
395 0, 0xf0, /* optional header size just forces 0xf0 bytes to be written,
396 0 or another number don't change the behaviour, what really
397 matters is file size regardless of values in the headers */
398 0x04 /* also serves as e_lfanew in the truncated MZ header */, 0x04,
399 0x40, /* minimal image size that Windows7 accepts */
401 { ERROR_SUCCESS }
404 int i;
405 DWORD file_size;
406 HMODULE hlib, hlib_as_data_file;
407 char temp_path[MAX_PATH];
408 char dll_name[MAX_PATH];
409 SIZE_T size;
410 BOOL ret;
411 NTSTATUS status;
412 WORD orig_machine = nt_header_template.FileHeader.Machine;
413 IMAGE_NT_HEADERS nt_header;
415 /* prevent displaying of the "Unable to load this DLL" message box */
416 SetErrorMode(SEM_FAILCRITICALERRORS);
418 GetTempPathA(MAX_PATH, temp_path);
420 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
422 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
424 nt_header = nt_header_template;
425 nt_header.FileHeader.NumberOfSections = td[i].number_of_sections;
426 nt_header.FileHeader.SizeOfOptionalHeader = td[i].size_of_optional_header;
428 nt_header.OptionalHeader.SectionAlignment = td[i].section_alignment;
429 nt_header.OptionalHeader.FileAlignment = td[i].file_alignment;
430 nt_header.OptionalHeader.SizeOfImage = td[i].size_of_image;
431 nt_header.OptionalHeader.SizeOfHeaders = td[i].size_of_headers;
433 file_size = create_test_dll( &dos_header, td[i].size_of_dos_header, &nt_header, dll_name );
434 if (!file_size)
436 ok(0, "could not create %s\n", dll_name);
437 break;
440 SetLastError(0xdeadbeef);
441 hlib = LoadLibraryA(dll_name);
442 if (hlib)
444 MEMORY_BASIC_INFORMATION info;
445 void *ptr;
447 ok( td[i].errors[0] == ERROR_SUCCESS, "%d: should have failed\n", i );
449 SetLastError(0xdeadbeef);
450 size = VirtualQuery(hlib, &info, sizeof(info));
451 ok(size == sizeof(info),
452 "%d: VirtualQuery error %d\n", i, GetLastError());
453 ok(info.BaseAddress == hlib, "%d: %p != %p\n", i, info.BaseAddress, hlib);
454 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
455 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
456 ok(info.RegionSize == ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %lx != expected %x\n",
457 i, info.RegionSize, ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
458 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
459 if (nt_header.OptionalHeader.SectionAlignment < page_size)
460 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
461 else
462 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
463 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
465 SetLastError(0xdeadbeef);
466 ptr = VirtualAlloc(hlib, page_size, MEM_COMMIT, info.Protect);
467 ok(!ptr, "%d: VirtualAlloc should fail\n", i);
468 /* FIXME: Remove once Wine is fixed */
469 todo_wine_if (info.Protect == PAGE_WRITECOPY || info.Protect == PAGE_EXECUTE_WRITECOPY)
470 ok(GetLastError() == ERROR_ACCESS_DENIED, "%d: expected ERROR_ACCESS_DENIED, got %d\n", i, GetLastError());
472 SetLastError(0xdeadbeef);
473 size = VirtualQuery((char *)hlib + info.RegionSize, &info, sizeof(info));
474 ok(size == sizeof(info),
475 "%d: VirtualQuery error %d\n", i, GetLastError());
476 if (nt_header.OptionalHeader.SectionAlignment == page_size ||
477 nt_header.OptionalHeader.SectionAlignment == nt_header.OptionalHeader.FileAlignment)
479 ok(info.BaseAddress == (char *)hlib + ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %p != expected %p\n",
480 i, info.BaseAddress, (char *)hlib + ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
481 ok(info.AllocationBase == 0, "%d: %p != 0\n", i, info.AllocationBase);
482 ok(info.AllocationProtect == 0, "%d: %x != 0\n", i, info.AllocationProtect);
483 /*ok(info.RegionSize == not_practical_value, "%d: %lx != not_practical_value\n", i, info.RegionSize);*/
484 ok(info.State == MEM_FREE, "%d: %x != MEM_FREE\n", i, info.State);
485 ok(info.Type == 0, "%d: %x != 0\n", i, info.Type);
486 ok(info.Protect == PAGE_NOACCESS, "%d: %x != PAGE_NOACCESS\n", i, info.Protect);
488 else
490 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
491 ok(info.BaseAddress == hlib, "%d: got %p != expected %p\n", i, info.BaseAddress, hlib);
492 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
493 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
494 ok(info.RegionSize == ALIGN_SIZE(file_size, page_size), "%d: got %lx != expected %x\n",
495 i, info.RegionSize, ALIGN_SIZE(file_size, page_size));
496 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
497 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
498 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
501 /* header: check the zeroing of alignment */
502 if (nt_header.OptionalHeader.SectionAlignment >= page_size)
504 const char *start;
506 start = (const char *)hlib + nt_header.OptionalHeader.SizeOfHeaders;
507 size = ALIGN_SIZE((ULONG_PTR)start, page_size) - (ULONG_PTR)start;
508 ok(!memcmp(start, filler, size), "%d: header alignment is not cleared\n", i);
511 if (nt_header.FileHeader.NumberOfSections)
513 SetLastError(0xdeadbeef);
514 size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
515 ok(size == sizeof(info),
516 "%d: VirtualQuery error %d\n", i, GetLastError());
517 if (nt_header.OptionalHeader.SectionAlignment < page_size)
519 ok(info.BaseAddress == hlib, "%d: got %p != expected %p\n", i, info.BaseAddress, hlib);
520 ok(info.RegionSize == ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %lx != expected %x\n",
521 i, info.RegionSize, ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
522 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
524 else
526 ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
527 ok(info.RegionSize == ALIGN_SIZE(section.Misc.VirtualSize, page_size), "%d: got %lx != expected %x\n",
528 i, info.RegionSize, ALIGN_SIZE(section.Misc.VirtualSize, page_size));
529 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
531 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
532 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
533 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
534 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
536 if (nt_header.OptionalHeader.SectionAlignment >= page_size)
537 ok(!memcmp((const char *)hlib + section.VirtualAddress + section.PointerToRawData, &nt_header, section.SizeOfRawData), "wrong section data\n");
538 else
539 ok(!memcmp((const char *)hlib + section.PointerToRawData, section_data, section.SizeOfRawData), "wrong section data\n");
541 /* check the zeroing of alignment */
542 if (nt_header.OptionalHeader.SectionAlignment >= page_size)
544 const char *start;
546 start = (const char *)hlib + section.VirtualAddress + section.PointerToRawData + section.SizeOfRawData;
547 size = ALIGN_SIZE((ULONG_PTR)start, page_size) - (ULONG_PTR)start;
548 ok(memcmp(start, filler, size), "%d: alignment should not be cleared\n", i);
551 SetLastError(0xdeadbeef);
552 ptr = VirtualAlloc((char *)hlib + section.VirtualAddress, page_size, MEM_COMMIT, info.Protect);
553 ok(!ptr, "%d: VirtualAlloc should fail\n", i);
554 /* FIXME: Remove once Wine is fixed */
555 todo_wine_if (info.Protect == PAGE_WRITECOPY || info.Protect == PAGE_EXECUTE_WRITECOPY)
556 ok(GetLastError() == ERROR_ACCESS_DENIED || GetLastError() == ERROR_INVALID_ADDRESS,
557 "%d: expected ERROR_ACCESS_DENIED, got %d\n", i, GetLastError());
560 SetLastError(0xdeadbeef);
561 hlib_as_data_file = LoadLibraryExA(dll_name, 0, LOAD_LIBRARY_AS_DATAFILE);
562 ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
563 ok(hlib_as_data_file == hlib, "hlib_as_file and hlib are different\n");
565 SetLastError(0xdeadbeef);
566 ret = FreeLibrary(hlib);
567 ok(ret, "FreeLibrary error %d\n", GetLastError());
569 SetLastError(0xdeadbeef);
570 hlib = GetModuleHandleA(dll_name);
571 ok(hlib != 0, "GetModuleHandle error %u\n", GetLastError());
573 SetLastError(0xdeadbeef);
574 ret = FreeLibrary(hlib_as_data_file);
575 ok(ret, "FreeLibrary error %d\n", GetLastError());
577 hlib = GetModuleHandleA(dll_name);
578 ok(!hlib, "GetModuleHandle should fail\n");
580 SetLastError(0xdeadbeef);
581 hlib_as_data_file = LoadLibraryExA(dll_name, 0, LOAD_LIBRARY_AS_DATAFILE);
582 ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
583 ok((ULONG_PTR)hlib_as_data_file & 1, "hlib_as_data_file is even\n");
585 hlib = GetModuleHandleA(dll_name);
586 ok(!hlib, "GetModuleHandle should fail\n");
588 SetLastError(0xdeadbeef);
589 ret = FreeLibrary(hlib_as_data_file);
590 ok(ret, "FreeLibrary error %d\n", GetLastError());
592 else
594 BOOL error_match;
595 int error_index;
597 error_match = FALSE;
598 for (error_index = 0;
599 ! error_match && error_index < sizeof(td[i].errors) / sizeof(DWORD);
600 error_index++)
602 error_match = td[i].errors[error_index] == GetLastError();
604 ok(error_match, "%d: unexpected error %d\n", i, GetLastError());
607 SetLastError(0xdeadbeef);
608 ret = DeleteFileA(dll_name);
609 ok(ret, "DeleteFile error %d\n", GetLastError());
612 nt_header = nt_header_template;
613 nt_header.FileHeader.NumberOfSections = 1;
614 nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
616 nt_header.OptionalHeader.SectionAlignment = page_size;
617 nt_header.OptionalHeader.FileAlignment = page_size;
618 nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
619 nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + page_size;
621 status = map_image_section( &nt_header );
622 ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
624 dos_header.e_magic = 0;
625 status = map_image_section( &nt_header );
626 ok( status == STATUS_INVALID_IMAGE_NOT_MZ, "NtCreateSection error %08x\n", status );
628 dos_header.e_magic = IMAGE_DOS_SIGNATURE;
629 nt_header.Signature = IMAGE_OS2_SIGNATURE;
630 status = map_image_section( &nt_header );
631 ok( status == STATUS_INVALID_IMAGE_NE_FORMAT, "NtCreateSection error %08x\n", status );
633 nt_header.Signature = 0xdeadbeef;
634 status = map_image_section( &nt_header );
635 ok( status == STATUS_INVALID_IMAGE_PROTECT, "NtCreateSection error %08x\n", status );
637 nt_header.Signature = IMAGE_NT_SIGNATURE;
638 nt_header.OptionalHeader.Magic = 0xdead;
639 status = map_image_section( &nt_header );
640 ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
642 nt_header.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
643 nt_header.FileHeader.Machine = 0xdead;
644 status = map_image_section( &nt_header );
645 ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
646 "NtCreateSection error %08x\n", status );
648 nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_UNKNOWN;
649 status = map_image_section( &nt_header );
650 ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
651 "NtCreateSection error %08x\n", status );
653 switch (orig_machine)
655 case IMAGE_FILE_MACHINE_I386: nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; break;
656 case IMAGE_FILE_MACHINE_AMD64: nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_I386; break;
657 case IMAGE_FILE_MACHINE_ARMNT: nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_ARM64; break;
658 case IMAGE_FILE_MACHINE_ARM64: nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_ARMNT; break;
660 status = map_image_section( &nt_header );
661 ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
662 "NtCreateSection error %08x\n", status );
664 if (nt_header.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
666 IMAGE_NT_HEADERS64 nt64;
668 memset( &nt64, 0, sizeof(nt64) );
669 nt64.Signature = IMAGE_NT_SIGNATURE;
670 nt64.FileHeader.Machine = orig_machine;
671 nt64.FileHeader.NumberOfSections = 1;
672 nt64.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
673 nt64.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
674 nt64.OptionalHeader.MajorLinkerVersion = 1;
675 nt64.OptionalHeader.ImageBase = 0x10000000;
676 nt64.OptionalHeader.MajorOperatingSystemVersion = 4;
677 nt64.OptionalHeader.MajorImageVersion = 1;
678 nt64.OptionalHeader.MajorSubsystemVersion = 4;
679 nt64.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt64) + sizeof(IMAGE_SECTION_HEADER);
680 nt64.OptionalHeader.SizeOfImage = nt64.OptionalHeader.SizeOfHeaders + 0x1000;
681 nt64.OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
682 status = map_image_section( (IMAGE_NT_HEADERS *)&nt64 );
683 ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
685 else
687 IMAGE_NT_HEADERS32 nt32;
689 memset( &nt32, 0, sizeof(nt32) );
690 nt32.Signature = IMAGE_NT_SIGNATURE;
691 nt32.FileHeader.Machine = orig_machine;
692 nt32.FileHeader.NumberOfSections = 1;
693 nt32.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER32);
694 nt32.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC;
695 nt32.OptionalHeader.MajorLinkerVersion = 1;
696 nt32.OptionalHeader.ImageBase = 0x10000000;
697 nt32.OptionalHeader.MajorOperatingSystemVersion = 4;
698 nt32.OptionalHeader.MajorImageVersion = 1;
699 nt32.OptionalHeader.MajorSubsystemVersion = 4;
700 nt32.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt32) + sizeof(IMAGE_SECTION_HEADER);
701 nt32.OptionalHeader.SizeOfImage = nt32.OptionalHeader.SizeOfHeaders + 0x1000;
702 nt32.OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
703 status = map_image_section( (IMAGE_NT_HEADERS *)&nt32 );
704 ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
707 nt_header.FileHeader.Machine = orig_machine; /* restore it for the next tests */
710 /* Verify linking style of import descriptors */
711 static void test_ImportDescriptors(void)
713 HMODULE kernel32_module = NULL;
714 PIMAGE_DOS_HEADER d_header;
715 PIMAGE_NT_HEADERS nt_headers;
716 DWORD import_dir_size;
717 DWORD_PTR dir_offset;
718 PIMAGE_IMPORT_DESCRIPTOR import_chunk;
720 /* Load kernel32 module */
721 kernel32_module = GetModuleHandleA("kernel32.dll");
722 assert( kernel32_module != NULL );
724 /* Get PE header info from module image */
725 d_header = (PIMAGE_DOS_HEADER) kernel32_module;
726 nt_headers = (PIMAGE_NT_HEADERS) (((char*) d_header) +
727 d_header->e_lfanew);
729 /* Get size of import entry directory */
730 import_dir_size = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size;
731 if (!import_dir_size)
733 skip("Unable to continue testing due to missing import directory.\n");
734 return;
737 /* Get address of first import chunk */
738 dir_offset = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
739 import_chunk = RVAToAddr(dir_offset, kernel32_module);
740 ok(import_chunk != 0, "Invalid import_chunk: %p\n", import_chunk);
741 if (!import_chunk) return;
743 /* Iterate through import descriptors and verify set name,
744 * OriginalFirstThunk, and FirstThunk. Core Windows DLLs, such as
745 * kernel32.dll, don't use Borland-style linking, where the table of
746 * imported names is stored directly in FirstThunk and overwritten
747 * by the relocation, instead of being stored in OriginalFirstThunk.
748 * */
749 for (; import_chunk->FirstThunk; import_chunk++)
751 LPCSTR module_name = RVAToAddr(import_chunk->Name, kernel32_module);
752 PIMAGE_THUNK_DATA name_table = RVAToAddr(
753 U(*import_chunk).OriginalFirstThunk, kernel32_module);
754 PIMAGE_THUNK_DATA iat = RVAToAddr(
755 import_chunk->FirstThunk, kernel32_module);
756 ok(module_name != NULL, "Imported module name should not be NULL\n");
757 ok(name_table != NULL,
758 "Name table for imported module %s should not be NULL\n",
759 module_name);
760 ok(iat != NULL, "IAT for imported module %s should not be NULL\n",
761 module_name);
765 static void test_image_mapping(const char *dll_name, DWORD scn_page_access, BOOL is_dll)
767 HANDLE hfile, hmap;
768 NTSTATUS status;
769 LARGE_INTEGER offset;
770 SIZE_T size;
771 void *addr1, *addr2;
772 MEMORY_BASIC_INFORMATION info;
774 if (!pNtMapViewOfSection) return;
776 SetLastError(0xdeadbeef);
777 hfile = CreateFileA(dll_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
778 ok(hfile != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
780 SetLastError(0xdeadbeef);
781 hmap = CreateFileMappingW(hfile, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, 0);
782 ok(hmap != 0, "CreateFileMapping error %d\n", GetLastError());
784 offset.u.LowPart = 0;
785 offset.u.HighPart = 0;
787 addr1 = NULL;
788 size = 0;
789 status = pNtMapViewOfSection(hmap, GetCurrentProcess(), &addr1, 0, 0, &offset,
790 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
791 ok(status == STATUS_SUCCESS, "NtMapViewOfSection error %x\n", status);
792 ok(addr1 != 0, "mapped address should be valid\n");
794 SetLastError(0xdeadbeef);
795 size = VirtualQuery((char *)addr1 + section.VirtualAddress, &info, sizeof(info));
796 ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
797 ok(info.BaseAddress == (char *)addr1 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr1 + section.VirtualAddress);
798 ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
799 ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
800 ok(info.AllocationBase == addr1, "%p != %p\n", info.AllocationBase, addr1);
801 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
802 ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
803 ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
805 addr2 = NULL;
806 size = 0;
807 status = pNtMapViewOfSection(hmap, GetCurrentProcess(), &addr2, 0, 0, &offset,
808 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
809 ok(status == STATUS_IMAGE_NOT_AT_BASE, "expected STATUS_IMAGE_NOT_AT_BASE, got %x\n", status);
810 ok(addr2 != 0, "mapped address should be valid\n");
811 ok(addr2 != addr1, "mapped addresses should be different\n");
813 SetLastError(0xdeadbeef);
814 size = VirtualQuery((char *)addr2 + section.VirtualAddress, &info, sizeof(info));
815 ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
816 ok(info.BaseAddress == (char *)addr2 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr2 + section.VirtualAddress);
817 ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
818 ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
819 ok(info.AllocationBase == addr2, "%p != %p\n", info.AllocationBase, addr2);
820 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
821 ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
822 ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
824 status = pNtUnmapViewOfSection(GetCurrentProcess(), addr2);
825 ok(status == STATUS_SUCCESS, "NtUnmapViewOfSection error %x\n", status);
827 addr2 = MapViewOfFile(hmap, 0, 0, 0, 0);
828 ok(addr2 != 0, "mapped address should be valid\n");
829 ok(addr2 != addr1, "mapped addresses should be different\n");
831 SetLastError(0xdeadbeef);
832 size = VirtualQuery((char *)addr2 + section.VirtualAddress, &info, sizeof(info));
833 ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
834 ok(info.BaseAddress == (char *)addr2 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr2 + section.VirtualAddress);
835 ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
836 ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
837 ok(info.AllocationBase == addr2, "%p != %p\n", info.AllocationBase, addr2);
838 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
839 ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
840 ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
842 UnmapViewOfFile(addr2);
844 SetLastError(0xdeadbeef);
845 addr2 = LoadLibraryA(dll_name);
846 if (is_dll)
848 ok(!addr2, "LoadLibrary should fail, is_dll %d\n", is_dll);
849 ok(GetLastError() == ERROR_INVALID_ADDRESS, "expected ERROR_INVALID_ADDRESS, got %d\n", GetLastError());
851 else
853 BOOL ret;
854 ok(addr2 != 0, "LoadLibrary error %d, is_dll %d\n", GetLastError(), is_dll);
855 ok(addr2 != addr1, "mapped addresses should be different\n");
857 SetLastError(0xdeadbeef);
858 ret = FreeLibrary(addr2);
859 ok(ret, "FreeLibrary error %d\n", GetLastError());
862 status = pNtUnmapViewOfSection(GetCurrentProcess(), addr1);
863 ok(status == STATUS_SUCCESS, "NtUnmapViewOfSection error %x\n", status);
865 CloseHandle(hmap);
866 CloseHandle(hfile);
869 static BOOL is_mem_writable(DWORD prot)
871 switch (prot & 0xff)
873 case PAGE_READWRITE:
874 case PAGE_WRITECOPY:
875 case PAGE_EXECUTE_READWRITE:
876 case PAGE_EXECUTE_WRITECOPY:
877 return TRUE;
879 default:
880 return FALSE;
884 static void test_VirtualProtect(void *base, void *section)
886 static const struct test_data
888 DWORD prot_set, prot_get;
889 } td[] =
891 { 0, 0 }, /* 0x00 */
892 { PAGE_NOACCESS, PAGE_NOACCESS }, /* 0x01 */
893 { PAGE_READONLY, PAGE_READONLY }, /* 0x02 */
894 { PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x03 */
895 { PAGE_READWRITE, PAGE_WRITECOPY }, /* 0x04 */
896 { PAGE_READWRITE | PAGE_NOACCESS, 0 }, /* 0x05 */
897 { PAGE_READWRITE | PAGE_READONLY, 0 }, /* 0x06 */
898 { PAGE_READWRITE | PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x07 */
899 { PAGE_WRITECOPY, PAGE_WRITECOPY }, /* 0x08 */
900 { PAGE_WRITECOPY | PAGE_NOACCESS, 0 }, /* 0x09 */
901 { PAGE_WRITECOPY | PAGE_READONLY, 0 }, /* 0x0a */
902 { PAGE_WRITECOPY | PAGE_NOACCESS | PAGE_READONLY, 0 }, /* 0x0b */
903 { PAGE_WRITECOPY | PAGE_READWRITE, 0 }, /* 0x0c */
904 { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_NOACCESS, 0 }, /* 0x0d */
905 { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_READONLY, 0 }, /* 0x0e */
906 { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x0f */
908 { PAGE_EXECUTE, PAGE_EXECUTE }, /* 0x10 */
909 { PAGE_EXECUTE_READ, PAGE_EXECUTE_READ }, /* 0x20 */
910 { PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0x30 */
911 { PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY }, /* 0x40 */
912 { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0x50 */
913 { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0x60 */
914 { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0x70 */
915 { PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_WRITECOPY }, /* 0x80 */
916 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE, 0 }, /* 0x90 */
917 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ, 0 }, /* 0xa0 */
918 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0xb0 */
919 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE, 0 }, /* 0xc0 */
920 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0xd0 */
921 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0xe0 */
922 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 } /* 0xf0 */
924 DWORD ret, orig_prot, old_prot, rw_prot, exec_prot, i, j;
925 MEMORY_BASIC_INFORMATION info;
927 SetLastError(0xdeadbeef);
928 ret = VirtualProtect(section, page_size, PAGE_NOACCESS, &old_prot);
929 ok(ret, "VirtualProtect error %d\n", GetLastError());
931 orig_prot = old_prot;
933 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
935 SetLastError(0xdeadbeef);
936 ret = VirtualQuery(section, &info, sizeof(info));
937 ok(ret, "VirtualQuery failed %d\n", GetLastError());
938 ok(info.BaseAddress == section, "%d: got %p != expected %p\n", i, info.BaseAddress, section);
939 ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
940 ok(info.Protect == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, info.Protect);
941 ok(info.AllocationBase == base, "%d: %p != %p\n", i, info.AllocationBase, base);
942 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
943 ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
944 ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
946 old_prot = 0xdeadbeef;
947 SetLastError(0xdeadbeef);
948 ret = VirtualProtect(section, page_size, td[i].prot_set, &old_prot);
949 if (td[i].prot_get)
951 ok(ret, "%d: VirtualProtect error %d, requested prot %#x\n", i, GetLastError(), td[i].prot_set);
952 ok(old_prot == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, old_prot);
954 SetLastError(0xdeadbeef);
955 ret = VirtualQuery(section, &info, sizeof(info));
956 ok(ret, "VirtualQuery failed %d\n", GetLastError());
957 ok(info.BaseAddress == section, "%d: got %p != expected %p\n", i, info.BaseAddress, section);
958 ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
959 ok(info.Protect == td[i].prot_get, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].prot_get);
960 ok(info.AllocationBase == base, "%d: %p != %p\n", i, info.AllocationBase, base);
961 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
962 ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
963 ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
965 else
967 ok(!ret, "%d: VirtualProtect should fail\n", i);
968 ok(GetLastError() == ERROR_INVALID_PARAMETER, "%d: expected ERROR_INVALID_PARAMETER, got %d\n", i, GetLastError());
971 old_prot = 0xdeadbeef;
972 SetLastError(0xdeadbeef);
973 ret = VirtualProtect(section, page_size, PAGE_NOACCESS, &old_prot);
974 ok(ret, "%d: VirtualProtect error %d\n", i, GetLastError());
975 if (td[i].prot_get)
976 ok(old_prot == td[i].prot_get, "%d: got %#x != expected %#x\n", i, old_prot, td[i].prot_get);
977 else
978 ok(old_prot == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, old_prot);
981 exec_prot = 0;
983 for (i = 0; i <= 4; i++)
985 rw_prot = 0;
987 for (j = 0; j <= 4; j++)
989 DWORD prot = exec_prot | rw_prot;
991 SetLastError(0xdeadbeef);
992 ret = VirtualProtect(section, page_size, prot, &old_prot);
993 if ((rw_prot && exec_prot) || (!rw_prot && !exec_prot))
995 ok(!ret, "VirtualProtect(%02x) should fail\n", prot);
996 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
998 else
999 ok(ret, "VirtualProtect(%02x) error %d\n", prot, GetLastError());
1001 rw_prot = 1 << j;
1004 exec_prot = 1 << (i + 4);
1007 SetLastError(0xdeadbeef);
1008 ret = VirtualProtect(section, page_size, orig_prot, &old_prot);
1009 ok(ret, "VirtualProtect error %d\n", GetLastError());
1012 static void test_section_access(void)
1014 static const struct test_data
1016 DWORD scn_file_access, scn_page_access, scn_page_access_after_write;
1017 } td[] =
1019 { 0, PAGE_NOACCESS, 0 },
1020 { IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1021 { IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1022 { IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1023 { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1024 { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ },
1025 { IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1026 { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1028 { IMAGE_SCN_CNT_INITIALIZED_DATA, PAGE_NOACCESS, 0 },
1029 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1030 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1031 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1032 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1033 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ, 0 },
1034 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1035 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1037 { IMAGE_SCN_CNT_UNINITIALIZED_DATA, PAGE_NOACCESS, 0 },
1038 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1039 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1040 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1041 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1042 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ, 0 },
1043 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1044 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE }
1046 char buf[256];
1047 int i;
1048 DWORD dummy, file_align;
1049 HANDLE hfile;
1050 HMODULE hlib;
1051 char temp_path[MAX_PATH];
1052 char dll_name[MAX_PATH];
1053 SIZE_T size;
1054 MEMORY_BASIC_INFORMATION info;
1055 STARTUPINFOA sti;
1056 PROCESS_INFORMATION pi;
1057 DWORD ret;
1059 /* prevent displaying of the "Unable to load this DLL" message box */
1060 SetErrorMode(SEM_FAILCRITICALERRORS);
1062 GetTempPathA(MAX_PATH, temp_path);
1064 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
1066 IMAGE_NT_HEADERS nt_header;
1068 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
1070 /*trace("creating %s\n", dll_name);*/
1071 hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
1072 if (hfile == INVALID_HANDLE_VALUE)
1074 ok(0, "could not create %s\n", dll_name);
1075 return;
1078 SetLastError(0xdeadbeef);
1079 ret = WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
1080 ok(ret, "WriteFile error %d\n", GetLastError());
1082 nt_header = nt_header_template;
1083 nt_header.FileHeader.NumberOfSections = 1;
1084 nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
1085 nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_RELOCS_STRIPPED;
1087 nt_header.OptionalHeader.SectionAlignment = page_size;
1088 nt_header.OptionalHeader.FileAlignment = 0x200;
1089 nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + page_size;
1090 nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
1091 SetLastError(0xdeadbeef);
1092 ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
1093 ok(ret, "WriteFile error %d\n", GetLastError());
1094 SetLastError(0xdeadbeef);
1095 ret = WriteFile(hfile, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
1096 ok(ret, "WriteFile error %d\n", GetLastError());
1098 section.SizeOfRawData = sizeof(section_data);
1099 section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
1100 section.VirtualAddress = nt_header.OptionalHeader.SectionAlignment;
1101 section.Misc.VirtualSize = section.SizeOfRawData;
1102 section.Characteristics = td[i].scn_file_access;
1103 SetLastError(0xdeadbeef);
1104 ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
1105 ok(ret, "WriteFile error %d\n", GetLastError());
1107 file_align = nt_header.OptionalHeader.FileAlignment - nt_header.OptionalHeader.SizeOfHeaders;
1108 assert(file_align < sizeof(filler));
1109 SetLastError(0xdeadbeef);
1110 ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
1111 ok(ret, "WriteFile error %d\n", GetLastError());
1113 /* section data */
1114 SetLastError(0xdeadbeef);
1115 ret = WriteFile(hfile, section_data, sizeof(section_data), &dummy, NULL);
1116 ok(ret, "WriteFile error %d\n", GetLastError());
1118 CloseHandle(hfile);
1120 SetLastError(0xdeadbeef);
1121 hlib = LoadLibraryA(dll_name);
1122 ok(hlib != 0, "LoadLibrary error %d\n", GetLastError());
1124 SetLastError(0xdeadbeef);
1125 size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
1126 ok(size == sizeof(info),
1127 "%d: VirtualQuery error %d\n", i, GetLastError());
1128 ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
1129 ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
1130 ok(info.Protect == td[i].scn_page_access, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access);
1131 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
1132 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1133 ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1134 ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1135 if (info.Protect != PAGE_NOACCESS)
1136 ok(!memcmp((const char *)info.BaseAddress, section_data, section.SizeOfRawData), "wrong section data\n");
1138 test_VirtualProtect(hlib, (char *)hlib + section.VirtualAddress);
1140 /* Windows changes the WRITECOPY to WRITE protection on an image section write (for a changed page only) */
1141 if (is_mem_writable(info.Protect))
1143 char *p = info.BaseAddress;
1144 *p = 0xfe;
1145 SetLastError(0xdeadbeef);
1146 size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
1147 ok(size == sizeof(info), "%d: VirtualQuery error %d\n", i, GetLastError());
1148 /* FIXME: remove the condition below once Wine is fixed */
1149 todo_wine_if (info.Protect == PAGE_WRITECOPY || info.Protect == PAGE_EXECUTE_WRITECOPY)
1150 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);
1153 SetLastError(0xdeadbeef);
1154 ret = FreeLibrary(hlib);
1155 ok(ret, "FreeLibrary error %d\n", GetLastError());
1157 test_image_mapping(dll_name, td[i].scn_page_access, TRUE);
1159 /* reset IMAGE_FILE_DLL otherwise CreateProcess fails */
1160 nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_RELOCS_STRIPPED;
1161 SetLastError(0xdeadbeef);
1162 hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1163 /* LoadLibrary called on an already memory-mapped file in
1164 * test_image_mapping() above leads to a file handle leak
1165 * under nt4, and inability to overwrite and delete the file
1166 * due to sharing violation error. Ignore it and skip the test,
1167 * but leave a not deletable temporary file.
1169 ok(hfile != INVALID_HANDLE_VALUE || broken(hfile == INVALID_HANDLE_VALUE) /* nt4 */,
1170 "CreateFile error %d\n", GetLastError());
1171 if (hfile == INVALID_HANDLE_VALUE) goto nt4_is_broken;
1172 SetFilePointer(hfile, sizeof(dos_header), NULL, FILE_BEGIN);
1173 SetLastError(0xdeadbeef);
1174 ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
1175 ok(ret, "WriteFile error %d\n", GetLastError());
1176 CloseHandle(hfile);
1178 memset(&sti, 0, sizeof(sti));
1179 sti.cb = sizeof(sti);
1180 SetLastError(0xdeadbeef);
1181 ret = CreateProcessA(dll_name, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &sti, &pi);
1182 ok(ret, "CreateProcess() error %d\n", GetLastError());
1184 SetLastError(0xdeadbeef);
1185 size = VirtualQueryEx(pi.hProcess, (char *)hlib + section.VirtualAddress, &info, sizeof(info));
1186 ok(size == sizeof(info),
1187 "%d: VirtualQuery error %d\n", i, GetLastError());
1188 ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
1189 ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
1190 ok(info.Protect == td[i].scn_page_access, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access);
1191 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
1192 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1193 ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1194 ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1195 if (info.Protect != PAGE_NOACCESS)
1197 SetLastError(0xdeadbeef);
1198 ret = ReadProcessMemory(pi.hProcess, info.BaseAddress, buf, section.SizeOfRawData, NULL);
1199 ok(ret, "ReadProcessMemory() error %d\n", GetLastError());
1200 ok(!memcmp(buf, section_data, section.SizeOfRawData), "wrong section data\n");
1203 SetLastError(0xdeadbeef);
1204 ret = TerminateProcess(pi.hProcess, 0);
1205 ok(ret, "TerminateProcess() error %d\n", GetLastError());
1206 ret = WaitForSingleObject(pi.hProcess, 3000);
1207 ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
1209 CloseHandle(pi.hThread);
1210 CloseHandle(pi.hProcess);
1212 test_image_mapping(dll_name, td[i].scn_page_access, FALSE);
1214 nt4_is_broken:
1215 SetLastError(0xdeadbeef);
1216 ret = DeleteFileA(dll_name);
1217 ok(ret || broken(!ret) /* nt4 */, "DeleteFile error %d\n", GetLastError());
1221 static void test_import_resolution(void)
1223 char temp_path[MAX_PATH];
1224 char dll_name[MAX_PATH];
1225 DWORD dummy;
1226 void *expect;
1227 char *str;
1228 HANDLE hfile;
1229 HMODULE mod, mod2;
1230 struct imports
1232 IMAGE_IMPORT_DESCRIPTOR descr[2];
1233 IMAGE_THUNK_DATA original_thunks[2];
1234 IMAGE_THUNK_DATA thunks[2];
1235 char module[16];
1236 struct { WORD hint; char name[32]; } function;
1237 IMAGE_TLS_DIRECTORY tls;
1238 char tls_data[16];
1239 SHORT tls_index;
1240 } data, *ptr;
1241 IMAGE_NT_HEADERS nt;
1242 IMAGE_SECTION_HEADER section;
1243 int test;
1245 for (test = 0; test < 3; test++)
1247 #define DATA_RVA(ptr) (page_size + ((char *)(ptr) - (char *)&data))
1248 nt = nt_header_template;
1249 nt.FileHeader.NumberOfSections = 1;
1250 nt.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
1251 nt.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_RELOCS_STRIPPED;
1252 if (test != 2) nt.FileHeader.Characteristics |= IMAGE_FILE_DLL;
1253 nt.OptionalHeader.SectionAlignment = page_size;
1254 nt.OptionalHeader.FileAlignment = 0x200;
1255 nt.OptionalHeader.ImageBase = 0x12340000;
1256 nt.OptionalHeader.SizeOfImage = 2 * page_size;
1257 nt.OptionalHeader.SizeOfHeaders = nt.OptionalHeader.FileAlignment;
1258 nt.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
1259 memset( nt.OptionalHeader.DataDirectory, 0, sizeof(nt.OptionalHeader.DataDirectory) );
1260 nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = sizeof(data.descr);
1261 nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = DATA_RVA(data.descr);
1262 nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size = sizeof(data.tls);
1263 nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress = DATA_RVA(&data.tls);
1265 memset( &data, 0, sizeof(data) );
1266 data.descr[0].u.OriginalFirstThunk = DATA_RVA( data.original_thunks );
1267 data.descr[0].FirstThunk = DATA_RVA( data.thunks );
1268 data.descr[0].Name = DATA_RVA( data.module );
1269 strcpy( data.module, "kernel32.dll" );
1270 strcpy( data.function.name, "CreateEventA" );
1271 data.original_thunks[0].u1.AddressOfData = DATA_RVA( &data.function );
1272 data.thunks[0].u1.AddressOfData = 0xdeadbeef;
1274 data.tls.StartAddressOfRawData = nt.OptionalHeader.ImageBase + DATA_RVA( data.tls_data );
1275 data.tls.EndAddressOfRawData = data.tls.StartAddressOfRawData + sizeof(data.tls_data);
1276 data.tls.AddressOfIndex = nt.OptionalHeader.ImageBase + DATA_RVA( &data.tls_index );
1277 strcpy( data.tls_data, "hello world" );
1278 data.tls_index = 9999;
1280 GetTempPathA(MAX_PATH, temp_path);
1281 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
1283 hfile = CreateFileA(dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0);
1284 ok( hfile != INVALID_HANDLE_VALUE, "creation failed\n" );
1286 memset( &section, 0, sizeof(section) );
1287 memcpy( section.Name, ".text", sizeof(".text") );
1288 section.PointerToRawData = nt.OptionalHeader.FileAlignment;
1289 section.VirtualAddress = nt.OptionalHeader.SectionAlignment;
1290 section.Misc.VirtualSize = sizeof(data);
1291 section.SizeOfRawData = sizeof(data);
1292 section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
1294 WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
1295 WriteFile(hfile, &nt, sizeof(nt), &dummy, NULL);
1296 WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
1298 SetFilePointer( hfile, section.PointerToRawData, NULL, SEEK_SET );
1299 WriteFile(hfile, &data, sizeof(data), &dummy, NULL);
1301 CloseHandle( hfile );
1303 switch (test)
1305 case 0: /* normal load */
1306 mod = LoadLibraryA( dll_name );
1307 ok( mod != NULL, "failed to load err %u\n", GetLastError() );
1308 if (!mod) break;
1309 ptr = (struct imports *)((char *)mod + page_size);
1310 expect = GetProcAddress( GetModuleHandleA( data.module ), data.function.name );
1311 ok( (void *)ptr->thunks[0].u1.Function == expect, "thunk %p instead of %p for %s.%s\n",
1312 (void *)ptr->thunks[0].u1.Function, expect, data.module, data.function.name );
1313 ok( ptr->tls_index < 32 || broken(ptr->tls_index == 9999), /* before vista */
1314 "wrong tls index %d\n", ptr->tls_index );
1315 if (ptr->tls_index != 9999)
1317 str = ((char **)NtCurrentTeb()->ThreadLocalStoragePointer)[ptr->tls_index];
1318 ok( !strcmp( str, "hello world" ), "wrong tls data '%s' at %p\n", str, str );
1320 FreeLibrary( mod );
1321 break;
1322 case 1: /* load with DONT_RESOLVE_DLL_REFERENCES doesn't resolve imports */
1323 mod = LoadLibraryExA( dll_name, 0, DONT_RESOLVE_DLL_REFERENCES );
1324 ok( mod != NULL, "failed to load err %u\n", GetLastError() );
1325 if (!mod) break;
1326 ptr = (struct imports *)((char *)mod + page_size);
1327 ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
1328 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
1329 ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
1331 mod2 = LoadLibraryA( dll_name );
1332 ok( mod2 == mod, "loaded twice %p / %p\n", mod, mod2 );
1333 ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
1334 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
1335 ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
1336 FreeLibrary( mod );
1337 break;
1338 case 2: /* load without IMAGE_FILE_DLL doesn't resolve imports */
1339 mod = LoadLibraryA( dll_name );
1340 ok( mod != NULL, "failed to load err %u\n", GetLastError() );
1341 if (!mod) break;
1342 ptr = (struct imports *)((char *)mod + page_size);
1343 ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
1344 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
1345 ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
1346 FreeLibrary( mod );
1347 break;
1349 DeleteFileA( dll_name );
1350 #undef DATA_RVA
1354 #define MAX_COUNT 10
1355 static HANDLE attached_thread[MAX_COUNT];
1356 static DWORD attached_thread_count;
1357 HANDLE stop_event, event, mutex, semaphore, loader_lock_event, peb_lock_event, heap_lock_event, ack_event;
1358 static int test_dll_phase, inside_loader_lock, inside_peb_lock, inside_heap_lock;
1360 static DWORD WINAPI mutex_thread_proc(void *param)
1362 HANDLE wait_list[4];
1363 DWORD ret;
1365 ret = WaitForSingleObject(mutex, 0);
1366 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1368 SetEvent(param);
1370 wait_list[0] = stop_event;
1371 wait_list[1] = loader_lock_event;
1372 wait_list[2] = peb_lock_event;
1373 wait_list[3] = heap_lock_event;
1375 trace("%04u: mutex_thread_proc: starting\n", GetCurrentThreadId());
1376 while (1)
1378 ret = WaitForMultipleObjects(sizeof(wait_list)/sizeof(wait_list[0]), wait_list, FALSE, 50);
1379 if (ret == WAIT_OBJECT_0) break;
1380 else if (ret == WAIT_OBJECT_0 + 1)
1382 ULONG_PTR loader_lock_magic;
1383 trace("%04u: mutex_thread_proc: Entering loader lock\n", GetCurrentThreadId());
1384 ret = pLdrLockLoaderLock(0, NULL, &loader_lock_magic);
1385 ok(!ret, "LdrLockLoaderLock error %#x\n", ret);
1386 inside_loader_lock++;
1387 SetEvent(ack_event);
1389 else if (ret == WAIT_OBJECT_0 + 2)
1391 trace("%04u: mutex_thread_proc: Entering PEB lock\n", GetCurrentThreadId());
1392 pRtlAcquirePebLock();
1393 inside_peb_lock++;
1394 SetEvent(ack_event);
1396 else if (ret == WAIT_OBJECT_0 + 3)
1398 trace("%04u: mutex_thread_proc: Entering heap lock\n", GetCurrentThreadId());
1399 HeapLock(GetProcessHeap());
1400 inside_heap_lock++;
1401 SetEvent(ack_event);
1405 trace("%04u: mutex_thread_proc: exiting\n", GetCurrentThreadId());
1406 return 196;
1409 static DWORD WINAPI semaphore_thread_proc(void *param)
1411 DWORD ret;
1413 ret = WaitForSingleObject(semaphore, 0);
1414 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1416 SetEvent(param);
1418 while (1)
1420 if (winetest_debug > 1)
1421 trace("%04u: semaphore_thread_proc: still alive\n", GetCurrentThreadId());
1422 if (WaitForSingleObject(stop_event, 50) != WAIT_TIMEOUT) break;
1425 trace("%04u: semaphore_thread_proc: exiting\n", GetCurrentThreadId());
1426 return 196;
1429 static DWORD WINAPI noop_thread_proc(void *param)
1431 if (param)
1433 LONG *noop_thread_started = param;
1434 InterlockedIncrement(noop_thread_started);
1437 trace("%04u: noop_thread_proc: exiting\n", GetCurrentThreadId());
1438 return 195;
1441 static BOOL WINAPI dll_entry_point(HINSTANCE hinst, DWORD reason, LPVOID param)
1443 static LONG noop_thread_started;
1444 DWORD ret;
1446 ok(!inside_loader_lock, "inside_loader_lock should not be set\n");
1447 ok(!inside_peb_lock, "inside_peb_lock should not be set\n");
1449 switch (reason)
1451 case DLL_PROCESS_ATTACH:
1452 trace("dll: %p, DLL_PROCESS_ATTACH, %p\n", hinst, param);
1454 ret = pRtlDllShutdownInProgress();
1455 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1457 break;
1458 case DLL_PROCESS_DETACH:
1460 DWORD code, expected_code, i;
1461 HANDLE handle, process;
1462 void *addr;
1463 SIZE_T size;
1464 LARGE_INTEGER offset;
1465 DEBUG_EVENT de;
1467 trace("dll: %p, DLL_PROCESS_DETACH, %p\n", hinst, param);
1469 if (test_dll_phase == 4 || test_dll_phase == 5)
1471 ok(0, "dll_entry_point(DLL_PROCESS_DETACH) should not be called\n");
1472 break;
1475 /* The process should already deadlock at this point */
1476 if (test_dll_phase == 6)
1478 /* In reality, code below never gets executed, probably some other
1479 * code tries to access process heap and deadlocks earlier, even XP
1480 * doesn't call the DLL entry point on process detach either.
1482 HeapLock(GetProcessHeap());
1483 ok(0, "dll_entry_point: process should already deadlock\n");
1484 break;
1487 if (test_dll_phase == 0 || test_dll_phase == 1 || test_dll_phase == 3)
1488 ok(param != NULL, "dll: param %p\n", param);
1489 else
1490 ok(!param, "dll: param %p\n", param);
1492 if (test_dll_phase == 0 || test_dll_phase == 1) expected_code = 195;
1493 else if (test_dll_phase == 3) expected_code = 196;
1494 else expected_code = STILL_ACTIVE;
1496 if (test_dll_phase == 3)
1498 ret = pRtlDllShutdownInProgress();
1499 ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
1501 else
1503 ret = pRtlDllShutdownInProgress();
1505 /* FIXME: remove once Wine is fixed */
1506 todo_wine_if (!(expected_code == STILL_ACTIVE || expected_code == 196))
1507 ok(!ret || broken(ret) /* before Vista */, "RtlDllShutdownInProgress returned %d\n", ret);
1510 ok(attached_thread_count >= 2, "attached thread count should be >= 2\n");
1512 for (i = 0; i < attached_thread_count; i++)
1514 /* Calling GetExitCodeThread() without waiting for thread termination
1515 * leads to different results due to a race condition.
1517 if (expected_code != STILL_ACTIVE)
1519 ret = WaitForSingleObject(attached_thread[i], 1000);
1520 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1522 ret = GetExitCodeThread(attached_thread[i], &code);
1523 trace("dll: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
1524 ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
1525 ok(code == expected_code, "expected thread exit code %u, got %u\n", expected_code, code);
1528 ret = WaitForSingleObject(event, 0);
1529 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1531 ret = WaitForSingleObject(mutex, 0);
1532 if (expected_code == STILL_ACTIVE)
1533 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1534 else
1535 ok(ret == WAIT_ABANDONED, "expected WAIT_ABANDONED, got %#x\n", ret);
1537 /* semaphore is not abandoned on thread termination */
1538 ret = WaitForSingleObject(semaphore, 0);
1539 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1541 if (expected_code == STILL_ACTIVE)
1543 ret = WaitForSingleObject(attached_thread[0], 0);
1544 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1545 ret = WaitForSingleObject(attached_thread[1], 0);
1546 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1548 else
1550 ret = WaitForSingleObject(attached_thread[0], 0);
1551 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1552 ret = WaitForSingleObject(attached_thread[1], 0);
1553 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1556 /* win7 doesn't allow creating a thread during process shutdown but
1557 * earlier Windows versions allow it.
1559 noop_thread_started = 0;
1560 SetLastError(0xdeadbeef);
1561 handle = CreateThread(NULL, 0, noop_thread_proc, &noop_thread_started, 0, &ret);
1562 if (param)
1564 ok(!handle || broken(handle != 0) /* before win7 */, "CreateThread should fail\n");
1565 if (!handle)
1566 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1567 else
1569 ret = WaitForSingleObject(handle, 1000);
1570 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1571 CloseHandle(handle);
1574 else
1576 ok(handle != 0, "CreateThread error %d\n", GetLastError());
1577 ret = WaitForSingleObject(handle, 1000);
1578 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1579 ok(!noop_thread_started || broken(noop_thread_started) /* XP64 */, "thread shouldn't start yet\n");
1580 CloseHandle(handle);
1583 SetLastError(0xdeadbeef);
1584 process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, GetCurrentProcessId());
1585 ok(process != NULL, "OpenProcess error %d\n", GetLastError());
1587 noop_thread_started = 0;
1588 SetLastError(0xdeadbeef);
1589 handle = CreateRemoteThread(process, NULL, 0, noop_thread_proc, &noop_thread_started, 0, &ret);
1590 if (param)
1592 ok(!handle || broken(handle != 0) /* before win7 */, "CreateRemoteThread should fail\n");
1593 if (!handle)
1594 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1595 else
1597 ret = WaitForSingleObject(handle, 1000);
1598 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1599 CloseHandle(handle);
1602 else
1604 ok(handle != 0, "CreateRemoteThread error %d\n", GetLastError());
1605 ret = WaitForSingleObject(handle, 1000);
1606 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1607 ok(!noop_thread_started || broken(noop_thread_started) /* XP64 */, "thread shouldn't start yet\n");
1608 CloseHandle(handle);
1611 SetLastError(0xdeadbeef);
1612 handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, NULL);
1613 ok(handle != 0, "CreateFileMapping error %d\n", GetLastError());
1615 offset.u.LowPart = 0;
1616 offset.u.HighPart = 0;
1617 addr = NULL;
1618 size = 0;
1619 ret = pNtMapViewOfSection(handle, process, &addr, 0, 0, &offset,
1620 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
1621 ok(ret == STATUS_SUCCESS, "NtMapViewOfSection error %#x\n", ret);
1622 ret = pNtUnmapViewOfSection(process, addr);
1623 ok(ret == STATUS_SUCCESS, "NtUnmapViewOfSection error %#x\n", ret);
1625 CloseHandle(handle);
1626 CloseHandle(process);
1628 handle = GetModuleHandleA("winver.exe");
1629 ok(!handle, "winver.exe shouldn't be loaded yet\n");
1630 SetLastError(0xdeadbeef);
1631 handle = LoadLibraryA("winver.exe");
1632 ok(handle != 0, "LoadLibrary error %d\n", GetLastError());
1633 SetLastError(0xdeadbeef);
1634 ret = FreeLibrary(handle);
1635 ok(ret, "FreeLibrary error %d\n", GetLastError());
1636 handle = GetModuleHandleA("winver.exe");
1637 if (param)
1638 ok(handle != 0, "winver.exe should not be unloaded\n");
1639 else
1640 todo_wine
1641 ok(!handle || broken(handle != 0) /* before win7 */, "winver.exe should be unloaded\n");
1643 SetLastError(0xdeadbeef);
1644 ret = WaitForDebugEvent(&de, 0);
1645 ok(!ret, "WaitForDebugEvent should fail\n");
1646 todo_wine
1647 ok(GetLastError() == ERROR_INVALID_HANDLE, "expected ERROR_INVALID_HANDLE, got %d\n", GetLastError());
1649 SetLastError(0xdeadbeef);
1650 ret = DebugActiveProcess(GetCurrentProcessId());
1651 ok(!ret, "DebugActiveProcess should fail\n");
1652 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1654 SetLastError(0xdeadbeef);
1655 ret = WaitForDebugEvent(&de, 0);
1656 ok(!ret, "WaitForDebugEvent should fail\n");
1657 ok(GetLastError() == ERROR_SEM_TIMEOUT, "expected ERROR_SEM_TIMEOUT, got %d\n", GetLastError());
1659 if (test_dll_phase == 2)
1661 trace("dll: call ExitProcess()\n");
1662 *child_failures = winetest_get_failures();
1663 ExitProcess(197);
1665 trace("dll: %p, DLL_PROCESS_DETACH, %p => DONE\n", hinst, param);
1666 break;
1668 case DLL_THREAD_ATTACH:
1669 trace("dll: %p, DLL_THREAD_ATTACH, %p\n", hinst, param);
1671 ret = pRtlDllShutdownInProgress();
1672 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1674 if (attached_thread_count < MAX_COUNT)
1676 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &attached_thread[attached_thread_count],
1677 0, TRUE, DUPLICATE_SAME_ACCESS);
1678 attached_thread_count++;
1680 break;
1681 case DLL_THREAD_DETACH:
1682 trace("dll: %p, DLL_THREAD_DETACH, %p\n", hinst, param);
1684 ret = pRtlDllShutdownInProgress();
1685 /* win7 doesn't allow creating a thread during process shutdown but
1686 * earlier Windows versions allow it. In that case DLL_THREAD_DETACH is
1687 * sent on thread exit, but DLL_THREAD_ATTACH is never received.
1689 if (noop_thread_started)
1690 ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
1691 else
1692 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1694 break;
1695 default:
1696 trace("dll: %p, %d, %p\n", hinst, reason, param);
1697 break;
1700 *child_failures = winetest_get_failures();
1702 return TRUE;
1705 static void child_process(const char *dll_name, DWORD target_offset)
1707 void *target;
1708 DWORD ret, dummy, i, code, expected_code;
1709 HANDLE file, thread, process;
1710 HMODULE hmod;
1711 struct PROCESS_BASIC_INFORMATION_PRIVATE pbi;
1712 DWORD_PTR affinity;
1714 trace("phase %d: writing %p at %#x\n", test_dll_phase, dll_entry_point, target_offset);
1716 SetLastError(0xdeadbeef);
1717 mutex = CreateMutexW(NULL, FALSE, NULL);
1718 ok(mutex != 0, "CreateMutex error %d\n", GetLastError());
1720 SetLastError(0xdeadbeef);
1721 semaphore = CreateSemaphoreW(NULL, 1, 1, NULL);
1722 ok(semaphore != 0, "CreateSemaphore error %d\n", GetLastError());
1724 SetLastError(0xdeadbeef);
1725 event = CreateEventW(NULL, TRUE, FALSE, NULL);
1726 ok(event != 0, "CreateEvent error %d\n", GetLastError());
1728 SetLastError(0xdeadbeef);
1729 loader_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1730 ok(loader_lock_event != 0, "CreateEvent error %d\n", GetLastError());
1732 SetLastError(0xdeadbeef);
1733 peb_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1734 ok(peb_lock_event != 0, "CreateEvent error %d\n", GetLastError());
1736 SetLastError(0xdeadbeef);
1737 heap_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1738 ok(heap_lock_event != 0, "CreateEvent error %d\n", GetLastError());
1740 SetLastError(0xdeadbeef);
1741 ack_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1742 ok(ack_event != 0, "CreateEvent error %d\n", GetLastError());
1744 file = CreateFileA(dll_name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1745 if (file == INVALID_HANDLE_VALUE)
1747 ok(0, "could not open %s\n", dll_name);
1748 return;
1750 SetFilePointer(file, target_offset, NULL, FILE_BEGIN);
1751 SetLastError(0xdeadbeef);
1752 target = dll_entry_point;
1753 ret = WriteFile(file, &target, sizeof(target), &dummy, NULL);
1754 ok(ret, "WriteFile error %d\n", GetLastError());
1755 CloseHandle(file);
1757 SetLastError(0xdeadbeef);
1758 hmod = LoadLibraryA(dll_name);
1759 ok(hmod != 0, "LoadLibrary error %d\n", GetLastError());
1761 SetLastError(0xdeadbeef);
1762 stop_event = CreateEventW(NULL, TRUE, FALSE, NULL);
1763 ok(stop_event != 0, "CreateEvent error %d\n", GetLastError());
1765 SetLastError(0xdeadbeef);
1766 thread = CreateThread(NULL, 0, mutex_thread_proc, event, 0, &dummy);
1767 ok(thread != 0, "CreateThread error %d\n", GetLastError());
1768 WaitForSingleObject(event, 3000);
1769 CloseHandle(thread);
1771 ResetEvent(event);
1773 SetLastError(0xdeadbeef);
1774 thread = CreateThread(NULL, 0, semaphore_thread_proc, event, 0, &dummy);
1775 ok(thread != 0, "CreateThread error %d\n", GetLastError());
1776 WaitForSingleObject(event, 3000);
1777 CloseHandle(thread);
1779 ResetEvent(event);
1780 Sleep(100);
1782 ok(attached_thread_count == 2, "attached thread count should be 2\n");
1783 for (i = 0; i < attached_thread_count; i++)
1785 ret = GetExitCodeThread(attached_thread[i], &code);
1786 trace("child: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
1787 ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
1788 ok(code == STILL_ACTIVE, "expected thread exit code STILL_ACTIVE, got %u\n", code);
1791 ret = WaitForSingleObject(attached_thread[0], 0);
1792 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1793 ret = WaitForSingleObject(attached_thread[1], 0);
1794 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1796 ret = WaitForSingleObject(event, 0);
1797 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1798 ret = WaitForSingleObject(mutex, 0);
1799 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1800 ret = WaitForSingleObject(semaphore, 0);
1801 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1803 ret = pRtlDllShutdownInProgress();
1804 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1806 SetLastError(0xdeadbeef);
1807 process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, GetCurrentProcessId());
1808 ok(process != NULL, "OpenProcess error %d\n", GetLastError());
1810 SetLastError(0xdeadbeef);
1811 ret = TerminateProcess(0, 195);
1812 ok(!ret, "TerminateProcess(0) should fail\n");
1813 ok(GetLastError() == ERROR_INVALID_HANDLE, "expected ERROR_INVALID_HANDLE, got %d\n", GetLastError());
1815 Sleep(100);
1817 affinity = 1;
1818 ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
1819 ok(!ret, "NtSetInformationProcess error %#x\n", ret);
1821 switch (test_dll_phase)
1823 case 0:
1824 ret = pRtlDllShutdownInProgress();
1825 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1827 trace("call NtTerminateProcess(0, 195)\n");
1828 ret = pNtTerminateProcess(0, 195);
1829 ok(!ret, "NtTerminateProcess error %#x\n", ret);
1831 memset(&pbi, 0, sizeof(pbi));
1832 ret = pNtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
1833 ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
1834 ok(pbi.ExitStatus == STILL_ACTIVE, "expected STILL_ACTIVE, got %lu\n", pbi.ExitStatus);
1835 affinity = 1;
1836 ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
1837 ok(!ret, "NtSetInformationProcess error %#x\n", ret);
1839 ret = pRtlDllShutdownInProgress();
1840 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1842 hmod = GetModuleHandleA(dll_name);
1843 ok(hmod != 0, "DLL should not be unloaded\n");
1845 SetLastError(0xdeadbeef);
1846 thread = CreateThread(NULL, 0, noop_thread_proc, &dummy, 0, &ret);
1847 ok(!thread || broken(thread != 0) /* before win7 */, "CreateThread should fail\n");
1848 if (!thread)
1849 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1850 else
1852 ret = WaitForSingleObject(thread, 1000);
1853 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1854 CloseHandle(thread);
1857 trace("call LdrShutdownProcess()\n");
1858 pLdrShutdownProcess();
1860 ret = pRtlDllShutdownInProgress();
1861 ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
1863 hmod = GetModuleHandleA(dll_name);
1864 ok(hmod != 0, "DLL should not be unloaded\n");
1866 memset(&pbi, 0, sizeof(pbi));
1867 ret = pNtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
1868 ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
1869 ok(pbi.ExitStatus == STILL_ACTIVE, "expected STILL_ACTIVE, got %lu\n", pbi.ExitStatus);
1870 affinity = 1;
1871 ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
1872 ok(!ret, "NtSetInformationProcess error %#x\n", ret);
1873 break;
1875 case 1: /* normal ExitProcess */
1876 ret = pRtlDllShutdownInProgress();
1877 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1878 break;
1880 case 2: /* ExitProcess will be called by the PROCESS_DETACH handler */
1881 ret = pRtlDllShutdownInProgress();
1882 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1884 trace("call FreeLibrary(%p)\n", hmod);
1885 SetLastError(0xdeadbeef);
1886 ret = FreeLibrary(hmod);
1887 ok(ret, "FreeLibrary error %d\n", GetLastError());
1888 hmod = GetModuleHandleA(dll_name);
1889 ok(!hmod, "DLL should be unloaded\n");
1891 if (test_dll_phase == 2)
1892 ok(0, "FreeLibrary+ExitProcess should never return\n");
1894 ret = pRtlDllShutdownInProgress();
1895 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1897 break;
1899 case 3:
1900 trace("signalling thread exit\n");
1901 SetEvent(stop_event);
1902 CloseHandle(stop_event);
1903 break;
1905 case 4:
1906 trace("setting loader_lock_event\n");
1907 SetEvent(loader_lock_event);
1908 WaitForSingleObject(ack_event, 1000);
1909 ok(inside_loader_lock != 0, "inside_loader_lock is not set\n");
1911 /* calling NtTerminateProcess should not cause a deadlock */
1912 trace("call NtTerminateProcess(0, 198)\n");
1913 ret = pNtTerminateProcess(0, 198);
1914 ok(!ret, "NtTerminateProcess error %#x\n", ret);
1916 *child_failures = winetest_get_failures();
1918 /* Windows fails to release loader lock acquired from another thread,
1919 * so the LdrUnlockLoaderLock call fails here and ExitProcess deadlocks
1920 * later on, so NtTerminateProcess is used instead.
1922 trace("call NtTerminateProcess(GetCurrentProcess(), 198)\n");
1923 pNtTerminateProcess(GetCurrentProcess(), 198);
1924 ok(0, "NtTerminateProcess should not return\n");
1925 break;
1927 case 5:
1928 trace("setting peb_lock_event\n");
1929 SetEvent(peb_lock_event);
1930 WaitForSingleObject(ack_event, 1000);
1931 ok(inside_peb_lock != 0, "inside_peb_lock is not set\n");
1933 *child_failures = winetest_get_failures();
1935 /* calling ExitProcess should cause a deadlock */
1936 trace("call ExitProcess(198)\n");
1937 ExitProcess(198);
1938 ok(0, "ExitProcess should not return\n");
1939 break;
1941 case 6:
1942 trace("setting heap_lock_event\n");
1943 SetEvent(heap_lock_event);
1944 WaitForSingleObject(ack_event, 1000);
1945 ok(inside_heap_lock != 0, "inside_heap_lock is not set\n");
1947 *child_failures = winetest_get_failures();
1949 /* calling ExitProcess should cause a deadlock */
1950 trace("call ExitProcess(1)\n");
1951 ExitProcess(1);
1952 ok(0, "ExitProcess should not return\n");
1953 break;
1955 default:
1956 assert(0);
1957 break;
1960 if (test_dll_phase == 0) expected_code = 195;
1961 else if (test_dll_phase == 3) expected_code = 196;
1962 else if (test_dll_phase == 4) expected_code = 198;
1963 else expected_code = STILL_ACTIVE;
1965 if (expected_code == STILL_ACTIVE)
1967 ret = WaitForSingleObject(attached_thread[0], 100);
1968 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1969 ret = WaitForSingleObject(attached_thread[1], 100);
1970 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1972 else
1974 ret = WaitForSingleObject(attached_thread[0], 1000);
1975 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1976 ret = WaitForSingleObject(attached_thread[1], 1000);
1977 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1980 for (i = 0; i < attached_thread_count; i++)
1982 ret = GetExitCodeThread(attached_thread[i], &code);
1983 trace("child: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
1984 ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
1985 ok(code == expected_code, "expected thread exit code %u, got %u\n", expected_code, code);
1988 *child_failures = winetest_get_failures();
1990 trace("call ExitProcess(195)\n");
1991 ExitProcess(195);
1994 static void test_ExitProcess(void)
1996 #include "pshpack1.h"
1997 #ifdef __x86_64__
1998 static struct section_data
2000 BYTE mov_rax[2];
2001 void *target;
2002 BYTE jmp_rax[2];
2003 } section_data = { { 0x48,0xb8 }, dll_entry_point, { 0xff,0xe0 } };
2004 #else
2005 static struct section_data
2007 BYTE mov_eax;
2008 void *target;
2009 BYTE jmp_eax[2];
2010 } section_data = { 0xb8, dll_entry_point, { 0xff,0xe0 } };
2011 #endif
2012 #include "poppack.h"
2013 static const char filler[0x1000];
2014 DWORD dummy, file_align;
2015 HANDLE file, thread, process, hmap, hmap_dup;
2016 char temp_path[MAX_PATH], dll_name[MAX_PATH], cmdline[MAX_PATH * 2];
2017 DWORD ret, target_offset, old_prot;
2018 char **argv, buf[256];
2019 PROCESS_INFORMATION pi;
2020 STARTUPINFOA si = { sizeof(si) };
2021 CONTEXT ctx;
2022 struct PROCESS_BASIC_INFORMATION_PRIVATE pbi;
2023 MEMORY_BASIC_INFORMATION mbi;
2024 DWORD_PTR affinity;
2025 void *addr;
2026 LARGE_INTEGER offset;
2027 SIZE_T size;
2028 IMAGE_NT_HEADERS nt_header;
2030 #if !defined(__i386__) && !defined(__x86_64__)
2031 skip("x86 specific ExitProcess test\n");
2032 return;
2033 #endif
2035 if (!pRtlDllShutdownInProgress)
2037 win_skip("RtlDllShutdownInProgress is not available on this platform (XP+)\n");
2038 return;
2040 if (!pNtQueryInformationProcess || !pNtSetInformationProcess)
2042 win_skip("NtQueryInformationProcess/NtSetInformationProcess are not available on this platform\n");
2043 return;
2045 if (!pNtAllocateVirtualMemory || !pNtFreeVirtualMemory)
2047 win_skip("NtAllocateVirtualMemory/NtFreeVirtualMemory are not available on this platform\n");
2048 return;
2051 /* prevent displaying of the "Unable to load this DLL" message box */
2052 SetErrorMode(SEM_FAILCRITICALERRORS);
2054 GetTempPathA(MAX_PATH, temp_path);
2055 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
2057 /*trace("creating %s\n", dll_name);*/
2058 file = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
2059 if (file == INVALID_HANDLE_VALUE)
2061 ok(0, "could not create %s\n", dll_name);
2062 return;
2065 SetLastError(0xdeadbeef);
2066 ret = WriteFile(file, &dos_header, sizeof(dos_header), &dummy, NULL);
2067 ok(ret, "WriteFile error %d\n", GetLastError());
2069 nt_header = nt_header_template;
2070 nt_header.FileHeader.NumberOfSections = 1;
2071 nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
2072 nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_RELOCS_STRIPPED;
2074 nt_header.OptionalHeader.AddressOfEntryPoint = 0x1000;
2075 nt_header.OptionalHeader.SectionAlignment = 0x1000;
2076 nt_header.OptionalHeader.FileAlignment = 0x200;
2077 nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000;
2078 nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
2079 SetLastError(0xdeadbeef);
2080 ret = WriteFile(file, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
2081 ok(ret, "WriteFile error %d\n", GetLastError());
2082 SetLastError(0xdeadbeef);
2083 ret = WriteFile(file, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
2084 ok(ret, "WriteFile error %d\n", GetLastError());
2086 section.SizeOfRawData = sizeof(section_data);
2087 section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
2088 section.VirtualAddress = nt_header.OptionalHeader.SectionAlignment;
2089 section.Misc.VirtualSize = sizeof(section_data);
2090 section.Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE;
2091 SetLastError(0xdeadbeef);
2092 ret = WriteFile(file, &section, sizeof(section), &dummy, NULL);
2093 ok(ret, "WriteFile error %d\n", GetLastError());
2095 file_align = nt_header.OptionalHeader.FileAlignment - nt_header.OptionalHeader.SizeOfHeaders;
2096 assert(file_align < sizeof(filler));
2097 SetLastError(0xdeadbeef);
2098 ret = WriteFile(file, filler, file_align, &dummy, NULL);
2099 ok(ret, "WriteFile error %d\n", GetLastError());
2101 target_offset = SetFilePointer(file, 0, NULL, FILE_CURRENT) + FIELD_OFFSET(struct section_data, target);
2103 /* section data */
2104 SetLastError(0xdeadbeef);
2105 ret = WriteFile(file, &section_data, sizeof(section_data), &dummy, NULL);
2106 ok(ret, "WriteFile error %d\n", GetLastError());
2108 CloseHandle(file);
2110 winetest_get_mainargs(&argv);
2112 /* phase 0 */
2113 *child_failures = -1;
2114 sprintf(cmdline, "\"%s\" loader %s %u 0", argv[0], dll_name, target_offset);
2115 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2116 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2117 ret = WaitForSingleObject(pi.hProcess, 10000);
2118 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2119 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2120 GetExitCodeProcess(pi.hProcess, &ret);
2121 ok(ret == 195, "expected exit code 195, got %u\n", ret);
2122 if (*child_failures)
2124 trace("%d failures in child process\n", *child_failures);
2125 winetest_add_failures(*child_failures);
2127 CloseHandle(pi.hThread);
2128 CloseHandle(pi.hProcess);
2130 /* phase 1 */
2131 *child_failures = -1;
2132 sprintf(cmdline, "\"%s\" loader %s %u 1", argv[0], dll_name, target_offset);
2133 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2134 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2135 ret = WaitForSingleObject(pi.hProcess, 10000);
2136 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2137 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2138 GetExitCodeProcess(pi.hProcess, &ret);
2139 ok(ret == 195, "expected exit code 195, got %u\n", ret);
2140 if (*child_failures)
2142 trace("%d failures in child process\n", *child_failures);
2143 winetest_add_failures(*child_failures);
2145 CloseHandle(pi.hThread);
2146 CloseHandle(pi.hProcess);
2148 /* phase 2 */
2149 *child_failures = -1;
2150 sprintf(cmdline, "\"%s\" loader %s %u 2", argv[0], dll_name, target_offset);
2151 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2152 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2153 ret = WaitForSingleObject(pi.hProcess, 10000);
2154 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2155 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2156 GetExitCodeProcess(pi.hProcess, &ret);
2157 ok(ret == 197, "expected exit code 197, got %u\n", ret);
2158 if (*child_failures)
2160 trace("%d failures in child process\n", *child_failures);
2161 winetest_add_failures(*child_failures);
2163 CloseHandle(pi.hThread);
2164 CloseHandle(pi.hProcess);
2166 /* phase 3 */
2167 *child_failures = -1;
2168 sprintf(cmdline, "\"%s\" loader %s %u 3", argv[0], dll_name, target_offset);
2169 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2170 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2171 ret = WaitForSingleObject(pi.hProcess, 10000);
2172 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2173 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2174 GetExitCodeProcess(pi.hProcess, &ret);
2175 ok(ret == 195, "expected exit code 195, got %u\n", ret);
2176 if (*child_failures)
2178 trace("%d failures in child process\n", *child_failures);
2179 winetest_add_failures(*child_failures);
2181 CloseHandle(pi.hThread);
2182 CloseHandle(pi.hProcess);
2184 /* phase 4 */
2185 if (pLdrLockLoaderLock && pLdrUnlockLoaderLock)
2187 *child_failures = -1;
2188 sprintf(cmdline, "\"%s\" loader %s %u 4", argv[0], dll_name, target_offset);
2189 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2190 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2191 ret = WaitForSingleObject(pi.hProcess, 10000);
2192 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2193 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2194 GetExitCodeProcess(pi.hProcess, &ret);
2195 ok(ret == 198, "expected exit code 198, got %u\n", ret);
2196 if (*child_failures)
2198 trace("%d failures in child process\n", *child_failures);
2199 winetest_add_failures(*child_failures);
2201 CloseHandle(pi.hThread);
2202 CloseHandle(pi.hProcess);
2204 else
2205 win_skip("LdrLockLoaderLock/LdrUnlockLoaderLock are not available on this platform\n");
2207 /* phase 5 */
2208 if (pRtlAcquirePebLock && pRtlReleasePebLock)
2210 *child_failures = -1;
2211 sprintf(cmdline, "\"%s\" loader %s %u 5", argv[0], dll_name, target_offset);
2212 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2213 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2214 ret = WaitForSingleObject(pi.hProcess, 5000);
2215 ok(ret == WAIT_TIMEOUT, "child process should fail to terminate\n");
2216 if (ret != WAIT_OBJECT_0)
2218 trace("terminating child process\n");
2219 TerminateProcess(pi.hProcess, 199);
2221 ret = WaitForSingleObject(pi.hProcess, 1000);
2222 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2223 GetExitCodeProcess(pi.hProcess, &ret);
2224 ok(ret == 199, "expected exit code 199, got %u\n", ret);
2225 if (*child_failures)
2227 trace("%d failures in child process\n", *child_failures);
2228 winetest_add_failures(*child_failures);
2230 CloseHandle(pi.hThread);
2231 CloseHandle(pi.hProcess);
2233 else
2234 win_skip("RtlAcquirePebLock/RtlReleasePebLock are not available on this platform\n");
2236 /* phase 6 */
2237 *child_failures = -1;
2238 sprintf(cmdline, "\"%s\" loader %s %u 6", argv[0], dll_name, target_offset);
2239 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2240 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2241 ret = WaitForSingleObject(pi.hProcess, 5000);
2242 ok(ret == WAIT_TIMEOUT || broken(ret == WAIT_OBJECT_0) /* XP */, "child process should fail to terminate\n");
2243 if (ret != WAIT_OBJECT_0)
2245 trace("terminating child process\n");
2246 TerminateProcess(pi.hProcess, 201);
2248 ret = WaitForSingleObject(pi.hProcess, 1000);
2249 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2250 GetExitCodeProcess(pi.hProcess, &ret);
2251 ok(ret == 201 || broken(ret == 1) /* XP */, "expected exit code 201, got %u\n", ret);
2252 if (*child_failures)
2254 trace("%d failures in child process\n", *child_failures);
2255 winetest_add_failures(*child_failures);
2257 CloseHandle(pi.hThread);
2258 CloseHandle(pi.hProcess);
2260 /* test remote process termination */
2261 SetLastError(0xdeadbeef);
2262 ret = CreateProcessA(argv[0], NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi);
2263 ok(ret, "CreateProcess(%s) error %d\n", argv[0], GetLastError());
2265 SetLastError(0xdeadbeef);
2266 addr = VirtualAllocEx(pi.hProcess, NULL, 4096, MEM_COMMIT, PAGE_READWRITE);
2267 ok(addr != NULL, "VirtualAllocEx error %d\n", GetLastError());
2268 SetLastError(0xdeadbeef);
2269 ret = VirtualProtectEx(pi.hProcess, addr, 4096, PAGE_READONLY, &old_prot);
2270 ok(ret, "VirtualProtectEx error %d\n", GetLastError());
2271 ok(old_prot == PAGE_READWRITE, "expected PAGE_READWRITE, got %#x\n", old_prot);
2272 SetLastError(0xdeadbeef);
2273 size = VirtualQueryEx(pi.hProcess, NULL, &mbi, sizeof(mbi));
2274 ok(size == sizeof(mbi), "VirtualQueryEx error %d\n", GetLastError());
2276 SetLastError(0xdeadbeef);
2277 ret = ReadProcessMemory(pi.hProcess, addr, buf, 4, &size);
2278 ok(ret, "ReadProcessMemory error %d\n", GetLastError());
2279 ok(size == 4, "expected 4, got %lu\n", size);
2281 SetLastError(0xdeadbeef);
2282 hmap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, NULL);
2283 ok(hmap != 0, "CreateFileMapping error %d\n", GetLastError());
2285 SetLastError(0xdeadbeef);
2286 ret = DuplicateHandle(GetCurrentProcess(), hmap, pi.hProcess, &hmap_dup,
2287 0, FALSE, DUPLICATE_SAME_ACCESS);
2288 ok(ret, "DuplicateHandle error %d\n", GetLastError());
2290 offset.u.LowPart = 0;
2291 offset.u.HighPart = 0;
2292 addr = NULL;
2293 size = 0;
2294 ret = pNtMapViewOfSection(hmap, pi.hProcess, &addr, 0, 0, &offset,
2295 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
2296 ok(!ret, "NtMapViewOfSection error %#x\n", ret);
2297 ret = pNtUnmapViewOfSection(pi.hProcess, addr);
2298 ok(!ret, "NtUnmapViewOfSection error %#x\n", ret);
2300 SetLastError(0xdeadbeef);
2301 thread = CreateRemoteThread(pi.hProcess, NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
2302 ok(thread != 0, "CreateRemoteThread error %d\n", GetLastError());
2303 SetLastError(0xdeadbeef);
2304 ctx.ContextFlags = CONTEXT_INTEGER;
2305 ret = GetThreadContext(thread, &ctx);
2306 ok(ret, "GetThreadContext error %d\n", GetLastError());
2307 SetLastError(0xdeadbeef);
2308 ctx.ContextFlags = CONTEXT_INTEGER;
2309 ret = SetThreadContext(thread, &ctx);
2310 ok(ret, "SetThreadContext error %d\n", GetLastError());
2311 SetLastError(0xdeadbeef);
2312 ret = SetThreadPriority(thread, 0);
2313 ok(ret, "SetThreadPriority error %d\n", GetLastError());
2315 SetLastError(0xdeadbeef);
2316 ret = TerminateThread(thread, 199);
2317 ok(ret, "TerminateThread error %d\n", GetLastError());
2318 /* Calling GetExitCodeThread() without waiting for thread termination
2319 * leads to different results due to a race condition.
2321 ret = WaitForSingleObject(thread, 1000);
2322 ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
2323 GetExitCodeThread(thread, &ret);
2324 ok(ret == 199, "expected exit code 199, got %u\n", ret);
2326 SetLastError(0xdeadbeef);
2327 ret = TerminateProcess(pi.hProcess, 198);
2328 ok(ret, "TerminateProcess error %d\n", GetLastError());
2329 /* Checking process state without waiting for process termination
2330 * leads to different results due to a race condition.
2332 ret = WaitForSingleObject(pi.hProcess, 1000);
2333 ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
2335 SetLastError(0xdeadbeef);
2336 process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, pi.dwProcessId);
2337 ok(process != NULL, "OpenProcess error %d\n", GetLastError());
2338 CloseHandle(process);
2340 memset(&pbi, 0, sizeof(pbi));
2341 ret = pNtQueryInformationProcess(pi.hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2342 ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
2343 ok(pbi.ExitStatus == 198, "expected 198, got %lu\n", pbi.ExitStatus);
2344 affinity = 1;
2345 ret = pNtSetInformationProcess(pi.hProcess, ProcessAffinityMask, &affinity, sizeof(affinity));
2346 ok(ret == STATUS_PROCESS_IS_TERMINATING, "expected STATUS_PROCESS_IS_TERMINATING, got %#x\n", ret);
2348 SetLastError(0xdeadbeef);
2349 ctx.ContextFlags = CONTEXT_INTEGER;
2350 ret = GetThreadContext(thread, &ctx);
2351 ok(!ret || broken(ret) /* XP 64-bit */, "GetThreadContext should fail\n");
2352 if (!ret)
2353 ok(GetLastError() == ERROR_INVALID_PARAMETER ||
2354 GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
2355 GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
2356 "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
2357 SetLastError(0xdeadbeef);
2358 ctx.ContextFlags = CONTEXT_INTEGER;
2359 ret = SetThreadContext(thread, &ctx);
2360 ok(!ret || broken(ret) /* XP 64-bit */, "SetThreadContext should fail\n");
2361 if (!ret)
2362 ok(GetLastError() == ERROR_ACCESS_DENIED ||
2363 GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
2364 GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
2365 "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2366 SetLastError(0xdeadbeef);
2367 ret = SetThreadPriority(thread, 0);
2368 ok(ret, "SetThreadPriority error %d\n", GetLastError());
2369 CloseHandle(thread);
2371 SetLastError(0xdeadbeef);
2372 ctx.ContextFlags = CONTEXT_INTEGER;
2373 ret = GetThreadContext(pi.hThread, &ctx);
2374 ok(!ret || broken(ret) /* XP 64-bit */, "GetThreadContext should fail\n");
2375 if (!ret)
2376 ok(GetLastError() == ERROR_INVALID_PARAMETER ||
2377 GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
2378 GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
2379 "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
2380 SetLastError(0xdeadbeef);
2381 ctx.ContextFlags = CONTEXT_INTEGER;
2382 ret = SetThreadContext(pi.hThread, &ctx);
2383 ok(!ret || broken(ret) /* XP 64-bit */, "SetThreadContext should fail\n");
2384 if (!ret)
2385 ok(GetLastError() == ERROR_ACCESS_DENIED ||
2386 GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
2387 GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
2388 "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2389 SetLastError(0xdeadbeef);
2390 ret = VirtualProtectEx(pi.hProcess, addr, 4096, PAGE_READWRITE, &old_prot);
2391 ok(!ret, "VirtualProtectEx should fail\n");
2392 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2393 SetLastError(0xdeadbeef);
2394 size = 0;
2395 ret = ReadProcessMemory(pi.hProcess, addr, buf, 4, &size);
2396 ok(!ret, "ReadProcessMemory should fail\n");
2397 ok(GetLastError() == ERROR_PARTIAL_COPY || GetLastError() == ERROR_ACCESS_DENIED,
2398 "expected ERROR_PARTIAL_COPY, got %d\n", GetLastError());
2399 ok(!size, "expected 0, got %lu\n", size);
2400 SetLastError(0xdeadbeef);
2401 ret = VirtualFreeEx(pi.hProcess, addr, 0, MEM_RELEASE);
2402 ok(!ret, "VirtualFreeEx should fail\n");
2403 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2404 SetLastError(0xdeadbeef);
2405 addr = VirtualAllocEx(pi.hProcess, NULL, 4096, MEM_COMMIT, PAGE_READWRITE);
2406 ok(!addr, "VirtualAllocEx should fail\n");
2407 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2408 SetLastError(0xdeadbeef);
2409 size = VirtualQueryEx(pi.hProcess, NULL, &mbi, sizeof(mbi));
2410 ok(!size, "VirtualQueryEx should fail\n");
2411 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2413 /* CloseHandle() call below leads to premature process termination
2414 * under some Windows versions.
2416 if (0)
2418 SetLastError(0xdeadbeef);
2419 ret = CloseHandle(hmap_dup);
2420 ok(ret, "CloseHandle should not fail\n");
2423 SetLastError(0xdeadbeef);
2424 ret = DuplicateHandle(GetCurrentProcess(), hmap, pi.hProcess, &hmap_dup,
2425 0, FALSE, DUPLICATE_SAME_ACCESS);
2426 ok(!ret, "DuplicateHandle should fail\n");
2427 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2429 offset.u.LowPart = 0;
2430 offset.u.HighPart = 0;
2431 addr = NULL;
2432 size = 0;
2433 ret = pNtMapViewOfSection(hmap, pi.hProcess, &addr, 0, 0, &offset,
2434 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
2435 ok(ret == STATUS_PROCESS_IS_TERMINATING, "expected STATUS_PROCESS_IS_TERMINATING, got %#x\n", ret);
2437 SetLastError(0xdeadbeef);
2438 thread = CreateRemoteThread(pi.hProcess, NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
2439 ok(!thread, "CreateRemoteThread should fail\n");
2440 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2442 SetLastError(0xdeadbeef);
2443 ret = DebugActiveProcess(pi.dwProcessId);
2444 ok(!ret, "DebugActiveProcess should fail\n");
2445 ok(GetLastError() == ERROR_ACCESS_DENIED /* 64-bit */ || GetLastError() == ERROR_NOT_SUPPORTED /* 32-bit */,
2446 "ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2448 GetExitCodeProcess(pi.hProcess, &ret);
2449 ok(ret == 198 || broken(ret != 198) /* some 32-bit XP version in a VM returns random exit code */,
2450 "expected exit code 198, got %u\n", ret);
2451 CloseHandle(pi.hThread);
2452 CloseHandle(pi.hProcess);
2454 ret = DeleteFileA(dll_name);
2455 ok(ret, "DeleteFile error %d\n", GetLastError());
2458 static PVOID WINAPI failuredllhook(ULONG ul, DELAYLOAD_INFO* pd)
2460 ok(ul == 4, "expected 4, got %u\n", ul);
2461 ok(!!pd, "no delayload info supplied\n");
2462 if (pd)
2464 ok(pd->Size == sizeof(*pd), "got %u\n", pd->Size);
2465 ok(!!pd->DelayloadDescriptor, "no DelayloadDescriptor supplied\n");
2466 if (pd->DelayloadDescriptor)
2468 ok(pd->DelayloadDescriptor->Attributes.AllAttributes == 1,
2469 "expected 1, got %u\n", pd->DelayloadDescriptor->Attributes.AllAttributes);
2470 ok(pd->DelayloadDescriptor->DllNameRVA == 0x2000,
2471 "expected 0x2000, got %x\n", pd->DelayloadDescriptor->DllNameRVA);
2472 ok(pd->DelayloadDescriptor->ModuleHandleRVA == 0x201a,
2473 "expected 0x201a, got %x\n", pd->DelayloadDescriptor->ModuleHandleRVA);
2474 ok(pd->DelayloadDescriptor->ImportAddressTableRVA > pd->DelayloadDescriptor->ModuleHandleRVA,
2475 "expected %x > %x\n", pd->DelayloadDescriptor->ImportAddressTableRVA,
2476 pd->DelayloadDescriptor->ModuleHandleRVA);
2477 ok(pd->DelayloadDescriptor->ImportNameTableRVA > pd->DelayloadDescriptor->ImportAddressTableRVA,
2478 "expected %x > %x\n", pd->DelayloadDescriptor->ImportNameTableRVA,
2479 pd->DelayloadDescriptor->ImportAddressTableRVA);
2480 ok(pd->DelayloadDescriptor->BoundImportAddressTableRVA == 0,
2481 "expected 0, got %x\n", pd->DelayloadDescriptor->BoundImportAddressTableRVA);
2482 ok(pd->DelayloadDescriptor->UnloadInformationTableRVA == 0,
2483 "expected 0, got %x\n", pd->DelayloadDescriptor->UnloadInformationTableRVA);
2484 ok(pd->DelayloadDescriptor->TimeDateStamp == 0,
2485 "expected 0, got %x\n", pd->DelayloadDescriptor->TimeDateStamp);
2488 ok(!!pd->ThunkAddress, "no ThunkAddress supplied\n");
2489 if (pd->ThunkAddress)
2490 ok(pd->ThunkAddress->u1.Ordinal == 0, "expected 0, got %x\n", (UINT)pd->ThunkAddress->u1.Ordinal);
2492 ok(!!pd->TargetDllName, "no TargetDllName supplied\n");
2493 if (pd->TargetDllName)
2494 ok(!strcmp(pd->TargetDllName, "secur32.dll"),
2495 "expected \"secur32.dll\", got \"%s\"\n", pd->TargetDllName);
2497 ok(pd->TargetApiDescriptor.ImportDescribedByName == 0,
2498 "expected 0, got %x\n", pd->TargetApiDescriptor.ImportDescribedByName);
2499 ok(pd->TargetApiDescriptor.Description.Ordinal == 0 ||
2500 pd->TargetApiDescriptor.Description.Ordinal == 999,
2501 "expected 0, got %x\n", pd->TargetApiDescriptor.Description.Ordinal);
2503 ok(!!pd->TargetModuleBase, "no TargetModuleBase supplied\n");
2504 ok(pd->Unused == NULL, "expected NULL, got %p\n", pd->Unused);
2505 ok(pd->LastError, "no LastError supplied\n");
2507 cb_count++;
2508 return (void*)0xdeadbeef;
2511 static void test_ResolveDelayLoadedAPI(void)
2513 static const char test_dll[] = "secur32.dll";
2514 static const char test_func[] = "SealMessage";
2515 static const char filler[0x1000];
2516 char temp_path[MAX_PATH];
2517 char dll_name[MAX_PATH];
2518 IMAGE_DELAYLOAD_DESCRIPTOR idd, *delaydir;
2519 IMAGE_THUNK_DATA itd32;
2520 HANDLE hfile;
2521 HMODULE hlib;
2522 DWORD dummy, file_size, i;
2523 WORD hint = 0;
2524 BOOL ret;
2525 IMAGE_NT_HEADERS nt_header;
2527 static const struct test_data
2529 BOOL func;
2530 UINT_PTR ordinal;
2531 BOOL succeeds;
2532 } td[] =
2535 TRUE, 0, TRUE
2538 FALSE, IMAGE_ORDINAL_FLAG | 2, TRUE
2541 FALSE, IMAGE_ORDINAL_FLAG | 5, TRUE
2544 FALSE, IMAGE_ORDINAL_FLAG | 0, FALSE
2547 FALSE, IMAGE_ORDINAL_FLAG | 999, FALSE
2551 if (!pResolveDelayLoadedAPI)
2553 win_skip("ResolveDelayLoadedAPI is not available\n");
2554 return;
2557 if (0) /* crashes on native */
2559 SetLastError(0xdeadbeef);
2560 ok(!pResolveDelayLoadedAPI(NULL, NULL, NULL, NULL, NULL, 0),
2561 "ResolveDelayLoadedAPI succeeded\n");
2562 ok(GetLastError() == 0xdeadbeef, "GetLastError changed to %x\n", GetLastError());
2564 cb_count = 0;
2565 SetLastError(0xdeadbeef);
2566 ok(!pResolveDelayLoadedAPI(NULL, NULL, failuredllhook, NULL, NULL, 0),
2567 "ResolveDelayLoadedAPI succeeded\n");
2568 ok(GetLastError() == 0xdeadbeef, "GetLastError changed to %x\n", GetLastError());
2569 ok(cb_count == 1, "Wrong callback count: %d\n", cb_count);
2572 GetTempPathA(MAX_PATH, temp_path);
2573 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
2574 trace("creating %s\n", dll_name);
2575 hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
2576 if (hfile == INVALID_HANDLE_VALUE)
2578 ok(0, "could not create %s\n", dll_name);
2579 return;
2582 SetLastError(0xdeadbeef);
2583 ret = WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
2584 ok(ret, "WriteFile error %d\n", GetLastError());
2586 nt_header = nt_header_template;
2587 nt_header.FileHeader.NumberOfSections = 2;
2588 nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
2590 nt_header.OptionalHeader.SectionAlignment = 0x1000;
2591 nt_header.OptionalHeader.FileAlignment = 0x1000;
2592 nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x2200;
2593 nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + 2 * sizeof(IMAGE_SECTION_HEADER);
2594 nt_header.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
2595 nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress = 0x1000;
2596 nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size = 0x100;
2598 SetLastError(0xdeadbeef);
2599 ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
2600 ok(ret, "WriteFile error %d\n", GetLastError());
2602 SetLastError(0xdeadbeef);
2603 ret = WriteFile(hfile, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
2604 ok(ret, "WriteFile error %d\n", GetLastError());
2606 /* sections */
2607 section.PointerToRawData = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress;
2608 section.VirtualAddress = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress;
2609 section.Misc.VirtualSize = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
2610 section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
2611 SetLastError(0xdeadbeef);
2612 ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
2613 ok(ret, "WriteFile error %d\n", GetLastError());
2615 section.PointerToRawData = 0x2000;
2616 section.VirtualAddress = 0x2000;
2617 i = sizeof(td)/sizeof(td[0]);
2618 section.Misc.VirtualSize = sizeof(test_dll) + sizeof(hint) + sizeof(test_func) + sizeof(HMODULE) +
2619 2 * (i + 1) * sizeof(IMAGE_THUNK_DATA);
2620 ok(section.Misc.VirtualSize <= 0x1000, "Too much tests, add a new section!\n");
2621 section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
2622 SetLastError(0xdeadbeef);
2623 ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
2624 ok(ret, "WriteFile error %d\n", GetLastError());
2626 /* fill up to delay data */
2627 file_size = GetFileSize(hfile, NULL);
2628 SetLastError(0xdeadbeef);
2629 ret = WriteFile(hfile, filler,
2630 nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress - file_size,
2631 &dummy, NULL);
2632 ok(ret, "WriteFile error %d\n", GetLastError());
2634 /* delay data */
2635 idd.Attributes.AllAttributes = 1;
2636 idd.DllNameRVA = 0x2000;
2637 idd.ModuleHandleRVA = idd.DllNameRVA + sizeof(test_dll) + sizeof(hint) + sizeof(test_func);
2638 idd.ImportAddressTableRVA = idd.ModuleHandleRVA + sizeof(HMODULE);
2639 idd.ImportNameTableRVA = idd.ImportAddressTableRVA + (i + 1) * sizeof(IMAGE_THUNK_DATA);
2640 idd.BoundImportAddressTableRVA = 0;
2641 idd.UnloadInformationTableRVA = 0;
2642 idd.TimeDateStamp = 0;
2644 SetLastError(0xdeadbeef);
2645 ret = WriteFile(hfile, &idd, sizeof(idd), &dummy, NULL);
2646 ok(ret, "WriteFile error %d\n", GetLastError());
2648 SetLastError(0xdeadbeef);
2649 ret = WriteFile(hfile, filler, sizeof(idd), &dummy, NULL);
2650 ok(ret, "WriteFile error %d\n", GetLastError());
2652 /* fill up to extended delay data */
2653 file_size = GetFileSize(hfile, NULL);
2654 SetLastError(0xdeadbeef);
2655 ret = WriteFile(hfile, filler, idd.DllNameRVA - file_size, &dummy, NULL);
2656 ok(ret, "WriteFile error %d\n", GetLastError());
2658 /* extended delay data */
2659 SetLastError(0xdeadbeef);
2660 ret = WriteFile(hfile, test_dll, sizeof(test_dll), &dummy, NULL);
2661 ok(ret, "WriteFile error %d\n", GetLastError());
2663 SetLastError(0xdeadbeef);
2664 ret = WriteFile(hfile, &hint, sizeof(hint), &dummy, NULL);
2665 ok(ret, "WriteFile error %d\n", GetLastError());
2667 SetLastError(0xdeadbeef);
2668 ret = WriteFile(hfile, test_func, sizeof(test_func), &dummy, NULL);
2669 ok(ret, "WriteFile error %d\n", GetLastError());
2671 file_size = GetFileSize(hfile, NULL);
2672 SetLastError(0xdeadbeef);
2673 ret = WriteFile(hfile, filler, idd.ImportNameTableRVA - file_size, &dummy, NULL);
2674 ok(ret, "WriteFile error %d\n", GetLastError());
2676 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
2678 if (td[i].func)
2679 itd32.u1.AddressOfData = idd.DllNameRVA + sizeof(test_dll);
2680 else
2681 itd32.u1.Ordinal = td[i].ordinal;
2682 SetLastError(0xdeadbeef);
2683 ret = WriteFile(hfile, &itd32, sizeof(itd32), &dummy, NULL);
2684 ok(ret, "WriteFile error %d\n", GetLastError());
2687 itd32.u1.Ordinal = 0;
2688 SetLastError(0xdeadbeef);
2689 ret = WriteFile(hfile, &itd32, sizeof(itd32), &dummy, NULL);
2690 ok(ret, "WriteFile error %d\n", GetLastError());
2692 /* fill up to eof */
2693 file_size = GetFileSize(hfile, NULL);
2694 SetLastError(0xdeadbeef);
2695 ret = WriteFile(hfile, filler, section.VirtualAddress + section.Misc.VirtualSize - file_size, &dummy, NULL);
2696 ok(ret, "WriteFile error %d\n", GetLastError());
2697 CloseHandle(hfile);
2699 SetLastError(0xdeadbeef);
2700 hlib = LoadLibraryA(dll_name);
2701 ok(hlib != NULL, "LoadLibrary error %u\n", GetLastError());
2702 if (!hlib)
2704 skip("couldn't load %s.\n", dll_name);
2705 DeleteFileA(dll_name);
2706 return;
2709 delaydir = pRtlImageDirectoryEntryToData(hlib, TRUE, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, &file_size);
2710 if (!delaydir)
2712 skip("haven't found section for delay import directory.\n");
2713 FreeLibrary(hlib);
2714 DeleteFileA(dll_name);
2715 return;
2718 for (;;)
2720 IMAGE_THUNK_DATA *itdn, *itda;
2721 HMODULE htarget;
2723 if (!delaydir->DllNameRVA ||
2724 !delaydir->ImportAddressTableRVA ||
2725 !delaydir->ImportNameTableRVA) break;
2727 itdn = RVAToAddr(delaydir->ImportNameTableRVA, hlib);
2728 itda = RVAToAddr(delaydir->ImportAddressTableRVA, hlib);
2729 htarget = LoadLibraryA(RVAToAddr(delaydir->DllNameRVA, hlib));
2731 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
2733 void *ret, *load;
2735 if (IMAGE_SNAP_BY_ORDINAL(itdn[i].u1.Ordinal))
2736 load = (void *)GetProcAddress(htarget, (LPSTR)IMAGE_ORDINAL(itdn[i].u1.Ordinal));
2737 else
2739 const IMAGE_IMPORT_BY_NAME* iibn = RVAToAddr(itdn[i].u1.AddressOfData, hlib);
2740 load = (void *)GetProcAddress(htarget, (char*)iibn->Name);
2743 cb_count = 0;
2744 ret = pResolveDelayLoadedAPI(hlib, delaydir, failuredllhook, NULL, &itda[i], 0);
2745 if (td[i].succeeds)
2747 ok(ret != NULL, "Test %u: ResolveDelayLoadedAPI failed\n", i);
2748 ok(ret == load, "Test %u: expected %p, got %p\n", i, load, ret);
2749 ok(ret == (void*)itda[i].u1.AddressOfData, "Test %u: expected %p, got %p\n",
2750 i, ret, (void*)itda[i].u1.AddressOfData);
2751 ok(!cb_count, "Test %u: Wrong callback count: %d\n", i, cb_count);
2753 else
2755 ok(ret == (void*)0xdeadbeef, "Test %u: ResolveDelayLoadedAPI succeeded with %p\n", i, ret);
2756 ok(cb_count, "Test %u: Wrong callback count: %d\n", i, cb_count);
2759 delaydir++;
2762 FreeLibrary(hlib);
2763 trace("deleting %s\n", dll_name);
2764 DeleteFileA(dll_name);
2767 static void test_InMemoryOrderModuleList(void)
2769 LIST_ENTRY *entry1, *mark1 = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2770 LIST_ENTRY *entry2, *mark2 = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
2771 LDR_MODULE *module1, *module2;
2773 for (entry1 = mark1->Flink, entry2 = mark2->Flink;
2774 entry1 != mark1 && entry2 != mark2;
2775 entry1 = entry1->Flink, entry2 = entry2->Flink)
2777 module1 = CONTAINING_RECORD(entry1, LDR_MODULE, InLoadOrderModuleList);
2778 module2 = CONTAINING_RECORD(entry2, LDR_MODULE, InMemoryOrderModuleList);
2779 ok(module1 == module2, "expected module1 == module2, got %p and %p\n", module1, module2);
2781 ok(entry1 == mark1, "expected entry1 == mark1, got %p and %p\n", entry1, mark1);
2782 ok(entry2 == mark2, "expected entry2 == mark2, got %p and %p\n", entry2, mark2);
2785 START_TEST(loader)
2787 int argc;
2788 char **argv;
2789 HANDLE ntdll, mapping;
2790 SYSTEM_INFO si;
2792 ntdll = GetModuleHandleA("ntdll.dll");
2793 pNtCreateSection = (void *)GetProcAddress(ntdll, "NtCreateSection");
2794 pNtQuerySection = (void *)GetProcAddress(ntdll, "NtQuerySection");
2795 pNtMapViewOfSection = (void *)GetProcAddress(ntdll, "NtMapViewOfSection");
2796 pNtUnmapViewOfSection = (void *)GetProcAddress(ntdll, "NtUnmapViewOfSection");
2797 pNtTerminateProcess = (void *)GetProcAddress(ntdll, "NtTerminateProcess");
2798 pNtQueryInformationProcess = (void *)GetProcAddress(ntdll, "NtQueryInformationProcess");
2799 pNtSetInformationProcess = (void *)GetProcAddress(ntdll, "NtSetInformationProcess");
2800 pLdrShutdownProcess = (void *)GetProcAddress(ntdll, "LdrShutdownProcess");
2801 pRtlDllShutdownInProgress = (void *)GetProcAddress(ntdll, "RtlDllShutdownInProgress");
2802 pNtAllocateVirtualMemory = (void *)GetProcAddress(ntdll, "NtAllocateVirtualMemory");
2803 pNtFreeVirtualMemory = (void *)GetProcAddress(ntdll, "NtFreeVirtualMemory");
2804 pLdrLockLoaderLock = (void *)GetProcAddress(ntdll, "LdrLockLoaderLock");
2805 pLdrUnlockLoaderLock = (void *)GetProcAddress(ntdll, "LdrUnlockLoaderLock");
2806 pRtlAcquirePebLock = (void *)GetProcAddress(ntdll, "RtlAcquirePebLock");
2807 pRtlReleasePebLock = (void *)GetProcAddress(ntdll, "RtlReleasePebLock");
2808 pRtlImageDirectoryEntryToData = (void *)GetProcAddress(ntdll, "RtlImageDirectoryEntryToData");
2809 pResolveDelayLoadedAPI = (void *)GetProcAddress(GetModuleHandleA("kernel32.dll"), "ResolveDelayLoadedAPI");
2811 GetSystemInfo( &si );
2812 page_size = si.dwPageSize;
2813 dos_header.e_magic = IMAGE_DOS_SIGNATURE;
2814 dos_header.e_lfanew = sizeof(dos_header);
2816 mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, "winetest_loader");
2817 ok(mapping != 0, "CreateFileMapping failed\n");
2818 child_failures = MapViewOfFile(mapping, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 4096);
2819 if (*child_failures == -1)
2821 *child_failures = 0;
2823 else
2824 *child_failures = -1;
2826 argc = winetest_get_mainargs(&argv);
2827 if (argc > 4)
2829 test_dll_phase = atoi(argv[4]);
2830 child_process(argv[2], atol(argv[3]));
2831 return;
2834 test_Loader();
2835 test_ResolveDelayLoadedAPI();
2836 test_ImportDescriptors();
2837 test_section_access();
2838 test_import_resolution();
2839 test_ExitProcess();
2840 test_InMemoryOrderModuleList();