ntdll: Ensure force_exec_prot is also used for views with write watch permissions.
[wine.git] / dlls / kernel32 / tests / loader.c
blobaf437796939866bd1a41ed7f9bfac4d3a347476d
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 *pNtMapViewOfSection)(HANDLE, HANDLE, PVOID *, ULONG, SIZE_T, const LARGE_INTEGER *, SIZE_T *, ULONG, ULONG, ULONG);
56 static NTSTATUS (WINAPI *pNtUnmapViewOfSection)(HANDLE, PVOID);
57 static NTSTATUS (WINAPI *pNtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
58 static NTSTATUS (WINAPI *pNtSetInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG);
59 static NTSTATUS (WINAPI *pNtTerminateProcess)(HANDLE, DWORD);
60 static void (WINAPI *pLdrShutdownProcess)(void);
61 static BOOLEAN (WINAPI *pRtlDllShutdownInProgress)(void);
62 static NTSTATUS (WINAPI *pNtAllocateVirtualMemory)(HANDLE, PVOID *, ULONG, SIZE_T *, ULONG, ULONG);
63 static NTSTATUS (WINAPI *pNtFreeVirtualMemory)(HANDLE, PVOID *, SIZE_T *, ULONG);
64 static NTSTATUS (WINAPI *pLdrLockLoaderLock)(ULONG, ULONG *, ULONG_PTR *);
65 static NTSTATUS (WINAPI *pLdrUnlockLoaderLock)(ULONG, ULONG_PTR);
66 static void (WINAPI *pRtlAcquirePebLock)(void);
67 static void (WINAPI *pRtlReleasePebLock)(void);
68 static PVOID (WINAPI *pResolveDelayLoadedAPI)(PVOID, PCIMAGE_DELAYLOAD_DESCRIPTOR,
69 PDELAYLOAD_FAILURE_DLL_CALLBACK, PVOID,
70 PIMAGE_THUNK_DATA ThunkAddress,ULONG);
72 static PVOID RVAToAddr(DWORD_PTR rva, HMODULE module)
74 if (rva == 0)
75 return NULL;
76 return ((char*) module) + rva;
79 static IMAGE_DOS_HEADER dos_header;
81 static IMAGE_NT_HEADERS nt_header =
83 IMAGE_NT_SIGNATURE, /* Signature */
85 #if defined __i386__
86 IMAGE_FILE_MACHINE_I386, /* Machine */
87 #elif defined __x86_64__
88 IMAGE_FILE_MACHINE_AMD64, /* Machine */
89 #elif defined __powerpc__
90 IMAGE_FILE_MACHINE_POWERPC, /* Machine */
91 #elif defined __arm__
92 IMAGE_FILE_MACHINE_ARMNT, /* Machine */
93 #elif defined __aarch64__
94 IMAGE_FILE_MACHINE_ARM64, /* Machine */
95 #else
96 # error You must specify the machine type
97 #endif
98 1, /* NumberOfSections */
99 0, /* TimeDateStamp */
100 0, /* PointerToSymbolTable */
101 0, /* NumberOfSymbols */
102 sizeof(IMAGE_OPTIONAL_HEADER), /* SizeOfOptionalHeader */
103 IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL /* Characteristics */
105 { IMAGE_NT_OPTIONAL_HDR_MAGIC, /* Magic */
106 1, /* MajorLinkerVersion */
107 0, /* MinorLinkerVersion */
108 0, /* SizeOfCode */
109 0, /* SizeOfInitializedData */
110 0, /* SizeOfUninitializedData */
111 0, /* AddressOfEntryPoint */
112 0x10, /* BaseOfCode, also serves as e_lfanew in the truncated MZ header */
113 #ifndef _WIN64
114 0, /* BaseOfData */
115 #endif
116 0x10000000, /* ImageBase */
117 0, /* SectionAlignment */
118 0, /* FileAlignment */
119 4, /* MajorOperatingSystemVersion */
120 0, /* MinorOperatingSystemVersion */
121 1, /* MajorImageVersion */
122 0, /* MinorImageVersion */
123 4, /* MajorSubsystemVersion */
124 0, /* MinorSubsystemVersion */
125 0, /* Win32VersionValue */
126 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000, /* SizeOfImage */
127 sizeof(dos_header) + sizeof(nt_header), /* SizeOfHeaders */
128 0, /* CheckSum */
129 IMAGE_SUBSYSTEM_WINDOWS_CUI, /* Subsystem */
130 0, /* DllCharacteristics */
131 0, /* SizeOfStackReserve */
132 0, /* SizeOfStackCommit */
133 0, /* SizeOfHeapReserve */
134 0, /* SizeOfHeapCommit */
135 0, /* LoaderFlags */
136 0, /* NumberOfRvaAndSizes */
137 { { 0 } } /* DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] */
141 static IMAGE_SECTION_HEADER section =
143 ".rodata", /* Name */
144 { 0x10 }, /* Misc */
145 0, /* VirtualAddress */
146 0x0a, /* SizeOfRawData */
147 0, /* PointerToRawData */
148 0, /* PointerToRelocations */
149 0, /* PointerToLinenumbers */
150 0, /* NumberOfRelocations */
151 0, /* NumberOfLinenumbers */
152 IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, /* Characteristics */
156 static const char filler[0x1000];
157 static const char section_data[0x10] = "section data";
159 static DWORD create_test_dll( const IMAGE_DOS_HEADER *dos_header, UINT dos_size,
160 const IMAGE_NT_HEADERS *nt_header, const char *dll_name )
162 DWORD dummy, size, file_align;
163 HANDLE hfile;
164 BOOL ret;
166 hfile = CreateFileA(dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0);
167 if (hfile == INVALID_HANDLE_VALUE) return 0;
169 SetLastError(0xdeadbeef);
170 ret = WriteFile(hfile, dos_header, dos_size, &dummy, NULL);
171 ok(ret, "WriteFile error %d\n", GetLastError());
173 SetLastError(0xdeadbeef);
174 ret = WriteFile(hfile, nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
175 ok(ret, "WriteFile error %d\n", GetLastError());
177 if (nt_header->FileHeader.SizeOfOptionalHeader)
179 SetLastError(0xdeadbeef);
180 ret = WriteFile(hfile, &nt_header->OptionalHeader,
181 min(nt_header->FileHeader.SizeOfOptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER)),
182 &dummy, NULL);
183 ok(ret, "WriteFile error %d\n", GetLastError());
184 if (nt_header->FileHeader.SizeOfOptionalHeader > sizeof(IMAGE_OPTIONAL_HEADER))
186 file_align = nt_header->FileHeader.SizeOfOptionalHeader - sizeof(IMAGE_OPTIONAL_HEADER);
187 assert(file_align < sizeof(filler));
188 SetLastError(0xdeadbeef);
189 ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
190 ok(ret, "WriteFile error %d\n", GetLastError());
194 assert(nt_header->FileHeader.NumberOfSections <= 1);
195 if (nt_header->FileHeader.NumberOfSections)
197 if (nt_header->OptionalHeader.SectionAlignment >= page_size)
199 section.PointerToRawData = dos_size;
200 section.VirtualAddress = nt_header->OptionalHeader.SectionAlignment;
201 section.Misc.VirtualSize = section.SizeOfRawData * 10;
203 else
205 section.PointerToRawData = nt_header->OptionalHeader.SizeOfHeaders;
206 section.VirtualAddress = nt_header->OptionalHeader.SizeOfHeaders;
207 section.Misc.VirtualSize = 5;
210 SetLastError(0xdeadbeef);
211 ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
212 ok(ret, "WriteFile error %d\n", GetLastError());
214 /* section data */
215 SetLastError(0xdeadbeef);
216 ret = WriteFile(hfile, section_data, sizeof(section_data), &dummy, NULL);
217 ok(ret, "WriteFile error %d\n", GetLastError());
219 size = GetFileSize(hfile, NULL);
220 CloseHandle(hfile);
221 return size;
224 /* helper to test image section mapping */
225 static NTSTATUS map_image_section( const IMAGE_NT_HEADERS *nt_header )
227 char temp_path[MAX_PATH];
228 char dll_name[MAX_PATH];
229 LARGE_INTEGER size;
230 HANDLE file, map;
231 NTSTATUS status;
233 GetTempPathA(MAX_PATH, temp_path);
234 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
236 size.u.LowPart = create_test_dll( &dos_header, sizeof(dos_header), nt_header, dll_name );
237 ok( size.u.LowPart, "could not create %s\n", dll_name);
238 size.u.HighPart = 0;
240 file = CreateFileA(dll_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
241 ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
243 status = pNtCreateSection(&map, STANDARD_RIGHTS_REQUIRED | SECTION_MAP_READ, NULL, &size,
244 PAGE_READONLY, SEC_IMAGE, file );
245 if (map) CloseHandle( map );
246 CloseHandle( file );
247 DeleteFileA( dll_name );
248 return status;
252 static void test_Loader(void)
254 static const struct test_data
256 DWORD size_of_dos_header;
257 WORD number_of_sections, size_of_optional_header;
258 DWORD section_alignment, file_alignment;
259 DWORD size_of_image, size_of_headers;
260 DWORD errors[4]; /* 0 means LoadLibrary should succeed */
261 } td[] =
263 { sizeof(dos_header),
264 1, 0, 0, 0, 0, 0,
265 { ERROR_BAD_EXE_FORMAT }
267 { sizeof(dos_header),
268 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
269 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0xe00,
270 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
271 { ERROR_BAD_EXE_FORMAT } /* XP doesn't like too small image size */
273 { sizeof(dos_header),
274 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
275 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
276 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
277 { ERROR_SUCCESS }
279 { sizeof(dos_header),
280 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
281 0x1f00,
282 0x1000,
283 { ERROR_SUCCESS }
285 { sizeof(dos_header),
286 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x200, 0x200,
287 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x200,
288 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
289 { ERROR_SUCCESS, ERROR_INVALID_ADDRESS } /* vista is more strict */
291 { sizeof(dos_header),
292 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x200, 0x1000,
293 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
294 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
295 { ERROR_BAD_EXE_FORMAT } /* XP doesn't like alignments */
297 { sizeof(dos_header),
298 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x200,
299 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
300 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER),
301 { ERROR_SUCCESS }
303 { sizeof(dos_header),
304 1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x200,
305 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
306 0x200,
307 { ERROR_SUCCESS }
309 /* Mandatory are all fields up to SizeOfHeaders, everything else
310 * is really optional (at least that's true for XP).
312 { sizeof(dos_header),
313 1, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
314 sizeof(dos_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum) + sizeof(IMAGE_SECTION_HEADER) + 0x10,
315 sizeof(dos_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum) + sizeof(IMAGE_SECTION_HEADER),
316 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT, ERROR_INVALID_ADDRESS,
317 ERROR_NOACCESS }
319 { sizeof(dos_header),
320 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
321 0xd0, /* beyond of the end of file */
322 0xc0, /* beyond of the end of file */
323 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
325 { sizeof(dos_header),
326 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
327 0x1000,
329 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
331 { sizeof(dos_header),
332 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
335 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
337 #if 0 /* not power of 2 alignments need more test cases */
338 { sizeof(dos_header),
339 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x300, 0x300,
342 { ERROR_BAD_EXE_FORMAT } /* alignment is not power of 2 */
344 #endif
345 { sizeof(dos_header),
346 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 4, 4,
349 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
351 { sizeof(dos_header),
352 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 1, 1,
355 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
357 { sizeof(dos_header),
358 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
361 { ERROR_BAD_EXE_FORMAT } /* image size == 0 -> failure */
363 /* the following data mimics the PE image which upack creates */
364 { 0x10,
365 1, 0x148, 0x1000, 0x200,
366 sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
367 0x200,
368 { ERROR_SUCCESS }
370 /* Minimal PE image that XP is able to load: 92 bytes */
371 { 0x04,
372 0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum),
373 0x04 /* also serves as e_lfanew in the truncated MZ header */, 0x04,
376 { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
379 int i;
380 DWORD file_size;
381 HMODULE hlib, hlib_as_data_file;
382 char temp_path[MAX_PATH];
383 char dll_name[MAX_PATH];
384 SIZE_T size;
385 BOOL ret;
386 NTSTATUS status;
387 WORD orig_machine = nt_header.FileHeader.Machine;
389 /* prevent displaying of the "Unable to load this DLL" message box */
390 SetErrorMode(SEM_FAILCRITICALERRORS);
392 GetTempPathA(MAX_PATH, temp_path);
394 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
396 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
398 nt_header.FileHeader.NumberOfSections = td[i].number_of_sections;
399 nt_header.FileHeader.SizeOfOptionalHeader = td[i].size_of_optional_header;
401 nt_header.OptionalHeader.SectionAlignment = td[i].section_alignment;
402 nt_header.OptionalHeader.FileAlignment = td[i].file_alignment;
403 nt_header.OptionalHeader.SizeOfImage = td[i].size_of_image;
404 nt_header.OptionalHeader.SizeOfHeaders = td[i].size_of_headers;
406 file_size = create_test_dll( &dos_header, td[i].size_of_dos_header, &nt_header, dll_name );
407 if (!file_size)
409 ok(0, "could not create %s\n", dll_name);
410 break;
413 SetLastError(0xdeadbeef);
414 hlib = LoadLibraryA(dll_name);
415 if (hlib)
417 MEMORY_BASIC_INFORMATION info;
418 void *ptr;
420 ok( td[i].errors[0] == ERROR_SUCCESS, "%d: should have failed\n", i );
422 SetLastError(0xdeadbeef);
423 size = VirtualQuery(hlib, &info, sizeof(info));
424 ok(size == sizeof(info),
425 "%d: VirtualQuery error %d\n", i, GetLastError());
426 ok(info.BaseAddress == hlib, "%d: %p != %p\n", i, info.BaseAddress, hlib);
427 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
428 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
429 ok(info.RegionSize == ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %lx != expected %x\n",
430 i, info.RegionSize, ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
431 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
432 if (nt_header.OptionalHeader.SectionAlignment < page_size)
433 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
434 else
435 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
436 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
438 SetLastError(0xdeadbeef);
439 ptr = VirtualAlloc(hlib, page_size, MEM_COMMIT, info.Protect);
440 ok(!ptr, "%d: VirtualAlloc should fail\n", i);
441 /* FIXME: Remove once Wine is fixed */
442 if (info.Protect == PAGE_WRITECOPY || info.Protect == PAGE_EXECUTE_WRITECOPY)
443 todo_wine
444 ok(GetLastError() == ERROR_ACCESS_DENIED, "%d: expected ERROR_ACCESS_DENIED, got %d\n", i, GetLastError());
445 else
446 ok(GetLastError() == ERROR_ACCESS_DENIED, "%d: expected ERROR_ACCESS_DENIED, got %d\n", i, GetLastError());
448 SetLastError(0xdeadbeef);
449 size = VirtualQuery((char *)hlib + info.RegionSize, &info, sizeof(info));
450 ok(size == sizeof(info),
451 "%d: VirtualQuery error %d\n", i, GetLastError());
452 if (nt_header.OptionalHeader.SectionAlignment == page_size ||
453 nt_header.OptionalHeader.SectionAlignment == nt_header.OptionalHeader.FileAlignment)
455 ok(info.BaseAddress == (char *)hlib + ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %p != expected %p\n",
456 i, info.BaseAddress, (char *)hlib + ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
457 ok(info.AllocationBase == 0, "%d: %p != 0\n", i, info.AllocationBase);
458 ok(info.AllocationProtect == 0, "%d: %x != 0\n", i, info.AllocationProtect);
459 /*ok(info.RegionSize == not_practical_value, "%d: %lx != not_practical_value\n", i, info.RegionSize);*/
460 ok(info.State == MEM_FREE, "%d: %x != MEM_FREE\n", i, info.State);
461 ok(info.Type == 0, "%d: %x != 0\n", i, info.Type);
462 ok(info.Protect == PAGE_NOACCESS, "%d: %x != PAGE_NOACCESS\n", i, info.Protect);
464 else
466 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
467 ok(info.BaseAddress == hlib, "%d: got %p != expected %p\n", i, info.BaseAddress, hlib);
468 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
469 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
470 ok(info.RegionSize == ALIGN_SIZE(file_size, page_size), "%d: got %lx != expected %x\n",
471 i, info.RegionSize, ALIGN_SIZE(file_size, page_size));
472 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
473 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
474 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
477 /* header: check the zeroing of alignment */
478 if (nt_header.OptionalHeader.SectionAlignment >= page_size)
480 const char *start;
482 start = (const char *)hlib + nt_header.OptionalHeader.SizeOfHeaders;
483 size = ALIGN_SIZE((ULONG_PTR)start, page_size) - (ULONG_PTR)start;
484 ok(!memcmp(start, filler, size), "%d: header alignment is not cleared\n", i);
487 if (nt_header.FileHeader.NumberOfSections)
489 SetLastError(0xdeadbeef);
490 size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
491 ok(size == sizeof(info),
492 "%d: VirtualQuery error %d\n", i, GetLastError());
493 if (nt_header.OptionalHeader.SectionAlignment < page_size)
495 ok(info.BaseAddress == hlib, "%d: got %p != expected %p\n", i, info.BaseAddress, hlib);
496 ok(info.RegionSize == ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %lx != expected %x\n",
497 i, info.RegionSize, ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
498 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
500 else
502 ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
503 ok(info.RegionSize == ALIGN_SIZE(section.Misc.VirtualSize, page_size), "%d: got %lx != expected %x\n",
504 i, info.RegionSize, ALIGN_SIZE(section.Misc.VirtualSize, page_size));
505 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
507 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
508 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
509 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
510 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
512 if (nt_header.OptionalHeader.SectionAlignment >= page_size)
513 ok(!memcmp((const char *)hlib + section.VirtualAddress + section.PointerToRawData, &nt_header, section.SizeOfRawData), "wrong section data\n");
514 else
515 ok(!memcmp((const char *)hlib + section.PointerToRawData, section_data, section.SizeOfRawData), "wrong section data\n");
517 /* check the zeroing of alignment */
518 if (nt_header.OptionalHeader.SectionAlignment >= page_size)
520 const char *start;
522 start = (const char *)hlib + section.VirtualAddress + section.PointerToRawData + section.SizeOfRawData;
523 size = ALIGN_SIZE((ULONG_PTR)start, page_size) - (ULONG_PTR)start;
524 ok(memcmp(start, filler, size), "%d: alignment should not be cleared\n", i);
527 SetLastError(0xdeadbeef);
528 ptr = VirtualAlloc((char *)hlib + section.VirtualAddress, page_size, MEM_COMMIT, info.Protect);
529 ok(!ptr, "%d: VirtualAlloc should fail\n", i);
530 /* FIXME: Remove once Wine is fixed */
531 if (info.Protect == PAGE_WRITECOPY || info.Protect == PAGE_EXECUTE_WRITECOPY)
532 todo_wine
533 ok(GetLastError() == ERROR_ACCESS_DENIED || GetLastError() == ERROR_INVALID_ADDRESS,
534 "%d: expected ERROR_ACCESS_DENIED, got %d\n", i, GetLastError());
535 else
536 ok(GetLastError() == ERROR_ACCESS_DENIED || GetLastError() == ERROR_INVALID_ADDRESS,
537 "%d: expected ERROR_ACCESS_DENIED, got %d\n", i, GetLastError());
540 SetLastError(0xdeadbeef);
541 hlib_as_data_file = LoadLibraryExA(dll_name, 0, LOAD_LIBRARY_AS_DATAFILE);
542 ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
543 ok(hlib_as_data_file == hlib, "hlib_as_file and hlib are different\n");
545 SetLastError(0xdeadbeef);
546 ret = FreeLibrary(hlib);
547 ok(ret, "FreeLibrary error %d\n", GetLastError());
549 SetLastError(0xdeadbeef);
550 hlib = GetModuleHandleA(dll_name);
551 ok(hlib != 0, "GetModuleHandle error %u\n", GetLastError());
553 SetLastError(0xdeadbeef);
554 ret = FreeLibrary(hlib_as_data_file);
555 ok(ret, "FreeLibrary error %d\n", GetLastError());
557 hlib = GetModuleHandleA(dll_name);
558 ok(!hlib, "GetModuleHandle should fail\n");
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((ULONG_PTR)hlib_as_data_file & 1, "hlib_as_data_file is even\n");
565 hlib = GetModuleHandleA(dll_name);
566 ok(!hlib, "GetModuleHandle should fail\n");
568 SetLastError(0xdeadbeef);
569 ret = FreeLibrary(hlib_as_data_file);
570 ok(ret, "FreeLibrary error %d\n", GetLastError());
572 else
574 BOOL error_match;
575 int error_index;
577 error_match = FALSE;
578 for (error_index = 0;
579 ! error_match && error_index < sizeof(td[i].errors) / sizeof(DWORD);
580 error_index++)
582 error_match = td[i].errors[error_index] == GetLastError();
584 ok(error_match, "%d: unexpected error %d\n", i, GetLastError());
587 SetLastError(0xdeadbeef);
588 ret = DeleteFileA(dll_name);
589 ok(ret, "DeleteFile error %d\n", GetLastError());
592 nt_header.FileHeader.NumberOfSections = 1;
593 nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
595 nt_header.OptionalHeader.SectionAlignment = page_size;
596 nt_header.OptionalHeader.FileAlignment = page_size;
597 nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
598 nt_header.OptionalHeader.SizeOfImage = nt_header.OptionalHeader.SizeOfImage + page_size;
600 status = map_image_section( &nt_header );
601 ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
603 dos_header.e_magic = 0;
604 status = map_image_section( &nt_header );
605 ok( status == STATUS_INVALID_IMAGE_NOT_MZ, "NtCreateSection error %08x\n", status );
607 dos_header.e_magic = IMAGE_DOS_SIGNATURE;
608 nt_header.Signature = IMAGE_OS2_SIGNATURE;
609 status = map_image_section( &nt_header );
610 ok( status == STATUS_INVALID_IMAGE_NE_FORMAT, "NtCreateSection error %08x\n", status );
612 nt_header.Signature = 0xdeadbeef;
613 status = map_image_section( &nt_header );
614 ok( status == STATUS_INVALID_IMAGE_PROTECT, "NtCreateSection error %08x\n", status );
616 nt_header.Signature = IMAGE_NT_SIGNATURE;
617 nt_header.OptionalHeader.Magic = 0xdead;
618 status = map_image_section( &nt_header );
619 ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
621 nt_header.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
622 nt_header.FileHeader.Machine = 0xdead;
623 status = map_image_section( &nt_header );
624 ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
625 "NtCreateSection error %08x\n", status );
627 nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_UNKNOWN;
628 status = map_image_section( &nt_header );
629 ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
630 "NtCreateSection error %08x\n", status );
632 switch (orig_machine)
634 case IMAGE_FILE_MACHINE_I386: nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; break;
635 case IMAGE_FILE_MACHINE_AMD64: nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_I386; break;
636 case IMAGE_FILE_MACHINE_ARMNT: nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_ARM64; break;
637 case IMAGE_FILE_MACHINE_ARM64: nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_ARMNT; break;
639 status = map_image_section( &nt_header );
640 ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
641 "NtCreateSection error %08x\n", status );
643 if (nt_header.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
645 IMAGE_NT_HEADERS64 nt64;
647 memset( &nt64, 0, sizeof(nt64) );
648 nt64.Signature = IMAGE_NT_SIGNATURE;
649 nt64.FileHeader.Machine = orig_machine;
650 nt64.FileHeader.NumberOfSections = 1;
651 nt64.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
652 nt64.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
653 nt64.OptionalHeader.MajorLinkerVersion = 1;
654 nt64.OptionalHeader.ImageBase = 0x10000000;
655 nt64.OptionalHeader.MajorOperatingSystemVersion = 4;
656 nt64.OptionalHeader.MajorImageVersion = 1;
657 nt64.OptionalHeader.MajorSubsystemVersion = 4;
658 nt64.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt64) + sizeof(IMAGE_SECTION_HEADER);
659 nt64.OptionalHeader.SizeOfImage = nt64.OptionalHeader.SizeOfHeaders + 0x1000;
660 nt64.OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
661 status = map_image_section( (IMAGE_NT_HEADERS *)&nt64 );
662 ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
664 else
666 IMAGE_NT_HEADERS32 nt32;
668 memset( &nt32, 0, sizeof(nt32) );
669 nt32.Signature = IMAGE_NT_SIGNATURE;
670 nt32.FileHeader.Machine = orig_machine;
671 nt32.FileHeader.NumberOfSections = 1;
672 nt32.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER32);
673 nt32.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC;
674 nt32.OptionalHeader.MajorLinkerVersion = 1;
675 nt32.OptionalHeader.ImageBase = 0x10000000;
676 nt32.OptionalHeader.MajorOperatingSystemVersion = 4;
677 nt32.OptionalHeader.MajorImageVersion = 1;
678 nt32.OptionalHeader.MajorSubsystemVersion = 4;
679 nt32.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt32) + sizeof(IMAGE_SECTION_HEADER);
680 nt32.OptionalHeader.SizeOfImage = nt32.OptionalHeader.SizeOfHeaders + 0x1000;
681 nt32.OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
682 status = map_image_section( (IMAGE_NT_HEADERS *)&nt32 );
683 ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
686 nt_header.FileHeader.Machine = orig_machine; /* restore it for the next tests */
689 /* Verify linking style of import descriptors */
690 static void test_ImportDescriptors(void)
692 HMODULE kernel32_module = NULL;
693 PIMAGE_DOS_HEADER d_header;
694 PIMAGE_NT_HEADERS nt_headers;
695 DWORD import_dir_size;
696 DWORD_PTR dir_offset;
697 PIMAGE_IMPORT_DESCRIPTOR import_chunk;
699 /* Load kernel32 module */
700 kernel32_module = GetModuleHandleA("kernel32.dll");
701 assert( kernel32_module != NULL );
703 /* Get PE header info from module image */
704 d_header = (PIMAGE_DOS_HEADER) kernel32_module;
705 nt_headers = (PIMAGE_NT_HEADERS) (((char*) d_header) +
706 d_header->e_lfanew);
708 /* Get size of import entry directory */
709 import_dir_size = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size;
710 if (!import_dir_size)
712 skip("Unable to continue testing due to missing import directory.\n");
713 return;
716 /* Get address of first import chunk */
717 dir_offset = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
718 import_chunk = RVAToAddr(dir_offset, kernel32_module);
719 ok(import_chunk != 0, "Invalid import_chunk: %p\n", import_chunk);
720 if (!import_chunk) return;
722 /* Iterate through import descriptors and verify set name,
723 * OriginalFirstThunk, and FirstThunk. Core Windows DLLs, such as
724 * kernel32.dll, don't use Borland-style linking, where the table of
725 * imported names is stored directly in FirstThunk and overwritten
726 * by the relocation, instead of being stored in OriginalFirstThunk.
727 * */
728 for (; import_chunk->FirstThunk; import_chunk++)
730 LPCSTR module_name = RVAToAddr(import_chunk->Name, kernel32_module);
731 PIMAGE_THUNK_DATA name_table = RVAToAddr(
732 U(*import_chunk).OriginalFirstThunk, kernel32_module);
733 PIMAGE_THUNK_DATA iat = RVAToAddr(
734 import_chunk->FirstThunk, kernel32_module);
735 ok(module_name != NULL, "Imported module name should not be NULL\n");
736 ok(name_table != NULL,
737 "Name table for imported module %s should not be NULL\n",
738 module_name);
739 ok(iat != NULL, "IAT for imported module %s should not be NULL\n",
740 module_name);
744 static void test_image_mapping(const char *dll_name, DWORD scn_page_access, BOOL is_dll)
746 HANDLE hfile, hmap;
747 NTSTATUS status;
748 LARGE_INTEGER offset;
749 SIZE_T size;
750 void *addr1, *addr2;
751 MEMORY_BASIC_INFORMATION info;
753 if (!pNtMapViewOfSection) return;
755 SetLastError(0xdeadbeef);
756 hfile = CreateFileA(dll_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
757 ok(hfile != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
759 SetLastError(0xdeadbeef);
760 hmap = CreateFileMappingW(hfile, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, 0);
761 ok(hmap != 0, "CreateFileMapping error %d\n", GetLastError());
763 offset.u.LowPart = 0;
764 offset.u.HighPart = 0;
766 addr1 = NULL;
767 size = 0;
768 status = pNtMapViewOfSection(hmap, GetCurrentProcess(), &addr1, 0, 0, &offset,
769 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
770 ok(status == STATUS_SUCCESS, "NtMapViewOfSection error %x\n", status);
771 ok(addr1 != 0, "mapped address should be valid\n");
773 SetLastError(0xdeadbeef);
774 size = VirtualQuery((char *)addr1 + section.VirtualAddress, &info, sizeof(info));
775 ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
776 ok(info.BaseAddress == (char *)addr1 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr1 + section.VirtualAddress);
777 ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
778 ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
779 ok(info.AllocationBase == addr1, "%p != %p\n", info.AllocationBase, addr1);
780 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
781 ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
782 ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
784 addr2 = NULL;
785 size = 0;
786 status = pNtMapViewOfSection(hmap, GetCurrentProcess(), &addr2, 0, 0, &offset,
787 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
788 /* FIXME: remove once Wine is fixed */
789 if (status != STATUS_IMAGE_NOT_AT_BASE)
791 todo_wine {
792 ok(status == STATUS_IMAGE_NOT_AT_BASE, "expected STATUS_IMAGE_NOT_AT_BASE, got %x\n", status);
793 ok(addr2 != 0, "mapped address should be valid\n");
795 goto wine_is_broken;
797 ok(status == STATUS_IMAGE_NOT_AT_BASE, "expected STATUS_IMAGE_NOT_AT_BASE, got %x\n", status);
798 ok(addr2 != 0, "mapped address should be valid\n");
799 ok(addr2 != addr1, "mapped addresses should be different\n");
801 SetLastError(0xdeadbeef);
802 size = VirtualQuery((char *)addr2 + section.VirtualAddress, &info, sizeof(info));
803 ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
804 ok(info.BaseAddress == (char *)addr2 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr2 + section.VirtualAddress);
805 ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
806 ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
807 ok(info.AllocationBase == addr2, "%p != %p\n", info.AllocationBase, addr2);
808 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
809 ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
810 ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
812 status = pNtUnmapViewOfSection(GetCurrentProcess(), addr2);
813 ok(status == STATUS_SUCCESS, "NtUnmapViewOfSection error %x\n", status);
815 addr2 = MapViewOfFile(hmap, 0, 0, 0, 0);
816 ok(addr2 != 0, "mapped address should be valid\n");
817 ok(addr2 != addr1, "mapped addresses should be different\n");
819 SetLastError(0xdeadbeef);
820 size = VirtualQuery((char *)addr2 + section.VirtualAddress, &info, sizeof(info));
821 ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
822 ok(info.BaseAddress == (char *)addr2 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr2 + section.VirtualAddress);
823 ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
824 ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
825 ok(info.AllocationBase == addr2, "%p != %p\n", info.AllocationBase, addr2);
826 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
827 ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
828 ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
830 UnmapViewOfFile(addr2);
832 SetLastError(0xdeadbeef);
833 addr2 = LoadLibraryA(dll_name);
834 if (is_dll)
836 ok(!addr2, "LoadLibrary should fail, is_dll %d\n", is_dll);
837 ok(GetLastError() == ERROR_INVALID_ADDRESS, "expected ERROR_INVALID_ADDRESS, got %d\n", GetLastError());
839 else
841 BOOL ret;
842 ok(addr2 != 0, "LoadLibrary error %d, is_dll %d\n", GetLastError(), is_dll);
843 ok(addr2 != addr1, "mapped addresses should be different\n");
845 SetLastError(0xdeadbeef);
846 ret = FreeLibrary(addr2);
847 ok(ret, "FreeLibrary error %d\n", GetLastError());
850 wine_is_broken:
851 status = pNtUnmapViewOfSection(GetCurrentProcess(), addr1);
852 ok(status == STATUS_SUCCESS, "NtUnmapViewOfSection error %x\n", status);
854 CloseHandle(hmap);
855 CloseHandle(hfile);
858 static BOOL is_mem_writable(DWORD prot)
860 switch (prot & 0xff)
862 case PAGE_READWRITE:
863 case PAGE_WRITECOPY:
864 case PAGE_EXECUTE_READWRITE:
865 case PAGE_EXECUTE_WRITECOPY:
866 return TRUE;
868 default:
869 return FALSE;
873 static void test_VirtualProtect(void *base, void *section)
875 static const struct test_data
877 DWORD prot_set, prot_get;
878 } td[] =
880 { 0, 0 }, /* 0x00 */
881 { PAGE_NOACCESS, PAGE_NOACCESS }, /* 0x01 */
882 { PAGE_READONLY, PAGE_READONLY }, /* 0x02 */
883 { PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x03 */
884 { PAGE_READWRITE, PAGE_WRITECOPY }, /* 0x04 */
885 { PAGE_READWRITE | PAGE_NOACCESS, 0 }, /* 0x05 */
886 { PAGE_READWRITE | PAGE_READONLY, 0 }, /* 0x06 */
887 { PAGE_READWRITE | PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x07 */
888 { PAGE_WRITECOPY, PAGE_WRITECOPY }, /* 0x08 */
889 { PAGE_WRITECOPY | PAGE_NOACCESS, 0 }, /* 0x09 */
890 { PAGE_WRITECOPY | PAGE_READONLY, 0 }, /* 0x0a */
891 { PAGE_WRITECOPY | PAGE_NOACCESS | PAGE_READONLY, 0 }, /* 0x0b */
892 { PAGE_WRITECOPY | PAGE_READWRITE, 0 }, /* 0x0c */
893 { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_NOACCESS, 0 }, /* 0x0d */
894 { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_READONLY, 0 }, /* 0x0e */
895 { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x0f */
897 { PAGE_EXECUTE, PAGE_EXECUTE }, /* 0x10 */
898 { PAGE_EXECUTE_READ, PAGE_EXECUTE_READ }, /* 0x20 */
899 { PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0x30 */
900 { PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY }, /* 0x40 */
901 { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0x50 */
902 { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0x60 */
903 { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0x70 */
904 { PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_WRITECOPY }, /* 0x80 */
905 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE, 0 }, /* 0x90 */
906 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ, 0 }, /* 0xa0 */
907 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0xb0 */
908 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE, 0 }, /* 0xc0 */
909 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0xd0 */
910 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0xe0 */
911 { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 } /* 0xf0 */
913 DWORD ret, orig_prot, old_prot, rw_prot, exec_prot, i, j;
914 MEMORY_BASIC_INFORMATION info;
916 SetLastError(0xdeadbeef);
917 ret = VirtualProtect(section, page_size, PAGE_NOACCESS, &old_prot);
918 ok(ret, "VirtualProtect error %d\n", GetLastError());
920 orig_prot = old_prot;
922 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
924 SetLastError(0xdeadbeef);
925 ret = VirtualQuery(section, &info, sizeof(info));
926 ok(ret, "VirtualQuery failed %d\n", GetLastError());
927 ok(info.BaseAddress == section, "%d: got %p != expected %p\n", i, info.BaseAddress, section);
928 ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
929 ok(info.Protect == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, info.Protect);
930 ok(info.AllocationBase == base, "%d: %p != %p\n", i, info.AllocationBase, base);
931 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
932 ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
933 ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
935 old_prot = 0xdeadbeef;
936 SetLastError(0xdeadbeef);
937 ret = VirtualProtect(section, page_size, td[i].prot_set, &old_prot);
938 if (td[i].prot_get)
940 ok(ret, "%d: VirtualProtect error %d, requested prot %#x\n", i, GetLastError(), td[i].prot_set);
941 ok(old_prot == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, old_prot);
943 SetLastError(0xdeadbeef);
944 ret = VirtualQuery(section, &info, sizeof(info));
945 ok(ret, "VirtualQuery failed %d\n", GetLastError());
946 ok(info.BaseAddress == section, "%d: got %p != expected %p\n", i, info.BaseAddress, section);
947 ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
948 ok(info.Protect == td[i].prot_get, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].prot_get);
949 ok(info.AllocationBase == base, "%d: %p != %p\n", i, info.AllocationBase, base);
950 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
951 ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
952 ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
954 else
956 ok(!ret, "%d: VirtualProtect should fail\n", i);
957 ok(GetLastError() == ERROR_INVALID_PARAMETER, "%d: expected ERROR_INVALID_PARAMETER, got %d\n", i, GetLastError());
960 old_prot = 0xdeadbeef;
961 SetLastError(0xdeadbeef);
962 ret = VirtualProtect(section, page_size, PAGE_NOACCESS, &old_prot);
963 ok(ret, "%d: VirtualProtect error %d\n", i, GetLastError());
964 if (td[i].prot_get)
965 ok(old_prot == td[i].prot_get, "%d: got %#x != expected %#x\n", i, old_prot, td[i].prot_get);
966 else
967 ok(old_prot == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, old_prot);
970 exec_prot = 0;
972 for (i = 0; i <= 4; i++)
974 rw_prot = 0;
976 for (j = 0; j <= 4; j++)
978 DWORD prot = exec_prot | rw_prot;
980 SetLastError(0xdeadbeef);
981 ret = VirtualProtect(section, page_size, prot, &old_prot);
982 if ((rw_prot && exec_prot) || (!rw_prot && !exec_prot))
984 ok(!ret, "VirtualProtect(%02x) should fail\n", prot);
985 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
987 else
988 ok(ret, "VirtualProtect(%02x) error %d\n", prot, GetLastError());
990 rw_prot = 1 << j;
993 exec_prot = 1 << (i + 4);
996 SetLastError(0xdeadbeef);
997 ret = VirtualProtect(section, page_size, orig_prot, &old_prot);
998 ok(ret, "VirtualProtect error %d\n", GetLastError());
1001 static void test_section_access(void)
1003 static const struct test_data
1005 DWORD scn_file_access, scn_page_access, scn_page_access_after_write;
1006 } td[] =
1008 { 0, PAGE_NOACCESS, 0 },
1009 { IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1010 { IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1011 { IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1012 { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1013 { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ },
1014 { IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1015 { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1017 { IMAGE_SCN_CNT_INITIALIZED_DATA, PAGE_NOACCESS, 0 },
1018 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1019 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1020 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1021 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1022 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ, 0 },
1023 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1024 { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1026 { IMAGE_SCN_CNT_UNINITIALIZED_DATA, PAGE_NOACCESS, 0 },
1027 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1028 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1029 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1030 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1031 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ, 0 },
1032 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1033 { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE }
1035 static const char filler[0x1000];
1036 static const char section_data[0x10] = "section data";
1037 char buf[256];
1038 int i;
1039 DWORD dummy, file_align;
1040 HANDLE hfile;
1041 HMODULE hlib;
1042 char temp_path[MAX_PATH];
1043 char dll_name[MAX_PATH];
1044 SIZE_T size;
1045 MEMORY_BASIC_INFORMATION info;
1046 STARTUPINFOA sti;
1047 PROCESS_INFORMATION pi;
1048 DWORD ret;
1050 /* prevent displaying of the "Unable to load this DLL" message box */
1051 SetErrorMode(SEM_FAILCRITICALERRORS);
1053 GetTempPathA(MAX_PATH, temp_path);
1055 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
1057 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
1059 /*trace("creating %s\n", dll_name);*/
1060 hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
1061 if (hfile == INVALID_HANDLE_VALUE)
1063 ok(0, "could not create %s\n", dll_name);
1064 return;
1067 SetLastError(0xdeadbeef);
1068 ret = WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
1069 ok(ret, "WriteFile error %d\n", GetLastError());
1071 nt_header.FileHeader.NumberOfSections = 1;
1072 nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
1073 nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_RELOCS_STRIPPED;
1075 nt_header.OptionalHeader.SectionAlignment = page_size;
1076 nt_header.OptionalHeader.FileAlignment = 0x200;
1077 nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + page_size;
1078 nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
1079 SetLastError(0xdeadbeef);
1080 ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
1081 ok(ret, "WriteFile error %d\n", GetLastError());
1082 SetLastError(0xdeadbeef);
1083 ret = WriteFile(hfile, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
1084 ok(ret, "WriteFile error %d\n", GetLastError());
1086 section.SizeOfRawData = sizeof(section_data);
1087 section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
1088 section.VirtualAddress = nt_header.OptionalHeader.SectionAlignment;
1089 section.Misc.VirtualSize = section.SizeOfRawData;
1090 section.Characteristics = td[i].scn_file_access;
1091 SetLastError(0xdeadbeef);
1092 ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
1093 ok(ret, "WriteFile error %d\n", GetLastError());
1095 file_align = nt_header.OptionalHeader.FileAlignment - nt_header.OptionalHeader.SizeOfHeaders;
1096 assert(file_align < sizeof(filler));
1097 SetLastError(0xdeadbeef);
1098 ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
1099 ok(ret, "WriteFile error %d\n", GetLastError());
1101 /* section data */
1102 SetLastError(0xdeadbeef);
1103 ret = WriteFile(hfile, section_data, sizeof(section_data), &dummy, NULL);
1104 ok(ret, "WriteFile error %d\n", GetLastError());
1106 CloseHandle(hfile);
1108 SetLastError(0xdeadbeef);
1109 hlib = LoadLibraryA(dll_name);
1110 ok(hlib != 0, "LoadLibrary error %d\n", GetLastError());
1112 SetLastError(0xdeadbeef);
1113 size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
1114 ok(size == sizeof(info),
1115 "%d: VirtualQuery error %d\n", i, GetLastError());
1116 ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
1117 ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
1118 ok(info.Protect == td[i].scn_page_access, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access);
1119 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
1120 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1121 ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1122 ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1123 if (info.Protect != PAGE_NOACCESS)
1124 ok(!memcmp((const char *)info.BaseAddress, section_data, section.SizeOfRawData), "wrong section data\n");
1126 test_VirtualProtect(hlib, (char *)hlib + section.VirtualAddress);
1128 /* Windows changes the WRITECOPY to WRITE protection on an image section write (for a changed page only) */
1129 if (is_mem_writable(info.Protect))
1131 char *p = info.BaseAddress;
1132 *p = 0xfe;
1133 SetLastError(0xdeadbeef);
1134 size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
1135 ok(size == sizeof(info), "%d: VirtualQuery error %d\n", i, GetLastError());
1136 /* FIXME: remove the condition below once Wine is fixed */
1137 if (info.Protect == PAGE_WRITECOPY || info.Protect == PAGE_EXECUTE_WRITECOPY)
1138 todo_wine ok(info.Protect == td[i].scn_page_access_after_write, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access_after_write);
1139 else
1140 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);
1143 SetLastError(0xdeadbeef);
1144 ret = FreeLibrary(hlib);
1145 ok(ret, "FreeLibrary error %d\n", GetLastError());
1147 test_image_mapping(dll_name, td[i].scn_page_access, TRUE);
1149 /* reset IMAGE_FILE_DLL otherwise CreateProcess fails */
1150 nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_RELOCS_STRIPPED;
1151 SetLastError(0xdeadbeef);
1152 hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1153 /* LoadLibrary called on an already memory-mapped file in
1154 * test_image_mapping() above leads to a file handle leak
1155 * under nt4, and inability to overwrite and delete the file
1156 * due to sharing violation error. Ignore it and skip the test,
1157 * but leave a not deletable temporary file.
1159 ok(hfile != INVALID_HANDLE_VALUE || broken(hfile == INVALID_HANDLE_VALUE) /* nt4 */,
1160 "CreateFile error %d\n", GetLastError());
1161 if (hfile == INVALID_HANDLE_VALUE) goto nt4_is_broken;
1162 SetFilePointer(hfile, sizeof(dos_header), NULL, FILE_BEGIN);
1163 SetLastError(0xdeadbeef);
1164 ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
1165 ok(ret, "WriteFile error %d\n", GetLastError());
1166 CloseHandle(hfile);
1168 memset(&sti, 0, sizeof(sti));
1169 sti.cb = sizeof(sti);
1170 SetLastError(0xdeadbeef);
1171 ret = CreateProcessA(dll_name, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &sti, &pi);
1172 ok(ret, "CreateProcess() error %d\n", GetLastError());
1174 SetLastError(0xdeadbeef);
1175 size = VirtualQueryEx(pi.hProcess, (char *)hlib + section.VirtualAddress, &info, sizeof(info));
1176 ok(size == sizeof(info),
1177 "%d: VirtualQuery error %d\n", i, GetLastError());
1178 ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
1179 ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
1180 ok(info.Protect == td[i].scn_page_access, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access);
1181 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
1182 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1183 ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1184 ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1185 if (info.Protect != PAGE_NOACCESS)
1187 SetLastError(0xdeadbeef);
1188 ret = ReadProcessMemory(pi.hProcess, info.BaseAddress, buf, section.SizeOfRawData, NULL);
1189 ok(ret, "ReadProcessMemory() error %d\n", GetLastError());
1190 ok(!memcmp(buf, section_data, section.SizeOfRawData), "wrong section data\n");
1193 SetLastError(0xdeadbeef);
1194 ret = TerminateProcess(pi.hProcess, 0);
1195 ok(ret, "TerminateProcess() error %d\n", GetLastError());
1196 ret = WaitForSingleObject(pi.hProcess, 3000);
1197 ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
1199 CloseHandle(pi.hThread);
1200 CloseHandle(pi.hProcess);
1202 test_image_mapping(dll_name, td[i].scn_page_access, FALSE);
1204 nt4_is_broken:
1205 SetLastError(0xdeadbeef);
1206 ret = DeleteFileA(dll_name);
1207 ok(ret || broken(!ret) /* nt4 */, "DeleteFile error %d\n", GetLastError());
1211 static void test_import_resolution(void)
1213 char temp_path[MAX_PATH];
1214 char dll_name[MAX_PATH];
1215 DWORD dummy;
1216 void *expect;
1217 char *str;
1218 HANDLE hfile;
1219 HMODULE mod, mod2;
1220 struct imports
1222 IMAGE_IMPORT_DESCRIPTOR descr[2];
1223 IMAGE_THUNK_DATA original_thunks[2];
1224 IMAGE_THUNK_DATA thunks[2];
1225 char module[16];
1226 struct { WORD hint; char name[32]; } function;
1227 IMAGE_TLS_DIRECTORY tls;
1228 char tls_data[16];
1229 SHORT tls_index;
1230 } data, *ptr;
1231 IMAGE_NT_HEADERS nt;
1232 IMAGE_SECTION_HEADER section;
1233 int test;
1235 for (test = 0; test < 3; test++)
1237 #define DATA_RVA(ptr) (page_size + ((char *)(ptr) - (char *)&data))
1238 nt = nt_header;
1239 nt.FileHeader.NumberOfSections = 1;
1240 nt.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
1241 nt.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_RELOCS_STRIPPED;
1242 if (test != 2) nt.FileHeader.Characteristics |= IMAGE_FILE_DLL;
1243 nt.OptionalHeader.ImageBase = 0x12340000;
1244 nt.OptionalHeader.SizeOfImage = 2 * page_size;
1245 nt.OptionalHeader.SizeOfHeaders = nt.OptionalHeader.FileAlignment;
1246 nt.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
1247 memset( nt.OptionalHeader.DataDirectory, 0, sizeof(nt.OptionalHeader.DataDirectory) );
1248 nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = sizeof(data.descr);
1249 nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = DATA_RVA(data.descr);
1250 nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size = sizeof(data.tls);
1251 nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress = DATA_RVA(&data.tls);
1253 memset( &data, 0, sizeof(data) );
1254 data.descr[0].u.OriginalFirstThunk = DATA_RVA( data.original_thunks );
1255 data.descr[0].FirstThunk = DATA_RVA( data.thunks );
1256 data.descr[0].Name = DATA_RVA( data.module );
1257 strcpy( data.module, "kernel32.dll" );
1258 strcpy( data.function.name, "CreateEventA" );
1259 data.original_thunks[0].u1.AddressOfData = DATA_RVA( &data.function );
1260 data.thunks[0].u1.AddressOfData = 0xdeadbeef;
1262 data.tls.StartAddressOfRawData = nt.OptionalHeader.ImageBase + DATA_RVA( data.tls_data );
1263 data.tls.EndAddressOfRawData = data.tls.StartAddressOfRawData + sizeof(data.tls_data);
1264 data.tls.AddressOfIndex = nt.OptionalHeader.ImageBase + DATA_RVA( &data.tls_index );
1265 strcpy( data.tls_data, "hello world" );
1266 data.tls_index = 9999;
1268 GetTempPathA(MAX_PATH, temp_path);
1269 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
1271 hfile = CreateFileA(dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0);
1272 ok( hfile != INVALID_HANDLE_VALUE, "creation failed\n" );
1274 memset( &section, 0, sizeof(section) );
1275 memcpy( section.Name, ".text", sizeof(".text") );
1276 section.PointerToRawData = nt.OptionalHeader.FileAlignment;
1277 section.VirtualAddress = nt.OptionalHeader.SectionAlignment;
1278 section.Misc.VirtualSize = sizeof(data);
1279 section.SizeOfRawData = sizeof(data);
1280 section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
1282 WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
1283 WriteFile(hfile, &nt, sizeof(nt), &dummy, NULL);
1284 WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
1286 SetFilePointer( hfile, section.PointerToRawData, NULL, SEEK_SET );
1287 WriteFile(hfile, &data, sizeof(data), &dummy, NULL);
1289 CloseHandle( hfile );
1291 switch (test)
1293 case 0: /* normal load */
1294 mod = LoadLibraryA( dll_name );
1295 ok( mod != NULL, "failed to load err %u\n", GetLastError() );
1296 if (!mod) break;
1297 ptr = (struct imports *)((char *)mod + page_size);
1298 expect = GetProcAddress( GetModuleHandleA( data.module ), data.function.name );
1299 ok( (void *)ptr->thunks[0].u1.Function == expect, "thunk %p instead of %p for %s.%s\n",
1300 (void *)ptr->thunks[0].u1.Function, expect, data.module, data.function.name );
1301 ok( ptr->tls_index < 32 || broken(ptr->tls_index == 9999), /* before vista */
1302 "wrong tls index %d\n", ptr->tls_index );
1303 if (ptr->tls_index != 9999)
1305 str = ((char **)NtCurrentTeb()->ThreadLocalStoragePointer)[ptr->tls_index];
1306 ok( !strcmp( str, "hello world" ), "wrong tls data '%s' at %p\n", str, str );
1308 FreeLibrary( mod );
1309 break;
1310 case 1: /* load with DONT_RESOLVE_DLL_REFERENCES doesn't resolve imports */
1311 mod = LoadLibraryExA( dll_name, 0, DONT_RESOLVE_DLL_REFERENCES );
1312 ok( mod != NULL, "failed to load err %u\n", GetLastError() );
1313 if (!mod) break;
1314 ptr = (struct imports *)((char *)mod + page_size);
1315 ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
1316 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
1317 ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
1319 mod2 = LoadLibraryA( dll_name );
1320 ok( mod2 == mod, "loaded twice %p / %p\n", mod, mod2 );
1321 ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
1322 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
1323 ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
1324 FreeLibrary( mod );
1325 break;
1326 case 2: /* load without IMAGE_FILE_DLL doesn't resolve imports */
1327 mod = LoadLibraryA( dll_name );
1328 ok( mod != NULL, "failed to load err %u\n", GetLastError() );
1329 if (!mod) break;
1330 ptr = (struct imports *)((char *)mod + page_size);
1331 ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
1332 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
1333 ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
1334 FreeLibrary( mod );
1335 break;
1337 DeleteFileA( dll_name );
1338 #undef DATA_RVA
1342 #define MAX_COUNT 10
1343 static HANDLE attached_thread[MAX_COUNT];
1344 static DWORD attached_thread_count;
1345 HANDLE stop_event, event, mutex, semaphore, loader_lock_event, peb_lock_event, heap_lock_event, ack_event;
1346 static int test_dll_phase, inside_loader_lock, inside_peb_lock, inside_heap_lock;
1348 static DWORD WINAPI mutex_thread_proc(void *param)
1350 HANDLE wait_list[4];
1351 DWORD ret;
1353 ret = WaitForSingleObject(mutex, 0);
1354 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1356 SetEvent(param);
1358 wait_list[0] = stop_event;
1359 wait_list[1] = loader_lock_event;
1360 wait_list[2] = peb_lock_event;
1361 wait_list[3] = heap_lock_event;
1363 trace("%04u: mutex_thread_proc: starting\n", GetCurrentThreadId());
1364 while (1)
1366 ret = WaitForMultipleObjects(sizeof(wait_list)/sizeof(wait_list[0]), wait_list, FALSE, 50);
1367 if (ret == WAIT_OBJECT_0) break;
1368 else if (ret == WAIT_OBJECT_0 + 1)
1370 ULONG_PTR loader_lock_magic;
1371 trace("%04u: mutex_thread_proc: Entering loader lock\n", GetCurrentThreadId());
1372 ret = pLdrLockLoaderLock(0, NULL, &loader_lock_magic);
1373 ok(!ret, "LdrLockLoaderLock error %#x\n", ret);
1374 inside_loader_lock++;
1375 SetEvent(ack_event);
1377 else if (ret == WAIT_OBJECT_0 + 2)
1379 trace("%04u: mutex_thread_proc: Entering PEB lock\n", GetCurrentThreadId());
1380 pRtlAcquirePebLock();
1381 inside_peb_lock++;
1382 SetEvent(ack_event);
1384 else if (ret == WAIT_OBJECT_0 + 3)
1386 trace("%04u: mutex_thread_proc: Entering heap lock\n", GetCurrentThreadId());
1387 HeapLock(GetProcessHeap());
1388 inside_heap_lock++;
1389 SetEvent(ack_event);
1393 trace("%04u: mutex_thread_proc: exiting\n", GetCurrentThreadId());
1394 return 196;
1397 static DWORD WINAPI semaphore_thread_proc(void *param)
1399 DWORD ret;
1401 ret = WaitForSingleObject(semaphore, 0);
1402 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1404 SetEvent(param);
1406 while (1)
1408 trace("%04u: semaphore_thread_proc: still alive\n", GetCurrentThreadId());
1409 if (WaitForSingleObject(stop_event, 50) != WAIT_TIMEOUT) break;
1412 trace("%04u: semaphore_thread_proc: exiting\n", GetCurrentThreadId());
1413 return 196;
1416 static DWORD WINAPI noop_thread_proc(void *param)
1418 if (param)
1420 LONG *noop_thread_started = param;
1421 InterlockedIncrement(noop_thread_started);
1424 trace("%04u: noop_thread_proc: exiting\n", GetCurrentThreadId());
1425 return 195;
1428 static BOOL WINAPI dll_entry_point(HINSTANCE hinst, DWORD reason, LPVOID param)
1430 static LONG noop_thread_started;
1431 DWORD ret;
1433 ok(!inside_loader_lock, "inside_loader_lock should not be set\n");
1434 ok(!inside_peb_lock, "inside_peb_lock should not be set\n");
1436 switch (reason)
1438 case DLL_PROCESS_ATTACH:
1439 trace("dll: %p, DLL_PROCESS_ATTACH, %p\n", hinst, param);
1441 ret = pRtlDllShutdownInProgress();
1442 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1444 break;
1445 case DLL_PROCESS_DETACH:
1447 DWORD code, expected_code, i;
1448 HANDLE handle, process;
1449 void *addr;
1450 SIZE_T size;
1451 LARGE_INTEGER offset;
1452 DEBUG_EVENT de;
1454 trace("dll: %p, DLL_PROCESS_DETACH, %p\n", hinst, param);
1456 if (test_dll_phase == 4 || test_dll_phase == 5)
1458 ok(0, "dll_entry_point(DLL_PROCESS_DETACH) should not be called\n");
1459 break;
1462 /* The process should already deadlock at this point */
1463 if (test_dll_phase == 6)
1465 /* In reality, code below never gets executed, probably some other
1466 * code tries to access process heap and deadlocks earlier, even XP
1467 * doesn't call the DLL entry point on process detach either.
1469 HeapLock(GetProcessHeap());
1470 ok(0, "dll_entry_point: process should already deadlock\n");
1471 break;
1474 if (test_dll_phase == 0 || test_dll_phase == 1 || test_dll_phase == 3)
1475 ok(param != NULL, "dll: param %p\n", param);
1476 else
1477 ok(!param, "dll: param %p\n", param);
1479 if (test_dll_phase == 0 || test_dll_phase == 1) expected_code = 195;
1480 else if (test_dll_phase == 3) expected_code = 196;
1481 else expected_code = STILL_ACTIVE;
1483 if (test_dll_phase == 3)
1485 ret = pRtlDllShutdownInProgress();
1486 ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
1488 else
1490 ret = pRtlDllShutdownInProgress();
1492 /* FIXME: remove once Wine is fixed */
1493 if (expected_code == STILL_ACTIVE || expected_code == 196)
1494 ok(!ret || broken(ret) /* before Vista */, "RtlDllShutdownInProgress returned %d\n", ret);
1495 else
1496 todo_wine
1497 ok(!ret || broken(ret) /* before Vista */, "RtlDllShutdownInProgress returned %d\n", ret);
1500 ok(attached_thread_count >= 2, "attached thread count should be >= 2\n");
1502 for (i = 0; i < attached_thread_count; i++)
1504 /* Calling GetExitCodeThread() without waiting for thread termination
1505 * leads to different results due to a race condition.
1507 if (expected_code != STILL_ACTIVE)
1509 ret = WaitForSingleObject(attached_thread[i], 1000);
1510 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1512 ret = GetExitCodeThread(attached_thread[i], &code);
1513 trace("dll: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
1514 ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
1515 ok(code == expected_code, "expected thread exit code %u, got %u\n", expected_code, code);
1518 ret = WaitForSingleObject(event, 0);
1519 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1521 ret = WaitForSingleObject(mutex, 0);
1522 if (expected_code == STILL_ACTIVE)
1523 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1524 else
1525 ok(ret == WAIT_ABANDONED, "expected WAIT_ABANDONED, got %#x\n", ret);
1527 /* semaphore is not abandoned on thread termination */
1528 ret = WaitForSingleObject(semaphore, 0);
1529 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1531 if (expected_code == STILL_ACTIVE)
1533 ret = WaitForSingleObject(attached_thread[0], 0);
1534 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1535 ret = WaitForSingleObject(attached_thread[1], 0);
1536 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1538 else
1540 ret = WaitForSingleObject(attached_thread[0], 0);
1541 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1542 ret = WaitForSingleObject(attached_thread[1], 0);
1543 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1546 /* win7 doesn't allow to create a thread during process shutdown,
1547 * earlier Windows versions allow it.
1549 noop_thread_started = 0;
1550 SetLastError(0xdeadbeef);
1551 handle = CreateThread(NULL, 0, noop_thread_proc, &noop_thread_started, 0, &ret);
1552 if (param)
1554 ok(!handle || broken(handle != 0) /* before win7 */, "CreateThread should fail\n");
1555 if (!handle)
1556 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1557 else
1559 ret = WaitForSingleObject(handle, 1000);
1560 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1561 CloseHandle(handle);
1564 else
1566 ok(handle != 0, "CreateThread error %d\n", GetLastError());
1567 ret = WaitForSingleObject(handle, 1000);
1568 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1569 ok(!noop_thread_started || broken(noop_thread_started) /* XP64 */, "thread shouldn't start yet\n");
1570 CloseHandle(handle);
1573 SetLastError(0xdeadbeef);
1574 process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, GetCurrentProcessId());
1575 ok(process != NULL, "OpenProcess error %d\n", GetLastError());
1577 noop_thread_started = 0;
1578 SetLastError(0xdeadbeef);
1579 handle = CreateRemoteThread(process, NULL, 0, noop_thread_proc, &noop_thread_started, 0, &ret);
1580 if (param)
1582 ok(!handle || broken(handle != 0) /* before win7 */, "CreateRemoteThread should fail\n");
1583 if (!handle)
1584 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1585 else
1587 ret = WaitForSingleObject(handle, 1000);
1588 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1589 CloseHandle(handle);
1592 else
1594 ok(handle != 0, "CreateRemoteThread error %d\n", GetLastError());
1595 ret = WaitForSingleObject(handle, 1000);
1596 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1597 ok(!noop_thread_started || broken(noop_thread_started) /* XP64 */, "thread shouldn't start yet\n");
1598 CloseHandle(handle);
1601 SetLastError(0xdeadbeef);
1602 handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, NULL);
1603 ok(handle != 0, "CreateFileMapping error %d\n", GetLastError());
1605 offset.u.LowPart = 0;
1606 offset.u.HighPart = 0;
1607 addr = NULL;
1608 size = 0;
1609 ret = pNtMapViewOfSection(handle, process, &addr, 0, 0, &offset,
1610 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
1611 ok(ret == STATUS_SUCCESS, "NtMapViewOfSection error %#x\n", ret);
1612 ret = pNtUnmapViewOfSection(process, addr);
1613 ok(ret == STATUS_SUCCESS, "NtUnmapViewOfSection error %#x\n", ret);
1615 CloseHandle(handle);
1616 CloseHandle(process);
1618 handle = GetModuleHandleA("winver.exe");
1619 ok(!handle, "winver.exe shouldn't be loaded yet\n");
1620 SetLastError(0xdeadbeef);
1621 handle = LoadLibraryA("winver.exe");
1622 ok(handle != 0, "LoadLibrary error %d\n", GetLastError());
1623 SetLastError(0xdeadbeef);
1624 ret = FreeLibrary(handle);
1625 ok(ret, "FreeLibrary error %d\n", GetLastError());
1626 handle = GetModuleHandleA("winver.exe");
1627 if (param)
1628 ok(handle != 0, "winver.exe should not be unloaded\n");
1629 else
1630 todo_wine
1631 ok(!handle || broken(handle != 0) /* before win7 */, "winver.exe should be unloaded\n");
1633 SetLastError(0xdeadbeef);
1634 ret = WaitForDebugEvent(&de, 0);
1635 ok(!ret, "WaitForDebugEvent should fail\n");
1636 todo_wine
1637 ok(GetLastError() == ERROR_INVALID_HANDLE, "expected ERROR_INVALID_HANDLE, got %d\n", GetLastError());
1639 SetLastError(0xdeadbeef);
1640 ret = DebugActiveProcess(GetCurrentProcessId());
1641 ok(!ret, "DebugActiveProcess should fail\n");
1642 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1644 SetLastError(0xdeadbeef);
1645 ret = WaitForDebugEvent(&de, 0);
1646 ok(!ret, "WaitForDebugEvent should fail\n");
1647 ok(GetLastError() == ERROR_SEM_TIMEOUT, "expected ERROR_SEM_TIMEOUT, got %d\n", GetLastError());
1649 if (test_dll_phase == 2)
1651 trace("dll: call ExitProcess()\n");
1652 *child_failures = winetest_get_failures();
1653 ExitProcess(197);
1655 trace("dll: %p, DLL_PROCESS_DETACH, %p => DONE\n", hinst, param);
1656 break;
1658 case DLL_THREAD_ATTACH:
1659 trace("dll: %p, DLL_THREAD_ATTACH, %p\n", hinst, param);
1661 ret = pRtlDllShutdownInProgress();
1662 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1664 if (attached_thread_count < MAX_COUNT)
1666 DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &attached_thread[attached_thread_count],
1667 0, TRUE, DUPLICATE_SAME_ACCESS);
1668 attached_thread_count++;
1670 break;
1671 case DLL_THREAD_DETACH:
1672 trace("dll: %p, DLL_THREAD_DETACH, %p\n", hinst, param);
1674 ret = pRtlDllShutdownInProgress();
1675 /* win7 doesn't allow to create a thread during process shutdown,
1676 * earlier Windows versions allow it, and DLL_THREAD_DETACH is
1677 * sent on thread exit, but DLL_THREAD_ATTACH is never received.
1679 if (noop_thread_started)
1680 ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
1681 else
1682 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1684 break;
1685 default:
1686 trace("dll: %p, %d, %p\n", hinst, reason, param);
1687 break;
1690 *child_failures = winetest_get_failures();
1692 return TRUE;
1695 static void child_process(const char *dll_name, DWORD target_offset)
1697 void *target;
1698 DWORD ret, dummy, i, code, expected_code;
1699 HANDLE file, thread, process;
1700 HMODULE hmod;
1701 struct PROCESS_BASIC_INFORMATION_PRIVATE pbi;
1702 DWORD_PTR affinity;
1704 trace("phase %d: writing %p at %#x\n", test_dll_phase, dll_entry_point, target_offset);
1706 SetLastError(0xdeadbeef);
1707 mutex = CreateMutexW(NULL, FALSE, NULL);
1708 ok(mutex != 0, "CreateMutex error %d\n", GetLastError());
1710 SetLastError(0xdeadbeef);
1711 semaphore = CreateSemaphoreW(NULL, 1, 1, NULL);
1712 ok(semaphore != 0, "CreateSemaphore error %d\n", GetLastError());
1714 SetLastError(0xdeadbeef);
1715 event = CreateEventW(NULL, TRUE, FALSE, NULL);
1716 ok(event != 0, "CreateEvent error %d\n", GetLastError());
1718 SetLastError(0xdeadbeef);
1719 loader_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1720 ok(loader_lock_event != 0, "CreateEvent error %d\n", GetLastError());
1722 SetLastError(0xdeadbeef);
1723 peb_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1724 ok(peb_lock_event != 0, "CreateEvent error %d\n", GetLastError());
1726 SetLastError(0xdeadbeef);
1727 heap_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1728 ok(heap_lock_event != 0, "CreateEvent error %d\n", GetLastError());
1730 SetLastError(0xdeadbeef);
1731 ack_event = CreateEventW(NULL, FALSE, FALSE, NULL);
1732 ok(ack_event != 0, "CreateEvent error %d\n", GetLastError());
1734 file = CreateFileA(dll_name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1735 if (file == INVALID_HANDLE_VALUE)
1737 ok(0, "could not open %s\n", dll_name);
1738 return;
1740 SetFilePointer(file, target_offset, NULL, FILE_BEGIN);
1741 SetLastError(0xdeadbeef);
1742 target = dll_entry_point;
1743 ret = WriteFile(file, &target, sizeof(target), &dummy, NULL);
1744 ok(ret, "WriteFile error %d\n", GetLastError());
1745 CloseHandle(file);
1747 SetLastError(0xdeadbeef);
1748 hmod = LoadLibraryA(dll_name);
1749 ok(hmod != 0, "LoadLibrary error %d\n", GetLastError());
1751 SetLastError(0xdeadbeef);
1752 stop_event = CreateEventW(NULL, TRUE, FALSE, NULL);
1753 ok(stop_event != 0, "CreateEvent error %d\n", GetLastError());
1755 SetLastError(0xdeadbeef);
1756 thread = CreateThread(NULL, 0, mutex_thread_proc, event, 0, &dummy);
1757 ok(thread != 0, "CreateThread error %d\n", GetLastError());
1758 WaitForSingleObject(event, 3000);
1759 CloseHandle(thread);
1761 ResetEvent(event);
1763 SetLastError(0xdeadbeef);
1764 thread = CreateThread(NULL, 0, semaphore_thread_proc, event, 0, &dummy);
1765 ok(thread != 0, "CreateThread error %d\n", GetLastError());
1766 WaitForSingleObject(event, 3000);
1767 CloseHandle(thread);
1769 ResetEvent(event);
1770 Sleep(100);
1772 ok(attached_thread_count == 2, "attached thread count should be 2\n");
1773 for (i = 0; i < attached_thread_count; i++)
1775 ret = GetExitCodeThread(attached_thread[i], &code);
1776 trace("child: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
1777 ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
1778 ok(code == STILL_ACTIVE, "expected thread exit code STILL_ACTIVE, got %u\n", code);
1781 ret = WaitForSingleObject(attached_thread[0], 0);
1782 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1783 ret = WaitForSingleObject(attached_thread[1], 0);
1784 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1786 ret = WaitForSingleObject(event, 0);
1787 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1788 ret = WaitForSingleObject(mutex, 0);
1789 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1790 ret = WaitForSingleObject(semaphore, 0);
1791 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1793 ret = pRtlDllShutdownInProgress();
1794 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1796 SetLastError(0xdeadbeef);
1797 process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, GetCurrentProcessId());
1798 ok(process != NULL, "OpenProcess error %d\n", GetLastError());
1800 SetLastError(0xdeadbeef);
1801 ret = TerminateProcess(0, 195);
1802 ok(!ret, "TerminateProcess(0) should fail\n");
1803 ok(GetLastError() == ERROR_INVALID_HANDLE, "expected ERROR_INVALID_HANDLE, got %d\n", GetLastError());
1805 Sleep(100);
1807 affinity = 1;
1808 ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
1809 ok(!ret, "NtSetInformationProcess error %#x\n", ret);
1811 switch (test_dll_phase)
1813 case 0:
1814 ret = pRtlDllShutdownInProgress();
1815 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1817 trace("call NtTerminateProcess(0, 195)\n");
1818 ret = pNtTerminateProcess(0, 195);
1819 ok(!ret, "NtTerminateProcess error %#x\n", ret);
1821 memset(&pbi, 0, sizeof(pbi));
1822 ret = pNtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
1823 ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
1824 ok(pbi.ExitStatus == STILL_ACTIVE, "expected STILL_ACTIVE, got %lu\n", pbi.ExitStatus);
1825 affinity = 1;
1826 ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
1827 ok(!ret, "NtSetInformationProcess error %#x\n", ret);
1829 ret = pRtlDllShutdownInProgress();
1830 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1832 hmod = GetModuleHandleA(dll_name);
1833 ok(hmod != 0, "DLL should not be unloaded\n");
1835 SetLastError(0xdeadbeef);
1836 thread = CreateThread(NULL, 0, noop_thread_proc, &dummy, 0, &ret);
1837 ok(!thread || broken(thread != 0) /* before win7 */, "CreateThread should fail\n");
1838 if (!thread)
1839 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
1840 else
1842 ret = WaitForSingleObject(thread, 1000);
1843 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1844 CloseHandle(thread);
1847 trace("call LdrShutdownProcess()\n");
1848 pLdrShutdownProcess();
1850 ret = pRtlDllShutdownInProgress();
1851 ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
1853 hmod = GetModuleHandleA(dll_name);
1854 ok(hmod != 0, "DLL should not be unloaded\n");
1856 memset(&pbi, 0, sizeof(pbi));
1857 ret = pNtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
1858 ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
1859 ok(pbi.ExitStatus == STILL_ACTIVE, "expected STILL_ACTIVE, got %lu\n", pbi.ExitStatus);
1860 affinity = 1;
1861 ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
1862 ok(!ret, "NtSetInformationProcess error %#x\n", ret);
1863 break;
1865 case 1: /* normal ExitProcess */
1866 ret = pRtlDllShutdownInProgress();
1867 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1868 break;
1870 case 2: /* ExitProcess will be called by the PROCESS_DETACH handler */
1871 ret = pRtlDllShutdownInProgress();
1872 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1874 trace("call FreeLibrary(%p)\n", hmod);
1875 SetLastError(0xdeadbeef);
1876 ret = FreeLibrary(hmod);
1877 ok(ret, "FreeLibrary error %d\n", GetLastError());
1878 hmod = GetModuleHandleA(dll_name);
1879 ok(!hmod, "DLL should be unloaded\n");
1881 if (test_dll_phase == 2)
1882 ok(0, "FreeLibrary+ExitProcess should never return\n");
1884 ret = pRtlDllShutdownInProgress();
1885 ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
1887 break;
1889 case 3:
1890 trace("signalling thread exit\n");
1891 SetEvent(stop_event);
1892 CloseHandle(stop_event);
1893 break;
1895 case 4:
1896 trace("setting loader_lock_event\n");
1897 SetEvent(loader_lock_event);
1898 WaitForSingleObject(ack_event, 1000);
1899 ok(inside_loader_lock != 0, "inside_loader_lock is not set\n");
1901 /* calling NtTerminateProcess should not cause a deadlock */
1902 trace("call NtTerminateProcess(0, 198)\n");
1903 ret = pNtTerminateProcess(0, 198);
1904 ok(!ret, "NtTerminateProcess error %#x\n", ret);
1906 *child_failures = winetest_get_failures();
1908 /* Windows fails to release loader lock acquired from another thread,
1909 * so the LdrUnlockLoaderLock call fails here and ExitProcess deadlocks
1910 * later on, so NtTerminateProcess is used instead.
1912 trace("call NtTerminateProcess(GetCurrentProcess(), 198)\n");
1913 pNtTerminateProcess(GetCurrentProcess(), 198);
1914 ok(0, "NtTerminateProcess should not return\n");
1915 break;
1917 case 5:
1918 trace("setting peb_lock_event\n");
1919 SetEvent(peb_lock_event);
1920 WaitForSingleObject(ack_event, 1000);
1921 ok(inside_peb_lock != 0, "inside_peb_lock is not set\n");
1923 *child_failures = winetest_get_failures();
1925 /* calling ExitProcess should cause a deadlock */
1926 trace("call ExitProcess(198)\n");
1927 ExitProcess(198);
1928 ok(0, "ExitProcess should not return\n");
1929 break;
1931 case 6:
1932 trace("setting heap_lock_event\n");
1933 SetEvent(heap_lock_event);
1934 WaitForSingleObject(ack_event, 1000);
1935 ok(inside_heap_lock != 0, "inside_heap_lock is not set\n");
1937 *child_failures = winetest_get_failures();
1939 /* calling ExitProcess should cause a deadlock */
1940 trace("call ExitProcess(1)\n");
1941 ExitProcess(1);
1942 ok(0, "ExitProcess should not return\n");
1943 break;
1945 default:
1946 assert(0);
1947 break;
1950 if (test_dll_phase == 0) expected_code = 195;
1951 else if (test_dll_phase == 3) expected_code = 196;
1952 else if (test_dll_phase == 4) expected_code = 198;
1953 else expected_code = STILL_ACTIVE;
1955 if (expected_code == STILL_ACTIVE)
1957 ret = WaitForSingleObject(attached_thread[0], 100);
1958 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1959 ret = WaitForSingleObject(attached_thread[1], 100);
1960 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
1962 else
1964 ret = WaitForSingleObject(attached_thread[0], 1000);
1965 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1966 ret = WaitForSingleObject(attached_thread[1], 1000);
1967 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
1970 for (i = 0; i < attached_thread_count; i++)
1972 ret = GetExitCodeThread(attached_thread[i], &code);
1973 trace("child: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
1974 ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
1975 ok(code == expected_code, "expected thread exit code %u, got %u\n", expected_code, code);
1978 *child_failures = winetest_get_failures();
1980 trace("call ExitProcess(195)\n");
1981 ExitProcess(195);
1984 static void test_ExitProcess(void)
1986 #include "pshpack1.h"
1987 #ifdef __x86_64__
1988 static struct section_data
1990 BYTE mov_rax[2];
1991 void *target;
1992 BYTE jmp_rax[2];
1993 } section_data = { { 0x48,0xb8 }, dll_entry_point, { 0xff,0xe0 } };
1994 #else
1995 static struct section_data
1997 BYTE mov_eax;
1998 void *target;
1999 BYTE jmp_eax[2];
2000 } section_data = { 0xb8, dll_entry_point, { 0xff,0xe0 } };
2001 #endif
2002 #include "poppack.h"
2003 static const char filler[0x1000];
2004 DWORD dummy, file_align;
2005 HANDLE file, thread, process, hmap, hmap_dup;
2006 char temp_path[MAX_PATH], dll_name[MAX_PATH], cmdline[MAX_PATH * 2];
2007 DWORD ret, target_offset, old_prot;
2008 char **argv, buf[256];
2009 PROCESS_INFORMATION pi;
2010 STARTUPINFOA si = { sizeof(si) };
2011 CONTEXT ctx;
2012 struct PROCESS_BASIC_INFORMATION_PRIVATE pbi;
2013 MEMORY_BASIC_INFORMATION mbi;
2014 DWORD_PTR affinity;
2015 void *addr;
2016 LARGE_INTEGER offset;
2017 SIZE_T size;
2019 #if !defined(__i386__) && !defined(__x86_64__)
2020 skip("x86 specific ExitProcess test\n");
2021 return;
2022 #endif
2024 if (!pRtlDllShutdownInProgress)
2026 win_skip("RtlDllShutdownInProgress is not available on this platform (XP+)\n");
2027 return;
2029 if (!pNtQueryInformationProcess || !pNtSetInformationProcess)
2031 win_skip("NtQueryInformationProcess/NtSetInformationProcess are not available on this platform\n");
2032 return;
2034 if (!pNtAllocateVirtualMemory || !pNtFreeVirtualMemory)
2036 win_skip("NtAllocateVirtualMemory/NtFreeVirtualMemory are not available on this platform\n");
2037 return;
2040 /* prevent displaying of the "Unable to load this DLL" message box */
2041 SetErrorMode(SEM_FAILCRITICALERRORS);
2043 GetTempPathA(MAX_PATH, temp_path);
2044 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
2046 /*trace("creating %s\n", dll_name);*/
2047 file = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
2048 if (file == INVALID_HANDLE_VALUE)
2050 ok(0, "could not create %s\n", dll_name);
2051 return;
2054 SetLastError(0xdeadbeef);
2055 ret = WriteFile(file, &dos_header, sizeof(dos_header), &dummy, NULL);
2056 ok(ret, "WriteFile error %d\n", GetLastError());
2058 nt_header.FileHeader.NumberOfSections = 1;
2059 nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
2060 nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_RELOCS_STRIPPED;
2062 nt_header.OptionalHeader.AddressOfEntryPoint = 0x1000;
2063 nt_header.OptionalHeader.SectionAlignment = 0x1000;
2064 nt_header.OptionalHeader.FileAlignment = 0x200;
2065 nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000;
2066 nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
2067 SetLastError(0xdeadbeef);
2068 ret = WriteFile(file, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
2069 ok(ret, "WriteFile error %d\n", GetLastError());
2070 SetLastError(0xdeadbeef);
2071 ret = WriteFile(file, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
2072 ok(ret, "WriteFile error %d\n", GetLastError());
2074 section.SizeOfRawData = sizeof(section_data);
2075 section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
2076 section.VirtualAddress = nt_header.OptionalHeader.SectionAlignment;
2077 section.Misc.VirtualSize = sizeof(section_data);
2078 section.Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE;
2079 SetLastError(0xdeadbeef);
2080 ret = WriteFile(file, &section, sizeof(section), &dummy, NULL);
2081 ok(ret, "WriteFile error %d\n", GetLastError());
2083 file_align = nt_header.OptionalHeader.FileAlignment - nt_header.OptionalHeader.SizeOfHeaders;
2084 assert(file_align < sizeof(filler));
2085 SetLastError(0xdeadbeef);
2086 ret = WriteFile(file, filler, file_align, &dummy, NULL);
2087 ok(ret, "WriteFile error %d\n", GetLastError());
2089 target_offset = SetFilePointer(file, 0, NULL, FILE_CURRENT) + FIELD_OFFSET(struct section_data, target);
2091 /* section data */
2092 SetLastError(0xdeadbeef);
2093 ret = WriteFile(file, &section_data, sizeof(section_data), &dummy, NULL);
2094 ok(ret, "WriteFile error %d\n", GetLastError());
2096 CloseHandle(file);
2098 winetest_get_mainargs(&argv);
2100 /* phase 0 */
2101 *child_failures = -1;
2102 sprintf(cmdline, "\"%s\" loader %s %u 0", argv[0], dll_name, target_offset);
2103 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2104 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2105 ret = WaitForSingleObject(pi.hProcess, 10000);
2106 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2107 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2108 GetExitCodeProcess(pi.hProcess, &ret);
2109 ok(ret == 195, "expected exit code 195, got %u\n", ret);
2110 if (*child_failures)
2112 trace("%d failures in child process\n", *child_failures);
2113 winetest_add_failures(*child_failures);
2115 CloseHandle(pi.hThread);
2116 CloseHandle(pi.hProcess);
2118 /* phase 1 */
2119 *child_failures = -1;
2120 sprintf(cmdline, "\"%s\" loader %s %u 1", argv[0], dll_name, target_offset);
2121 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2122 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2123 ret = WaitForSingleObject(pi.hProcess, 10000);
2124 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2125 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2126 GetExitCodeProcess(pi.hProcess, &ret);
2127 ok(ret == 195, "expected exit code 195, got %u\n", ret);
2128 if (*child_failures)
2130 trace("%d failures in child process\n", *child_failures);
2131 winetest_add_failures(*child_failures);
2133 CloseHandle(pi.hThread);
2134 CloseHandle(pi.hProcess);
2136 /* phase 2 */
2137 *child_failures = -1;
2138 sprintf(cmdline, "\"%s\" loader %s %u 2", argv[0], dll_name, target_offset);
2139 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2140 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2141 ret = WaitForSingleObject(pi.hProcess, 10000);
2142 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2143 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2144 GetExitCodeProcess(pi.hProcess, &ret);
2145 ok(ret == 197, "expected exit code 197, got %u\n", ret);
2146 if (*child_failures)
2148 trace("%d failures in child process\n", *child_failures);
2149 winetest_add_failures(*child_failures);
2151 CloseHandle(pi.hThread);
2152 CloseHandle(pi.hProcess);
2154 /* phase 3 */
2155 *child_failures = -1;
2156 sprintf(cmdline, "\"%s\" loader %s %u 3", argv[0], dll_name, target_offset);
2157 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2158 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2159 ret = WaitForSingleObject(pi.hProcess, 10000);
2160 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2161 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2162 GetExitCodeProcess(pi.hProcess, &ret);
2163 ok(ret == 195, "expected exit code 195, got %u\n", ret);
2164 if (*child_failures)
2166 trace("%d failures in child process\n", *child_failures);
2167 winetest_add_failures(*child_failures);
2169 CloseHandle(pi.hThread);
2170 CloseHandle(pi.hProcess);
2172 /* phase 4 */
2173 if (pLdrLockLoaderLock && pLdrUnlockLoaderLock)
2175 *child_failures = -1;
2176 sprintf(cmdline, "\"%s\" loader %s %u 4", argv[0], dll_name, target_offset);
2177 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2178 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2179 ret = WaitForSingleObject(pi.hProcess, 10000);
2180 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2181 if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
2182 GetExitCodeProcess(pi.hProcess, &ret);
2183 ok(ret == 198, "expected exit code 198, got %u\n", ret);
2184 if (*child_failures)
2186 trace("%d failures in child process\n", *child_failures);
2187 winetest_add_failures(*child_failures);
2189 CloseHandle(pi.hThread);
2190 CloseHandle(pi.hProcess);
2192 else
2193 win_skip("LdrLockLoaderLock/LdrUnlockLoaderLock are not available on this platform\n");
2195 /* phase 5 */
2196 if (pRtlAcquirePebLock && pRtlReleasePebLock)
2198 *child_failures = -1;
2199 sprintf(cmdline, "\"%s\" loader %s %u 5", argv[0], dll_name, target_offset);
2200 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2201 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2202 ret = WaitForSingleObject(pi.hProcess, 5000);
2203 ok(ret == WAIT_TIMEOUT, "child process should fail to terminate\n");
2204 if (ret != WAIT_OBJECT_0)
2206 trace("terminating child process\n");
2207 TerminateProcess(pi.hProcess, 199);
2209 ret = WaitForSingleObject(pi.hProcess, 1000);
2210 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2211 GetExitCodeProcess(pi.hProcess, &ret);
2212 ok(ret == 199, "expected exit code 199, got %u\n", ret);
2213 if (*child_failures)
2215 trace("%d failures in child process\n", *child_failures);
2216 winetest_add_failures(*child_failures);
2218 CloseHandle(pi.hThread);
2219 CloseHandle(pi.hProcess);
2221 else
2222 win_skip("RtlAcquirePebLock/RtlReleasePebLock are not available on this platform\n");
2224 /* phase 6 */
2225 *child_failures = -1;
2226 sprintf(cmdline, "\"%s\" loader %s %u 6", argv[0], dll_name, target_offset);
2227 ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2228 ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2229 ret = WaitForSingleObject(pi.hProcess, 5000);
2230 ok(ret == WAIT_TIMEOUT || broken(ret == WAIT_OBJECT_0) /* XP */, "child process should fail to terminate\n");
2231 if (ret != WAIT_OBJECT_0)
2233 trace("terminating child process\n");
2234 TerminateProcess(pi.hProcess, 201);
2236 ret = WaitForSingleObject(pi.hProcess, 1000);
2237 ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
2238 GetExitCodeProcess(pi.hProcess, &ret);
2239 ok(ret == 201 || broken(ret == 1) /* XP */, "expected exit code 201, got %u\n", ret);
2240 if (*child_failures)
2242 trace("%d failures in child process\n", *child_failures);
2243 winetest_add_failures(*child_failures);
2245 CloseHandle(pi.hThread);
2246 CloseHandle(pi.hProcess);
2248 /* test remote process termination */
2249 SetLastError(0xdeadbeef);
2250 ret = CreateProcessA(argv[0], NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi);
2251 ok(ret, "CreateProcess(%s) error %d\n", argv[0], GetLastError());
2253 SetLastError(0xdeadbeef);
2254 addr = VirtualAllocEx(pi.hProcess, NULL, 4096, MEM_COMMIT, PAGE_READWRITE);
2255 ok(addr != NULL, "VirtualAllocEx error %d\n", GetLastError());
2256 SetLastError(0xdeadbeef);
2257 ret = VirtualProtectEx(pi.hProcess, addr, 4096, PAGE_READONLY, &old_prot);
2258 ok(ret, "VirtualProtectEx error %d\n", GetLastError());
2259 ok(old_prot == PAGE_READWRITE, "expected PAGE_READWRITE, got %#x\n", old_prot);
2260 SetLastError(0xdeadbeef);
2261 size = VirtualQueryEx(pi.hProcess, NULL, &mbi, sizeof(mbi));
2262 ok(size == sizeof(mbi), "VirtualQueryEx error %d\n", GetLastError());
2264 SetLastError(0xdeadbeef);
2265 ret = ReadProcessMemory(pi.hProcess, addr, buf, 4, &size);
2266 ok(ret, "ReadProcessMemory error %d\n", GetLastError());
2267 ok(size == 4, "expected 4, got %lu\n", size);
2269 SetLastError(0xdeadbeef);
2270 hmap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, NULL);
2271 ok(hmap != 0, "CreateFileMapping error %d\n", GetLastError());
2273 SetLastError(0xdeadbeef);
2274 ret = DuplicateHandle(GetCurrentProcess(), hmap, pi.hProcess, &hmap_dup,
2275 0, FALSE, DUPLICATE_SAME_ACCESS);
2276 ok(ret, "DuplicateHandle error %d\n", GetLastError());
2278 offset.u.LowPart = 0;
2279 offset.u.HighPart = 0;
2280 addr = NULL;
2281 size = 0;
2282 ret = pNtMapViewOfSection(hmap, pi.hProcess, &addr, 0, 0, &offset,
2283 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
2284 ok(!ret, "NtMapViewOfSection error %#x\n", ret);
2285 ret = pNtUnmapViewOfSection(pi.hProcess, addr);
2286 ok(!ret, "NtUnmapViewOfSection error %#x\n", ret);
2288 SetLastError(0xdeadbeef);
2289 thread = CreateRemoteThread(pi.hProcess, NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
2290 ok(thread != 0, "CreateRemoteThread error %d\n", GetLastError());
2291 SetLastError(0xdeadbeef);
2292 ctx.ContextFlags = CONTEXT_INTEGER;
2293 ret = GetThreadContext(thread, &ctx);
2294 ok(ret, "GetThreadContext error %d\n", GetLastError());
2295 SetLastError(0xdeadbeef);
2296 ctx.ContextFlags = CONTEXT_INTEGER;
2297 ret = SetThreadContext(thread, &ctx);
2298 ok(ret, "SetThreadContext error %d\n", GetLastError());
2299 SetLastError(0xdeadbeef);
2300 ret = SetThreadPriority(thread, 0);
2301 ok(ret, "SetThreadPriority error %d\n", GetLastError());
2303 SetLastError(0xdeadbeef);
2304 ret = TerminateThread(thread, 199);
2305 ok(ret, "TerminateThread error %d\n", GetLastError());
2306 /* Calling GetExitCodeThread() without waiting for thread termination
2307 * leads to different results due to a race condition.
2309 ret = WaitForSingleObject(thread, 1000);
2310 ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
2311 GetExitCodeThread(thread, &ret);
2312 ok(ret == 199, "expected exit code 199, got %u\n", ret);
2314 SetLastError(0xdeadbeef);
2315 ret = TerminateProcess(pi.hProcess, 198);
2316 ok(ret, "TerminateProcess error %d\n", GetLastError());
2317 /* Checking process state without waiting for process termination
2318 * leads to different results due to a race condition.
2320 ret = WaitForSingleObject(pi.hProcess, 1000);
2321 ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
2323 SetLastError(0xdeadbeef);
2324 process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, pi.dwProcessId);
2325 ok(process != NULL, "OpenProcess error %d\n", GetLastError());
2326 CloseHandle(process);
2328 memset(&pbi, 0, sizeof(pbi));
2329 ret = pNtQueryInformationProcess(pi.hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2330 ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
2331 ok(pbi.ExitStatus == 198, "expected 198, got %lu\n", pbi.ExitStatus);
2332 affinity = 1;
2333 ret = pNtSetInformationProcess(pi.hProcess, ProcessAffinityMask, &affinity, sizeof(affinity));
2334 ok(ret == STATUS_PROCESS_IS_TERMINATING, "expected STATUS_PROCESS_IS_TERMINATING, got %#x\n", ret);
2336 SetLastError(0xdeadbeef);
2337 ctx.ContextFlags = CONTEXT_INTEGER;
2338 ret = GetThreadContext(thread, &ctx);
2339 ok(!ret || broken(ret) /* XP 64-bit */, "GetThreadContext should fail\n");
2340 if (!ret)
2341 ok(GetLastError() == ERROR_INVALID_PARAMETER ||
2342 GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
2343 GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
2344 "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
2345 SetLastError(0xdeadbeef);
2346 ctx.ContextFlags = CONTEXT_INTEGER;
2347 ret = SetThreadContext(thread, &ctx);
2348 ok(!ret || broken(ret) /* XP 64-bit */, "SetThreadContext should fail\n");
2349 if (!ret)
2350 ok(GetLastError() == ERROR_ACCESS_DENIED ||
2351 GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
2352 GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
2353 "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2354 SetLastError(0xdeadbeef);
2355 ret = SetThreadPriority(thread, 0);
2356 ok(ret, "SetThreadPriority error %d\n", GetLastError());
2357 CloseHandle(thread);
2359 SetLastError(0xdeadbeef);
2360 ctx.ContextFlags = CONTEXT_INTEGER;
2361 ret = GetThreadContext(pi.hThread, &ctx);
2362 ok(!ret || broken(ret) /* XP 64-bit */, "GetThreadContext should fail\n");
2363 if (!ret)
2364 ok(GetLastError() == ERROR_INVALID_PARAMETER ||
2365 GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
2366 GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
2367 "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
2368 SetLastError(0xdeadbeef);
2369 ctx.ContextFlags = CONTEXT_INTEGER;
2370 ret = SetThreadContext(pi.hThread, &ctx);
2371 ok(!ret || broken(ret) /* XP 64-bit */, "SetThreadContext should fail\n");
2372 if (!ret)
2373 ok(GetLastError() == ERROR_ACCESS_DENIED ||
2374 GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
2375 GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
2376 "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2377 SetLastError(0xdeadbeef);
2378 ret = VirtualProtectEx(pi.hProcess, addr, 4096, PAGE_READWRITE, &old_prot);
2379 ok(!ret, "VirtualProtectEx should fail\n");
2380 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2381 SetLastError(0xdeadbeef);
2382 size = 0;
2383 ret = ReadProcessMemory(pi.hProcess, addr, buf, 4, &size);
2384 ok(!ret, "ReadProcessMemory should fail\n");
2385 ok(GetLastError() == ERROR_PARTIAL_COPY || GetLastError() == ERROR_ACCESS_DENIED,
2386 "expected ERROR_PARTIAL_COPY, got %d\n", GetLastError());
2387 ok(!size, "expected 0, got %lu\n", size);
2388 SetLastError(0xdeadbeef);
2389 ret = VirtualFreeEx(pi.hProcess, addr, 0, MEM_RELEASE);
2390 ok(!ret, "VirtualFreeEx should fail\n");
2391 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2392 SetLastError(0xdeadbeef);
2393 addr = VirtualAllocEx(pi.hProcess, NULL, 4096, MEM_COMMIT, PAGE_READWRITE);
2394 ok(!addr, "VirtualAllocEx should fail\n");
2395 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2396 SetLastError(0xdeadbeef);
2397 size = VirtualQueryEx(pi.hProcess, NULL, &mbi, sizeof(mbi));
2398 ok(!size, "VirtualQueryEx should fail\n");
2399 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2401 /* CloseHandle() call below leads to premature process termination
2402 * under some Windows versions.
2404 if (0)
2406 SetLastError(0xdeadbeef);
2407 ret = CloseHandle(hmap_dup);
2408 ok(ret, "CloseHandle should not fail\n");
2411 SetLastError(0xdeadbeef);
2412 ret = DuplicateHandle(GetCurrentProcess(), hmap, pi.hProcess, &hmap_dup,
2413 0, FALSE, DUPLICATE_SAME_ACCESS);
2414 ok(!ret, "DuplicateHandle should fail\n");
2415 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2417 offset.u.LowPart = 0;
2418 offset.u.HighPart = 0;
2419 addr = NULL;
2420 size = 0;
2421 ret = pNtMapViewOfSection(hmap, pi.hProcess, &addr, 0, 0, &offset,
2422 &size, 1 /* ViewShare */, 0, PAGE_READONLY);
2423 ok(ret == STATUS_PROCESS_IS_TERMINATING, "expected STATUS_PROCESS_IS_TERMINATING, got %#x\n", ret);
2425 SetLastError(0xdeadbeef);
2426 thread = CreateRemoteThread(pi.hProcess, NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
2427 ok(!thread, "CreateRemoteThread should fail\n");
2428 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2430 SetLastError(0xdeadbeef);
2431 ret = DebugActiveProcess(pi.dwProcessId);
2432 ok(!ret, "DebugActiveProcess should fail\n");
2433 ok(GetLastError() == ERROR_ACCESS_DENIED /* 64-bit */ || GetLastError() == ERROR_NOT_SUPPORTED /* 32-bit */,
2434 "ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2436 GetExitCodeProcess(pi.hProcess, &ret);
2437 ok(ret == 198 || broken(ret != 198) /* some 32-bit XP version in a VM returns random exit code */,
2438 "expected exit code 198, got %u\n", ret);
2439 CloseHandle(pi.hThread);
2440 CloseHandle(pi.hProcess);
2442 ret = DeleteFileA(dll_name);
2443 ok(ret, "DeleteFile error %d\n", GetLastError());
2446 static PVOID WINAPI failuredllhook(ULONG ul, DELAYLOAD_INFO* pd)
2448 ok(ul == 4, "expected 4, got %u\n", ul);
2449 ok(!!pd, "no delayload info supplied\n");
2450 if (pd)
2452 ok(pd->Size == sizeof(*pd), "got %u\n", pd->Size);
2453 ok(!!pd->DelayloadDescriptor, "no DelayloadDescriptor supplied\n");
2454 if (pd->DelayloadDescriptor)
2456 ok(pd->DelayloadDescriptor->Attributes.AllAttributes == 1,
2457 "expected 1, got %u\n", pd->DelayloadDescriptor->Attributes.AllAttributes);
2458 ok(pd->DelayloadDescriptor->DllNameRVA == 0x2000,
2459 "expected 0x2000, got %x\n", pd->DelayloadDescriptor->DllNameRVA);
2460 ok(pd->DelayloadDescriptor->ModuleHandleRVA == 0x201a,
2461 "expected 0x201a, got %x\n", pd->DelayloadDescriptor->ModuleHandleRVA);
2462 ok(pd->DelayloadDescriptor->ImportAddressTableRVA > pd->DelayloadDescriptor->ModuleHandleRVA,
2463 "expected %x > %x\n", pd->DelayloadDescriptor->ImportAddressTableRVA,
2464 pd->DelayloadDescriptor->ModuleHandleRVA);
2465 ok(pd->DelayloadDescriptor->ImportNameTableRVA > pd->DelayloadDescriptor->ImportAddressTableRVA,
2466 "expected %x > %x\n", pd->DelayloadDescriptor->ImportNameTableRVA,
2467 pd->DelayloadDescriptor->ImportAddressTableRVA);
2468 ok(pd->DelayloadDescriptor->BoundImportAddressTableRVA == 0,
2469 "expected 0, got %x\n", pd->DelayloadDescriptor->BoundImportAddressTableRVA);
2470 ok(pd->DelayloadDescriptor->UnloadInformationTableRVA == 0,
2471 "expected 0, got %x\n", pd->DelayloadDescriptor->UnloadInformationTableRVA);
2472 ok(pd->DelayloadDescriptor->TimeDateStamp == 0,
2473 "expected 0, got %x\n", pd->DelayloadDescriptor->TimeDateStamp);
2476 ok(!!pd->ThunkAddress, "no ThunkAddress supplied\n");
2477 if (pd->ThunkAddress)
2478 ok(pd->ThunkAddress->u1.Ordinal == 0, "expected 0, got %x\n", (UINT)pd->ThunkAddress->u1.Ordinal);
2480 ok(!!pd->TargetDllName, "no TargetDllName supplied\n");
2481 if (pd->TargetDllName)
2482 ok(!strcmp(pd->TargetDllName, "secur32.dll"),
2483 "expected \"secur32.dll\", got \"%s\"\n", pd->TargetDllName);
2485 ok(pd->TargetApiDescriptor.ImportDescribedByName == 0,
2486 "expected 0, got %x\n", pd->TargetApiDescriptor.ImportDescribedByName);
2487 ok(pd->TargetApiDescriptor.Description.Ordinal == 0 ||
2488 pd->TargetApiDescriptor.Description.Ordinal == 999,
2489 "expected 0, got %x\n", pd->TargetApiDescriptor.Description.Ordinal);
2491 ok(!!pd->TargetModuleBase, "no TargetModuleBase supplied\n");
2492 ok(pd->Unused == NULL, "expected NULL, got %p\n", pd->Unused);
2493 ok(pd->LastError, "no LastError supplied\n");
2495 cb_count++;
2496 return (void*)0xdeadbeef;
2499 static void test_ResolveDelayLoadedAPI(void)
2501 static const char test_dll[] = "secur32.dll";
2502 static const char test_func[] = "SealMessage";
2503 static const char filler[0x1000];
2504 char temp_path[MAX_PATH];
2505 char dll_name[MAX_PATH];
2506 IMAGE_DELAYLOAD_DESCRIPTOR idd, *delaydir;
2507 IMAGE_THUNK_DATA itd32;
2508 HANDLE hfile;
2509 HMODULE hlib;
2510 DWORD dummy, file_size, i;
2511 WORD hint = 0;
2512 BOOL ret;
2513 static const struct test_data
2515 BOOL func;
2516 UINT_PTR ordinal;
2517 BOOL succeeds;
2518 } td[] =
2521 TRUE, 0, TRUE
2524 FALSE, IMAGE_ORDINAL_FLAG | 2, TRUE
2527 FALSE, IMAGE_ORDINAL_FLAG | 5, TRUE
2530 FALSE, IMAGE_ORDINAL_FLAG | 0, FALSE
2533 FALSE, IMAGE_ORDINAL_FLAG | 999, FALSE
2537 if (!pResolveDelayLoadedAPI)
2539 todo_wine win_skip("ResolveDelayLoadedAPI is not available\n");
2540 return;
2543 if (0) /* crashes on native */
2545 SetLastError(0xdeadbeef);
2546 ok(!pResolveDelayLoadedAPI(NULL, NULL, NULL, NULL, NULL, 0),
2547 "ResolveDelayLoadedAPI succeeded\n");
2548 ok(GetLastError() == 0xdeadbeef, "GetLastError changed to %x\n", GetLastError());
2550 cb_count = 0;
2551 SetLastError(0xdeadbeef);
2552 ok(!pResolveDelayLoadedAPI(NULL, NULL, failuredllhook, NULL, NULL, 0),
2553 "ResolveDelayLoadedAPI succeeded\n");
2554 ok(GetLastError() == 0xdeadbeef, "GetLastError changed to %x\n", GetLastError());
2555 ok(cb_count == 1, "Wrong callback count: %d\n", cb_count);
2558 GetTempPathA(MAX_PATH, temp_path);
2559 GetTempFileNameA(temp_path, "ldr", 0, dll_name);
2560 trace("creating %s\n", dll_name);
2561 hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
2562 if (hfile == INVALID_HANDLE_VALUE)
2564 ok(0, "could not create %s\n", dll_name);
2565 return;
2568 SetLastError(0xdeadbeef);
2569 ret = WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
2570 ok(ret, "WriteFile error %d\n", GetLastError());
2572 nt_header.FileHeader.NumberOfSections = 2;
2573 nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
2575 nt_header.OptionalHeader.SectionAlignment = 0x1000;
2576 nt_header.OptionalHeader.FileAlignment = 0x1000;
2577 nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x2200;
2578 nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + 2 * sizeof(IMAGE_SECTION_HEADER);
2579 nt_header.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
2580 nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress = 0x1000;
2581 nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size = 0x100;
2583 SetLastError(0xdeadbeef);
2584 ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
2585 ok(ret, "WriteFile error %d\n", GetLastError());
2587 SetLastError(0xdeadbeef);
2588 ret = WriteFile(hfile, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
2589 ok(ret, "WriteFile error %d\n", GetLastError());
2591 /* sections */
2592 section.PointerToRawData = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress;
2593 section.VirtualAddress = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress;
2594 section.Misc.VirtualSize = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size;
2595 section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
2596 SetLastError(0xdeadbeef);
2597 ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
2598 ok(ret, "WriteFile error %d\n", GetLastError());
2600 section.PointerToRawData = 0x2000;
2601 section.VirtualAddress = 0x2000;
2602 i = sizeof(td)/sizeof(td[0]);
2603 section.Misc.VirtualSize = sizeof(test_dll) + sizeof(hint) + sizeof(test_func) + sizeof(HMODULE) +
2604 2 * (i + 1) * sizeof(IMAGE_THUNK_DATA);
2605 ok(section.Misc.VirtualSize <= 0x1000, "Too much tests, add a new section!\n");
2606 section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
2607 SetLastError(0xdeadbeef);
2608 ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
2609 ok(ret, "WriteFile error %d\n", GetLastError());
2611 /* fill up to delay data */
2612 file_size = GetFileSize(hfile, NULL);
2613 SetLastError(0xdeadbeef);
2614 ret = WriteFile(hfile, filler,
2615 nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress - file_size,
2616 &dummy, NULL);
2617 ok(ret, "WriteFile error %d\n", GetLastError());
2619 /* delay data */
2620 idd.Attributes.AllAttributes = 1;
2621 idd.DllNameRVA = 0x2000;
2622 idd.ModuleHandleRVA = idd.DllNameRVA + sizeof(test_dll) + sizeof(hint) + sizeof(test_func);
2623 idd.ImportAddressTableRVA = idd.ModuleHandleRVA + sizeof(HMODULE);
2624 idd.ImportNameTableRVA = idd.ImportAddressTableRVA + (i + 1) * sizeof(IMAGE_THUNK_DATA);
2625 idd.BoundImportAddressTableRVA = 0;
2626 idd.UnloadInformationTableRVA = 0;
2627 idd.TimeDateStamp = 0;
2629 SetLastError(0xdeadbeef);
2630 ret = WriteFile(hfile, &idd, sizeof(idd), &dummy, NULL);
2631 ok(ret, "WriteFile error %d\n", GetLastError());
2633 SetLastError(0xdeadbeef);
2634 ret = WriteFile(hfile, filler, sizeof(idd), &dummy, NULL);
2635 ok(ret, "WriteFile error %d\n", GetLastError());
2637 /* fill up to extended delay data */
2638 file_size = GetFileSize(hfile, NULL);
2639 SetLastError(0xdeadbeef);
2640 ret = WriteFile(hfile, filler, idd.DllNameRVA - file_size, &dummy, NULL);
2641 ok(ret, "WriteFile error %d\n", GetLastError());
2643 /* extended delay data */
2644 SetLastError(0xdeadbeef);
2645 ret = WriteFile(hfile, test_dll, sizeof(test_dll), &dummy, NULL);
2646 ok(ret, "WriteFile error %d\n", GetLastError());
2648 SetLastError(0xdeadbeef);
2649 ret = WriteFile(hfile, &hint, sizeof(hint), &dummy, NULL);
2650 ok(ret, "WriteFile error %d\n", GetLastError());
2652 SetLastError(0xdeadbeef);
2653 ret = WriteFile(hfile, test_func, sizeof(test_func), &dummy, NULL);
2654 ok(ret, "WriteFile error %d\n", GetLastError());
2656 file_size = GetFileSize(hfile, NULL);
2657 SetLastError(0xdeadbeef);
2658 ret = WriteFile(hfile, filler, idd.ImportNameTableRVA - file_size, &dummy, NULL);
2659 ok(ret, "WriteFile error %d\n", GetLastError());
2661 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
2663 if (td[i].func)
2664 itd32.u1.AddressOfData = idd.DllNameRVA + sizeof(test_dll);
2665 else
2666 itd32.u1.Ordinal = td[i].ordinal;
2667 SetLastError(0xdeadbeef);
2668 ret = WriteFile(hfile, &itd32, sizeof(itd32), &dummy, NULL);
2669 ok(ret, "WriteFile error %d\n", GetLastError());
2672 itd32.u1.Ordinal = 0;
2673 SetLastError(0xdeadbeef);
2674 ret = WriteFile(hfile, &itd32, sizeof(itd32), &dummy, NULL);
2675 ok(ret, "WriteFile error %d\n", GetLastError());
2677 /* fill up to eof */
2678 file_size = GetFileSize(hfile, NULL);
2679 SetLastError(0xdeadbeef);
2680 ret = WriteFile(hfile, filler, section.VirtualAddress + section.Misc.VirtualSize - file_size, &dummy, NULL);
2681 ok(ret, "WriteFile error %d\n", GetLastError());
2682 CloseHandle(hfile);
2684 SetLastError(0xdeadbeef);
2685 hlib = LoadLibraryA(dll_name);
2686 ok(hlib != NULL, "LoadLibrary error %u\n", GetLastError());
2687 if (!hlib)
2689 skip("couldn't load %s.\n", dll_name);
2690 DeleteFileA(dll_name);
2691 return;
2694 delaydir = RtlImageDirectoryEntryToData(hlib, TRUE, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, &file_size);
2695 if (!delaydir)
2697 skip("haven't found section for delay import directory.\n");
2698 FreeLibrary(hlib);
2699 DeleteFileA(dll_name);
2700 return;
2703 for (;;)
2705 IMAGE_THUNK_DATA *itdn, *itda;
2706 HMODULE htarget;
2708 if (!delaydir->DllNameRVA ||
2709 !delaydir->ImportAddressTableRVA ||
2710 !delaydir->ImportNameTableRVA) break;
2712 itdn = RVAToAddr(delaydir->ImportNameTableRVA, hlib);
2713 itda = RVAToAddr(delaydir->ImportAddressTableRVA, hlib);
2714 htarget = LoadLibraryA(RVAToAddr(delaydir->DllNameRVA, hlib));
2716 for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
2718 void *ret, *load;
2720 if (IMAGE_SNAP_BY_ORDINAL(itdn[i].u1.Ordinal))
2721 load = (void *)GetProcAddress(htarget, (LPSTR)IMAGE_ORDINAL(itdn[i].u1.Ordinal));
2722 else
2724 const IMAGE_IMPORT_BY_NAME* iibn = RVAToAddr(itdn[i].u1.AddressOfData, hlib);
2725 load = (void *)GetProcAddress(htarget, (char*)iibn->Name);
2728 cb_count = 0;
2729 ret = pResolveDelayLoadedAPI(hlib, delaydir, failuredllhook, NULL, &itda[i], 0);
2730 if (td[i].succeeds)
2732 ok(ret != NULL, "Test %u: ResolveDelayLoadedAPI failed\n", i);
2733 ok(ret == load, "Test %u: expected %p, got %p\n", i, load, ret);
2734 ok(ret == (void*)itda[i].u1.AddressOfData, "Test %u: expected %p, got %p\n",
2735 i, ret, (void*)itda[i].u1.AddressOfData);
2736 ok(!cb_count, "Test %u: Wrong callback count: %d\n", i, cb_count);
2738 else
2740 ok(ret == (void*)0xdeadbeef, "Test %u: ResolveDelayLoadedAPI succeeded with %p\n", i, ret);
2741 ok(cb_count, "Test %u: Wrong callback count: %d\n", i, cb_count);
2744 delaydir++;
2747 FreeLibrary(hlib);
2748 trace("deleting %s\n", dll_name);
2749 DeleteFileA(dll_name);
2752 START_TEST(loader)
2754 int argc;
2755 char **argv;
2756 HANDLE ntdll, mapping;
2757 SYSTEM_INFO si;
2759 ntdll = GetModuleHandleA("ntdll.dll");
2760 pNtCreateSection = (void *)GetProcAddress(ntdll, "NtCreateSection");
2761 pNtMapViewOfSection = (void *)GetProcAddress(ntdll, "NtMapViewOfSection");
2762 pNtUnmapViewOfSection = (void *)GetProcAddress(ntdll, "NtUnmapViewOfSection");
2763 pNtTerminateProcess = (void *)GetProcAddress(ntdll, "NtTerminateProcess");
2764 pNtQueryInformationProcess = (void *)GetProcAddress(ntdll, "NtQueryInformationProcess");
2765 pNtSetInformationProcess = (void *)GetProcAddress(ntdll, "NtSetInformationProcess");
2766 pLdrShutdownProcess = (void *)GetProcAddress(ntdll, "LdrShutdownProcess");
2767 pRtlDllShutdownInProgress = (void *)GetProcAddress(ntdll, "RtlDllShutdownInProgress");
2768 pNtAllocateVirtualMemory = (void *)GetProcAddress(ntdll, "NtAllocateVirtualMemory");
2769 pNtFreeVirtualMemory = (void *)GetProcAddress(ntdll, "NtFreeVirtualMemory");
2770 pLdrLockLoaderLock = (void *)GetProcAddress(ntdll, "LdrLockLoaderLock");
2771 pLdrUnlockLoaderLock = (void *)GetProcAddress(ntdll, "LdrUnlockLoaderLock");
2772 pRtlAcquirePebLock = (void *)GetProcAddress(ntdll, "RtlAcquirePebLock");
2773 pRtlReleasePebLock = (void *)GetProcAddress(ntdll, "RtlReleasePebLock");
2774 pResolveDelayLoadedAPI = (void *)GetProcAddress(GetModuleHandleA("kernel32.dll"), "ResolveDelayLoadedAPI");
2776 GetSystemInfo( &si );
2777 page_size = si.dwPageSize;
2778 dos_header.e_magic = IMAGE_DOS_SIGNATURE;
2779 dos_header.e_lfanew = sizeof(dos_header);
2781 mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, "winetest_loader");
2782 ok(mapping != 0, "CreateFileMapping failed\n");
2783 child_failures = MapViewOfFile(mapping, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 4096);
2784 if (*child_failures == -1)
2786 *child_failures = 0;
2788 else
2789 *child_failures = -1;
2791 argc = winetest_get_mainargs(&argv);
2792 if (argc > 4)
2794 test_dll_phase = atoi(argv[4]);
2795 child_process(argv[2], atol(argv[3]));
2796 return;
2799 test_Loader();
2800 test_ResolveDelayLoadedAPI();
2801 test_ImportDescriptors();
2802 test_section_access();
2803 test_import_resolution();
2804 test_ExitProcess();