1 /*
2  * Unit test suite for the PE loader.
3  *
4  * Copyright 2006,2011 Dmitry Timoshkov
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20 
21 #define NONAMELESSUNION
22 #define NONAMELESSSTRUCT
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <assert.h>
26 
27 #include "ntstatus.h"
28 #define WIN32_NO_STATUS
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winternl.h"
32 #include "winuser.h"
33 #include "wine/test.h"
34 #include "delayloadhandler.h"
35 
36 /* PROCESS_ALL_ACCESS in Vista+ PSDKs is incompatible with older Windows versions */
37 #define PROCESS_ALL_ACCESS_NT4 (PROCESS_ALL_ACCESS & ~0xf000)
38 
39 #define ALIGN_SIZE(size, alignment) (((size) + (alignment - 1)) & ~((alignment - 1)))
40 
41 struct PROCESS_BASIC_INFORMATION_PRIVATE
42 {
43     DWORD_PTR ExitStatus;
44     PPEB      PebBaseAddress;
45     DWORD_PTR AffinityMask;
46     DWORD_PTR BasePriority;
47     ULONG_PTR UniqueProcessId;
48     ULONG_PTR InheritedFromUniqueProcessId;
49 };
50 
51 static LONG *child_failures;
52 static WORD cb_count;
53 static DWORD page_size;
54 static BOOL is_win64 = sizeof(void *) > sizeof(int);
55 static BOOL is_wow64;
56 
57 static NTSTATUS (WINAPI *pNtCreateSection)(HANDLE *, ACCESS_MASK, const OBJECT_ATTRIBUTES *,
58                                            const LARGE_INTEGER *, ULONG, ULONG, HANDLE );
59 static NTSTATUS (WINAPI *pNtQuerySection)(HANDLE, SECTION_INFORMATION_CLASS, void *, SIZE_T, SIZE_T *);
60 static NTSTATUS (WINAPI *pNtMapViewOfSection)(HANDLE, HANDLE, PVOID *, ULONG, SIZE_T, const LARGE_INTEGER *, SIZE_T *, ULONG, ULONG, ULONG);
61 static NTSTATUS (WINAPI *pNtUnmapViewOfSection)(HANDLE, PVOID);
62 static NTSTATUS (WINAPI *pNtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
63 static NTSTATUS (WINAPI *pNtSetInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG);
64 static NTSTATUS (WINAPI *pNtTerminateProcess)(HANDLE, DWORD);
65 static void (WINAPI *pLdrShutdownProcess)(void);
66 static BOOLEAN (WINAPI *pRtlDllShutdownInProgress)(void);
67 static NTSTATUS (WINAPI *pNtAllocateVirtualMemory)(HANDLE, PVOID *, ULONG, SIZE_T *, ULONG, ULONG);
68 static NTSTATUS (WINAPI *pNtFreeVirtualMemory)(HANDLE, PVOID *, SIZE_T *, ULONG);
69 static NTSTATUS (WINAPI *pLdrLockLoaderLock)(ULONG, ULONG *, ULONG_PTR *);
70 static NTSTATUS (WINAPI *pLdrUnlockLoaderLock)(ULONG, ULONG_PTR);
71 static void (WINAPI *pRtlAcquirePebLock)(void);
72 static void (WINAPI *pRtlReleasePebLock)(void);
73 static PVOID    (WINAPI *pResolveDelayLoadedAPI)(PVOID, PCIMAGE_DELAYLOAD_DESCRIPTOR,
74                                                  PDELAYLOAD_FAILURE_DLL_CALLBACK, PVOID,
75                                                  PIMAGE_THUNK_DATA ThunkAddress,ULONG);
76 static PVOID (WINAPI *pRtlImageDirectoryEntryToData)(HMODULE,BOOL,WORD,ULONG *);
77 static DWORD (WINAPI *pFlsAlloc)(PFLS_CALLBACK_FUNCTION);
78 static BOOL (WINAPI *pFlsSetValue)(DWORD, PVOID);
79 static PVOID (WINAPI *pFlsGetValue)(DWORD);
80 static BOOL (WINAPI *pFlsFree)(DWORD);
81 static BOOL (WINAPI *pIsWow64Process)(HANDLE,PBOOL);
82 
RVAToAddr(DWORD_PTR rva,HMODULE module)83 static PVOID RVAToAddr(DWORD_PTR rva, HMODULE module)
84 {
85     if (rva == 0)
86         return NULL;
87     return ((char*) module) + rva;
88 }
89 
90 static IMAGE_DOS_HEADER dos_header;
91 
92 static const IMAGE_NT_HEADERS nt_header_template =
93 {
94     IMAGE_NT_SIGNATURE, /* Signature */
95     {
96 #if defined __i386__
97       IMAGE_FILE_MACHINE_I386, /* Machine */
98 #elif defined __x86_64__
99       IMAGE_FILE_MACHINE_AMD64, /* Machine */
100 #elif defined __powerpc__
101       IMAGE_FILE_MACHINE_POWERPC, /* Machine */
102 #elif defined __arm__
103       IMAGE_FILE_MACHINE_ARMNT, /* Machine */
104 #elif defined __aarch64__
105       IMAGE_FILE_MACHINE_ARM64, /* Machine */
106 #else
107 # error You must specify the machine type
108 #endif
109       1, /* NumberOfSections */
110       0, /* TimeDateStamp */
111       0, /* PointerToSymbolTable */
112       0, /* NumberOfSymbols */
113       sizeof(IMAGE_OPTIONAL_HEADER), /* SizeOfOptionalHeader */
114       IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL /* Characteristics */
115     },
116     { IMAGE_NT_OPTIONAL_HDR_MAGIC, /* Magic */
117       1, /* MajorLinkerVersion */
118       0, /* MinorLinkerVersion */
119       0, /* SizeOfCode */
120       0, /* SizeOfInitializedData */
121       0, /* SizeOfUninitializedData */
122       0, /* AddressOfEntryPoint */
123       0x10, /* BaseOfCode, also serves as e_lfanew in the truncated MZ header */
124 #ifndef _WIN64
125       0, /* BaseOfData */
126 #endif
127       0x10000000, /* ImageBase */
128       0, /* SectionAlignment */
129       0, /* FileAlignment */
130       4, /* MajorOperatingSystemVersion */
131       0, /* MinorOperatingSystemVersion */
132       1, /* MajorImageVersion */
133       0, /* MinorImageVersion */
134       4, /* MajorSubsystemVersion */
135       0, /* MinorSubsystemVersion */
136       0, /* Win32VersionValue */
137       sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000, /* SizeOfImage */
138       sizeof(dos_header) + sizeof(nt_header_template), /* SizeOfHeaders */
139       0, /* CheckSum */
140       IMAGE_SUBSYSTEM_WINDOWS_CUI, /* Subsystem */
141       0, /* DllCharacteristics */
142       0, /* SizeOfStackReserve */
143       0, /* SizeOfStackCommit */
144       0, /* SizeOfHeapReserve */
145       0, /* SizeOfHeapCommit */
146       0, /* LoaderFlags */
147       0, /* NumberOfRvaAndSizes */
148       { { 0 } } /* DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] */
149     }
150 };
151 
152 static IMAGE_SECTION_HEADER section =
153 {
154     ".rodata", /* Name */
155     { 0 }, /* Misc */
156     0, /* VirtualAddress */
157     0, /* SizeOfRawData */
158     0, /* PointerToRawData */
159     0, /* PointerToRelocations */
160     0, /* PointerToLinenumbers */
161     0, /* NumberOfRelocations */
162     0, /* NumberOfLinenumbers */
163     IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, /* Characteristics */
164 };
165 
166 
167 static const char filler[0x1000];
168 static const char section_data[0x10] = "section data";
169 
create_test_dll(const IMAGE_DOS_HEADER * dos_header,UINT dos_size,const IMAGE_NT_HEADERS * nt_header,char dll_name[MAX_PATH])170 static DWORD create_test_dll( const IMAGE_DOS_HEADER *dos_header, UINT dos_size,
171                               const IMAGE_NT_HEADERS *nt_header, char dll_name[MAX_PATH] )
172 {
173     char temp_path[MAX_PATH];
174     DWORD dummy, size, file_align;
175     HANDLE hfile;
176     BOOL ret;
177 
178     GetTempPathA(MAX_PATH, temp_path);
179     GetTempFileNameA(temp_path, "ldr", 0, dll_name);
180 
181     hfile = CreateFileA(dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0);
182     ok( hfile != INVALID_HANDLE_VALUE, "failed to create %s err %u\n", dll_name, GetLastError() );
183     if (hfile == INVALID_HANDLE_VALUE) return 0;
184 
185     SetLastError(0xdeadbeef);
186     ret = WriteFile(hfile, dos_header, dos_size, &dummy, NULL);
187     ok(ret, "WriteFile error %d\n", GetLastError());
188 
189     SetLastError(0xdeadbeef);
190     ret = WriteFile(hfile, nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
191     ok(ret, "WriteFile error %d\n", GetLastError());
192 
193     if (nt_header->FileHeader.SizeOfOptionalHeader)
194     {
195         SetLastError(0xdeadbeef);
196         ret = WriteFile(hfile, &nt_header->OptionalHeader,
197                         sizeof(IMAGE_OPTIONAL_HEADER),
198                         &dummy, NULL);
199         ok(ret, "WriteFile error %d\n", GetLastError());
200         if (nt_header->FileHeader.SizeOfOptionalHeader > sizeof(IMAGE_OPTIONAL_HEADER))
201         {
202             file_align = nt_header->FileHeader.SizeOfOptionalHeader - sizeof(IMAGE_OPTIONAL_HEADER);
203             assert(file_align < sizeof(filler));
204             SetLastError(0xdeadbeef);
205             ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
206             ok(ret, "WriteFile error %d\n", GetLastError());
207         }
208     }
209 
210     assert(nt_header->FileHeader.NumberOfSections <= 1);
211     if (nt_header->FileHeader.NumberOfSections)
212     {
213         SetFilePointer(hfile, dos_size + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + nt_header->FileHeader.SizeOfOptionalHeader, NULL, FILE_BEGIN);
214 
215         section.SizeOfRawData = 10;
216 
217         if (nt_header->OptionalHeader.SectionAlignment >= page_size)
218         {
219             section.PointerToRawData = dos_size;
220             section.VirtualAddress = nt_header->OptionalHeader.SectionAlignment;
221             section.Misc.VirtualSize = section.SizeOfRawData * 10;
222         }
223         else
224         {
225             section.PointerToRawData = nt_header->OptionalHeader.SizeOfHeaders;
226             section.VirtualAddress = nt_header->OptionalHeader.SizeOfHeaders;
227             section.Misc.VirtualSize = 5;
228         }
229 
230         SetLastError(0xdeadbeef);
231         ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
232         ok(ret, "WriteFile error %d\n", GetLastError());
233 
234         /* section data */
235         SetLastError(0xdeadbeef);
236         ret = WriteFile(hfile, section_data, sizeof(section_data), &dummy, NULL);
237         ok(ret, "WriteFile error %d\n", GetLastError());
238     }
239 
240     /* Minimal PE image that Windows7+ is able to load: 268 bytes */
241     size = GetFileSize(hfile, NULL);
242     if (size < 268)
243     {
244         file_align = 268 - size;
245         SetLastError(0xdeadbeef);
246         ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
247         ok(ret, "WriteFile error %d\n", GetLastError());
248     }
249 
250     size = GetFileSize(hfile, NULL);
251     CloseHandle(hfile);
252     return size;
253 }
254 
create_test_dll_sections(const IMAGE_DOS_HEADER * dos_header,const IMAGE_NT_HEADERS * nt_header,const IMAGE_SECTION_HEADER * sections,const void * section_data,char dll_name[MAX_PATH])255 static DWORD create_test_dll_sections( const IMAGE_DOS_HEADER *dos_header, const IMAGE_NT_HEADERS *nt_header,
256                                        const IMAGE_SECTION_HEADER *sections, const void *section_data,
257                                        char dll_name[MAX_PATH] )
258 {
259     char temp_path[MAX_PATH];
260     DWORD dummy, i, size;
261     HANDLE hfile;
262     BOOL ret;
263 
264     GetTempPathA(MAX_PATH, temp_path);
265     GetTempFileNameA(temp_path, "ldr", 0, dll_name);
266 
267     hfile = CreateFileA(dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0);
268     ok( hfile != INVALID_HANDLE_VALUE, "failed to create %s err %u\n", dll_name, GetLastError() );
269     if (hfile == INVALID_HANDLE_VALUE) return 0;
270 
271     SetLastError(0xdeadbeef);
272     ret = WriteFile(hfile, dos_header, sizeof(*dos_header), &dummy, NULL);
273     ok(ret, "WriteFile error %d\n", GetLastError());
274 
275     SetLastError(0xdeadbeef);
276     ret = WriteFile(hfile, nt_header, offsetof(IMAGE_NT_HEADERS, OptionalHeader) + nt_header->FileHeader.SizeOfOptionalHeader, &dummy, NULL);
277     ok(ret, "WriteFile error %d\n", GetLastError());
278 
279     SetLastError(0xdeadbeef);
280     ret = WriteFile(hfile, sections, sizeof(*sections) * nt_header->FileHeader.NumberOfSections,
281                     &dummy, NULL);
282     ok(ret, "WriteFile error %d\n", GetLastError());
283 
284     for (i = 0; i < nt_header->FileHeader.NumberOfSections; i++)
285     {
286         SetFilePointer(hfile, sections[i].PointerToRawData, NULL, FILE_BEGIN);
287         SetLastError(0xdeadbeef);
288         ret = WriteFile(hfile, section_data, sections[i].SizeOfRawData, &dummy, NULL);
289         ok(ret, "WriteFile error %d\n", GetLastError());
290     }
291     size = GetFileSize(hfile, NULL);
292     CloseHandle(hfile);
293     return size;
294 }
295 
query_image_section(int id,const char * dll_name,const IMAGE_NT_HEADERS * nt_header,const void * section_data)296 static BOOL query_image_section( int id, const char *dll_name, const IMAGE_NT_HEADERS *nt_header,
297                                  const void *section_data )
298 {
299     static BOOL is_winxp;
300     SECTION_BASIC_INFORMATION info;
301     SECTION_IMAGE_INFORMATION image;
302     const IMAGE_COR20_HEADER *cor_header = NULL;
303     SIZE_T info_size = (SIZE_T)0xdeadbeef << 16;
304     NTSTATUS status;
305     HANDLE file, mapping;
306     ULONG file_size;
307     LARGE_INTEGER map_size;
308     SIZE_T max_stack, commit_stack;
309     void *entry_point;
310 
311     /* truncated header is not handled correctly in windows <= w2k3 */
312     BOOL truncated;
313 
314     file = CreateFileA( dll_name, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE,
315                         NULL, OPEN_EXISTING, 0, 0 );
316     ok( file != INVALID_HANDLE_VALUE, "%u: CreateFile error %d\n", id, GetLastError() );
317     file_size = GetFileSize( file, NULL );
318 
319     status = pNtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_MAP_READ | SECTION_QUERY,
320                                NULL, NULL, PAGE_READONLY, SEC_IMAGE, file );
321     ok( !status, "%u: NtCreateSection failed err %x\n", id, status );
322     if (status)
323     {
324         CloseHandle( file );
325         return FALSE;
326     }
327     status = pNtQuerySection( mapping, SectionImageInformation, &image, sizeof(image), &info_size );
328     ok( !status, "%u: NtQuerySection failed err %x\n", id, status );
329     ok( info_size == sizeof(image), "%u: NtQuerySection wrong size %lu\n", id, info_size );
330     if (nt_header->OptionalHeader.Magic == (is_win64 ? IMAGE_NT_OPTIONAL_HDR64_MAGIC
331                                                      : IMAGE_NT_OPTIONAL_HDR32_MAGIC))
332     {
333         max_stack = nt_header->OptionalHeader.SizeOfStackReserve;
334         commit_stack = nt_header->OptionalHeader.SizeOfStackCommit;
335         entry_point = (char *)nt_header->OptionalHeader.ImageBase + nt_header->OptionalHeader.AddressOfEntryPoint;
336         truncated = nt_header->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER);
337         if (!truncated &&
338             nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress &&
339             nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size)
340             cor_header = section_data;
341     }
342     else if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
343     {
344         const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt_header;
345         max_stack = 0x100000;
346         commit_stack = 0x10000;
347         entry_point = (void *)0x81231234;
348         truncated = nt_header->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER64);
349         if (!truncated &&
350             nt64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress &&
351             nt64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size)
352             cor_header = section_data;
353     }
354     else
355     {
356         const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt_header;
357         max_stack = nt32->OptionalHeader.SizeOfStackReserve;
358         commit_stack = nt32->OptionalHeader.SizeOfStackCommit;
359         entry_point = (char *)(ULONG_PTR)nt32->OptionalHeader.ImageBase + nt32->OptionalHeader.AddressOfEntryPoint;
360         truncated = nt_header->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER32);
361         if (!truncated &&
362             nt32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress &&
363             nt32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size)
364             cor_header = section_data;
365     }
366     ok( (char *)image.TransferAddress == (char *)entry_point ||
367         (S(U(image)).ImageDynamicallyRelocated && LOWORD(image.TransferAddress) == LOWORD(entry_point)),
368         "%u: TransferAddress wrong %p / %p (%08x)\n", id,
369         image.TransferAddress, entry_point, nt_header->OptionalHeader.AddressOfEntryPoint );
370     ok( image.ZeroBits == 0, "%u: ZeroBits wrong %08x\n", id, image.ZeroBits );
371     ok( image.MaximumStackSize == max_stack || broken(truncated),
372         "%u: MaximumStackSize wrong %lx / %lx\n", id, image.MaximumStackSize, max_stack );
373     ok( image.CommittedStackSize == commit_stack || broken(truncated),
374         "%u: CommittedStackSize wrong %lx / %lx\n", id, image.CommittedStackSize, commit_stack );
375     if (truncated)
376         ok( !image.SubSystemType || broken(truncated),
377             "%u: SubSystemType wrong %08x / 00000000\n", id, image.SubSystemType );
378     else
379         ok( image.SubSystemType == nt_header->OptionalHeader.Subsystem,
380             "%u: SubSystemType wrong %08x / %08x\n", id,
381             image.SubSystemType, nt_header->OptionalHeader.Subsystem );
382     ok( image.SubsystemVersionLow == nt_header->OptionalHeader.MinorSubsystemVersion,
383         "%u: SubsystemVersionLow wrong %04x / %04x\n", id,
384         image.SubsystemVersionLow, nt_header->OptionalHeader.MinorSubsystemVersion );
385     ok( image.SubsystemVersionHigh == nt_header->OptionalHeader.MajorSubsystemVersion,
386         "%u: SubsystemVersionHigh wrong %04x / %04x\n", id,
387         image.SubsystemVersionHigh, nt_header->OptionalHeader.MajorSubsystemVersion );
388     ok( image.ImageCharacteristics == nt_header->FileHeader.Characteristics,
389         "%u: ImageCharacteristics wrong %04x / %04x\n", id,
390         image.ImageCharacteristics, nt_header->FileHeader.Characteristics );
391     ok( image.DllCharacteristics == nt_header->OptionalHeader.DllCharacteristics || broken(truncated),
392         "%u: DllCharacteristics wrong %04x / %04x\n", id,
393         image.DllCharacteristics, nt_header->OptionalHeader.DllCharacteristics );
394     ok( image.Machine == nt_header->FileHeader.Machine, "%u: Machine wrong %04x / %04x\n", id,
395         image.Machine, nt_header->FileHeader.Machine );
396     ok( image.LoaderFlags == (cor_header != NULL), "%u: LoaderFlags wrong %08x\n", id, image.LoaderFlags );
397     ok( image.ImageFileSize == file_size || broken(!image.ImageFileSize), /* winxpsp1 */
398         "%u: ImageFileSize wrong %08x / %08x\n", id, image.ImageFileSize, file_size );
399     ok( image.CheckSum == nt_header->OptionalHeader.CheckSum || broken(truncated),
400         "%u: CheckSum wrong %08x / %08x\n", id,
401         image.CheckSum, nt_header->OptionalHeader.CheckSum );
402 
403     if (nt_header->OptionalHeader.SizeOfCode || nt_header->OptionalHeader.AddressOfEntryPoint)
404         ok( image.ImageContainsCode == TRUE, "%u: ImageContainsCode wrong %u\n", id,
405             image.ImageContainsCode );
406     else if ((nt_header->OptionalHeader.SectionAlignment % page_size) ||
407              (nt_header->FileHeader.NumberOfSections == 1 &&
408               (section.Characteristics & IMAGE_SCN_MEM_EXECUTE)))
409         ok( image.ImageContainsCode == TRUE || broken(!image.ImageContainsCode), /* <= win8 */
410             "%u: ImageContainsCode wrong %u\n", id, image.ImageContainsCode );
411     else
412         ok( !image.ImageContainsCode, "%u: ImageContainsCode wrong %u\n", id, image.ImageContainsCode );
413 
414     if (cor_header &&
415         (cor_header->Flags & COMIMAGE_FLAGS_ILONLY) &&
416         (cor_header->MajorRuntimeVersion > 2 ||
417          (cor_header->MajorRuntimeVersion == 2 && cor_header->MinorRuntimeVersion >= 5)))
418     {
419         ok( S(U(image)).ComPlusILOnly || broken(is_winxp),
420             "%u: wrong ComPlusILOnly flags %02x\n", id, U(image).ImageFlags );
421         if (nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC &&
422             !(cor_header->Flags & COMIMAGE_FLAGS_32BITREQUIRED))
423             ok( S(U(image)).ComPlusNativeReady || broken(is_winxp),
424                 "%u: wrong ComPlusNativeReady flags %02x\n", id, U(image).ImageFlags );
425         else
426             ok( !S(U(image)).ComPlusNativeReady,
427                 "%u: wrong ComPlusNativeReady flags %02x\n", id, U(image).ImageFlags );
428     }
429     else
430     {
431         ok( !S(U(image)).ComPlusILOnly, "%u: wrong ComPlusILOnly flags %02x\n", id, U(image).ImageFlags );
432         ok( !S(U(image)).ComPlusNativeReady, "%u: wrong ComPlusNativeReady flags %02x\n", id, U(image).ImageFlags );
433     }
434     if (!(nt_header->OptionalHeader.SectionAlignment % page_size))
435         ok( !S(U(image)).ImageMappedFlat, "%u: wrong ImageMappedFlat flags %02x\n", id, U(image).ImageFlags );
436     else
437     {
438         /* winxp doesn't support any of the loader flags */
439         if (!S(U(image)).ImageMappedFlat) is_winxp = TRUE;
440         ok( S(U(image)).ImageMappedFlat || broken(is_winxp),
441         "%u: wrong ImageMappedFlat flags %02x\n", id, U(image).ImageFlags );
442     }
443     if (!(nt_header->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE))
444         ok( !S(U(image)).ImageDynamicallyRelocated || broken( S(U(image)).ComPlusILOnly ), /* <= win7 */
445             "%u: wrong ImageDynamicallyRelocated flags %02x\n", id, U(image).ImageFlags );
446     else if (image.ImageContainsCode && !cor_header)
447         ok( S(U(image)).ImageDynamicallyRelocated || broken(is_winxp),
448             "%u: wrong ImageDynamicallyRelocated flags %02x\n", id, U(image).ImageFlags );
449     else
450         ok( !S(U(image)).ImageDynamicallyRelocated || broken(TRUE), /* <= win8 */
451             "%u: wrong ImageDynamicallyRelocated flags %02x\n", id, U(image).ImageFlags );
452     ok( !S(U(image)).BaseBelow4gb, "%u: wrong BaseBelow4gb flags %02x\n", id, U(image).ImageFlags );
453 
454     /* FIXME: needs more work: */
455     /* image.GpValue */
456 
457     map_size.QuadPart = (nt_header->OptionalHeader.SizeOfImage + page_size - 1) & ~(page_size - 1);
458     status = pNtQuerySection( mapping, SectionBasicInformation, &info, sizeof(info), NULL );
459     ok( !status, "NtQuerySection failed err %x\n", status );
460     ok( info.Size.QuadPart == map_size.QuadPart, "NtQuerySection wrong size %x%08x / %x%08x\n",
461         info.Size.u.HighPart, info.Size.u.LowPart, map_size.u.HighPart, map_size.u.LowPart );
462     CloseHandle( mapping );
463 
464     map_size.QuadPart = (nt_header->OptionalHeader.SizeOfImage + page_size - 1) & ~(page_size - 1);
465     status = pNtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_MAP_READ | SECTION_QUERY,
466                                NULL, &map_size, PAGE_READONLY, SEC_IMAGE, file );
467     ok( !status, "%u: NtCreateSection failed err %x\n", id, status );
468     status = pNtQuerySection( mapping, SectionBasicInformation, &info, sizeof(info), NULL );
469     ok( !status, "NtQuerySection failed err %x\n", status );
470     ok( info.Size.QuadPart == map_size.QuadPart, "NtQuerySection wrong size %x%08x / %x%08x\n",
471         info.Size.u.HighPart, info.Size.u.LowPart, map_size.u.HighPart, map_size.u.LowPart );
472     CloseHandle( mapping );
473 
474     map_size.QuadPart++;
475     status = pNtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_MAP_READ | SECTION_QUERY,
476                                NULL, &map_size, PAGE_READONLY, SEC_IMAGE, file );
477     ok( status == STATUS_SECTION_TOO_BIG, "%u: NtCreateSection failed err %x\n", id, status );
478 
479     SetFilePointerEx( file, map_size, NULL, FILE_BEGIN );
480     SetEndOfFile( file );
481     status = pNtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_MAP_READ | SECTION_QUERY,
482                                NULL, &map_size, PAGE_READONLY, SEC_IMAGE, file );
483     ok( status == STATUS_SECTION_TOO_BIG, "%u: NtCreateSection failed err %x\n", id, status );
484 
485     map_size.QuadPart = 1;
486     status = pNtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_MAP_READ | SECTION_QUERY,
487                                NULL, &map_size, PAGE_READONLY, SEC_IMAGE, file );
488     ok( !status, "%u: NtCreateSection failed err %x\n", id, status );
489     status = pNtQuerySection( mapping, SectionBasicInformation, &info, sizeof(info), NULL );
490     ok( !status, "NtQuerySection failed err %x\n", status );
491     ok( info.Size.QuadPart == map_size.QuadPart, "NtQuerySection wrong size %x%08x / %x%08x\n",
492         info.Size.u.HighPart, info.Size.u.LowPart, map_size.u.HighPart, map_size.u.LowPart );
493     CloseHandle( mapping );
494 
495     CloseHandle( file );
496     return image.ImageContainsCode && (!cor_header || !(cor_header->Flags & COMIMAGE_FLAGS_ILONLY));
497 }
498 
499 /* helper to test image section mapping */
map_image_section(const IMAGE_NT_HEADERS * nt_header,const IMAGE_SECTION_HEADER * sections,const void * section_data,int line)500 static NTSTATUS map_image_section( const IMAGE_NT_HEADERS *nt_header, const IMAGE_SECTION_HEADER *sections,
501                                    const void *section_data, int line )
502 {
503     char dll_name[MAX_PATH];
504     LARGE_INTEGER size;
505     HANDLE file, map;
506     NTSTATUS status;
507     ULONG file_size;
508     BOOL has_code;
509     HMODULE mod;
510 
511     file_size = create_test_dll_sections( &dos_header, nt_header, sections, section_data, dll_name );
512 
513     file = CreateFileA(dll_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
514     ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
515 
516     size.QuadPart = file_size;
517     status = pNtCreateSection(&map, STANDARD_RIGHTS_REQUIRED | SECTION_MAP_READ | SECTION_QUERY,
518                               NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
519     if (!status)
520     {
521         SECTION_BASIC_INFORMATION info;
522         SIZE_T info_size = 0xdeadbeef;
523         NTSTATUS ret = pNtQuerySection( map, SectionBasicInformation, &info, sizeof(info), &info_size );
524         ok( !ret, "NtQuerySection failed err %x\n", ret );
525         ok( info_size == sizeof(info), "NtQuerySection wrong size %lu\n", info_size );
526         ok( info.Attributes == (SEC_IMAGE | SEC_FILE), "NtQuerySection wrong attr %x\n", info.Attributes );
527         ok( info.BaseAddress == NULL, "NtQuerySection wrong base %p\n", info.BaseAddress );
528         ok( info.Size.QuadPart == file_size, "NtQuerySection wrong size %x%08x / %08x\n",
529             info.Size.u.HighPart, info.Size.u.LowPart, file_size );
530         has_code = query_image_section( line, dll_name, nt_header, section_data );
531         /* test loading dll of wrong 32/64 bitness */
532         if (nt_header->OptionalHeader.Magic == (is_win64 ? IMAGE_NT_OPTIONAL_HDR32_MAGIC
533                                                          : IMAGE_NT_OPTIONAL_HDR64_MAGIC))
534         {
535             SetLastError( 0xdeadbeef );
536             mod = LoadLibraryExA( dll_name, 0, DONT_RESOLVE_DLL_REFERENCES );
537             if (!has_code && nt_header->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
538             {
539                 BOOL il_only = FALSE;
540                 if (((const IMAGE_NT_HEADERS32 *)nt_header)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress)
541                 {
542                     const IMAGE_COR20_HEADER *cor_header = section_data;
543                     il_only = (cor_header->Flags & COMIMAGE_FLAGS_ILONLY) != 0;
544                 }
545                 ok( mod != NULL || broken(il_only), /* <= win7 */
546                     "%u: loading failed err %u\n", line, GetLastError() );
547             }
548             else
549             {
550                 ok( !mod, "%u: loading succeeded\n", line );
551                 ok( GetLastError() == ERROR_BAD_EXE_FORMAT, "%u: wrong error %u\n", line, GetLastError() );
552             }
553             if (mod) FreeLibrary( mod );
554         }
555     }
556     if (map) CloseHandle( map );
557     CloseHandle( file );
558     DeleteFileA( dll_name );
559     return status;
560 }
561 
562 
test_Loader(void)563 static void test_Loader(void)
564 {
565     static const struct test_data
566     {
567         DWORD size_of_dos_header;
568         WORD number_of_sections, size_of_optional_header;
569         DWORD section_alignment, file_alignment;
570         DWORD size_of_image, size_of_headers;
571         DWORD errors[4]; /* 0 means LoadLibrary should succeed */
572     } td[] =
573     {
574         { sizeof(dos_header),
575           1, 0, 0, 0, 0, 0,
576           { ERROR_BAD_EXE_FORMAT }
577         },
578         { sizeof(dos_header),
579           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
580           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0xe00,
581           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
582           { ERROR_BAD_EXE_FORMAT } /* XP doesn't like too small image size */
583         },
584         { sizeof(dos_header),
585           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
586           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
587           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
588           { ERROR_SUCCESS }
589         },
590         { sizeof(dos_header),
591           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x1000,
592           0x1f00,
593           0x1000,
594           { ERROR_SUCCESS }
595         },
596         { sizeof(dos_header),
597           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x200, 0x200,
598           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x200,
599           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
600           { ERROR_SUCCESS, ERROR_INVALID_ADDRESS } /* vista is more strict */
601         },
602         { sizeof(dos_header),
603           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x200, 0x1000,
604           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
605           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
606           { ERROR_BAD_EXE_FORMAT } /* XP doesn't like alignments */
607         },
608         { sizeof(dos_header),
609           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x200,
610           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
611           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER),
612           { ERROR_SUCCESS }
613         },
614         { sizeof(dos_header),
615           1, sizeof(IMAGE_OPTIONAL_HEADER), 0x1000, 0x200,
616           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
617           0x200,
618           { ERROR_SUCCESS }
619         },
620         /* Mandatory are all fields up to SizeOfHeaders, everything else
621          * is really optional (at least that's true for XP).
622          */
623 #if 0 /* 32-bit Windows 8 crashes inside of LoadLibrary */
624         { sizeof(dos_header),
625           1, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
626           sizeof(dos_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum) + sizeof(IMAGE_SECTION_HEADER) + 0x10,
627           sizeof(dos_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER) + FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum) + sizeof(IMAGE_SECTION_HEADER),
628           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT, ERROR_INVALID_ADDRESS,
629             ERROR_NOACCESS }
630         },
631 #endif
632         { sizeof(dos_header),
633           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
634           0xd0, /* beyond of the end of file */
635           0xc0, /* beyond of the end of file */
636           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
637         },
638         { sizeof(dos_header),
639           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
640           0x1000,
641           0,
642           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
643         },
644         { sizeof(dos_header),
645           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
646           1,
647           0,
648           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
649         },
650 #if 0 /* not power of 2 alignments need more test cases */
651         { sizeof(dos_header),
652           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x300, 0x300,
653           1,
654           0,
655           { ERROR_BAD_EXE_FORMAT } /* alignment is not power of 2 */
656         },
657 #endif
658         { sizeof(dos_header),
659           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 4, 4,
660           1,
661           0,
662           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
663         },
664         { sizeof(dos_header),
665           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 1, 1,
666           1,
667           0,
668           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
669         },
670         { sizeof(dos_header),
671           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum), 0x200, 0x200,
672           0,
673           0,
674           { ERROR_BAD_EXE_FORMAT } /* image size == 0 -> failure */
675         },
676         /* the following data mimics the PE image which upack creates */
677         { 0x10,
678           1, 0x148, 0x1000, 0x200,
679           sizeof(dos_header) + sizeof(nt_header_template) + sizeof(IMAGE_SECTION_HEADER) + 0x1000,
680           0x200,
681           { ERROR_SUCCESS }
682         },
683         /* Minimal PE image that XP is able to load: 92 bytes */
684         { 0x04,
685           0, FIELD_OFFSET(IMAGE_OPTIONAL_HEADER, CheckSum),
686           0x04 /* also serves as e_lfanew in the truncated MZ header */, 0x04,
687           1,
688           0,
689           { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
690         },
691         /* Minimal PE image that Windows7 is able to load: 268 bytes */
692         { 0x04,
693           0, 0xf0, /* optional header size just forces 0xf0 bytes to be written,
694                       0 or another number don't change the behaviour, what really
695                       matters is file size regardless of values in the headers */
696           0x04 /* also serves as e_lfanew in the truncated MZ header */, 0x04,
697           0x40, /* minimal image size that Windows7 accepts */
698           0,
699           { ERROR_SUCCESS }
700         },
701         /* the following data mimics the PE image which 8k demos have */
702         { 0x04,
703           0, 0x08,
704           0x04 /* also serves as e_lfanew in the truncated MZ header */, 0x04,
705           0x200000,
706           0x40,
707           { ERROR_SUCCESS }
708         }
709     };
710     int i;
711     DWORD file_size;
712     HANDLE h;
713     HMODULE hlib, hlib_as_data_file;
714     char dll_name[MAX_PATH];
715     SIZE_T size;
716     BOOL ret;
717     NTSTATUS status;
718     WORD alt_machine, orig_machine = nt_header_template.FileHeader.Machine;
719     IMAGE_NT_HEADERS nt_header;
720     IMAGE_COR20_HEADER cor_header;
721 
722     /* prevent displaying of the "Unable to load this DLL" message box */
723     SetErrorMode(SEM_FAILCRITICALERRORS);
724 
725     for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
726     {
727         nt_header = nt_header_template;
728         nt_header.FileHeader.NumberOfSections = td[i].number_of_sections;
729         nt_header.FileHeader.SizeOfOptionalHeader = td[i].size_of_optional_header;
730 
731         nt_header.OptionalHeader.SectionAlignment = td[i].section_alignment;
732         nt_header.OptionalHeader.FileAlignment = td[i].file_alignment;
733         nt_header.OptionalHeader.SizeOfImage = td[i].size_of_image;
734         nt_header.OptionalHeader.SizeOfHeaders = td[i].size_of_headers;
735 
736         file_size = create_test_dll( &dos_header, td[i].size_of_dos_header, &nt_header, dll_name );
737 
738         SetLastError(0xdeadbeef);
739         hlib = LoadLibraryA(dll_name);
740         if (hlib)
741         {
742             MEMORY_BASIC_INFORMATION info;
743             void *ptr;
744 
745             ok( td[i].errors[0] == ERROR_SUCCESS, "%d: should have failed\n", i );
746 
747             SetLastError(0xdeadbeef);
748             size = VirtualQuery(hlib, &info, sizeof(info));
749             ok(size == sizeof(info),
750                 "%d: VirtualQuery error %d\n", i, GetLastError());
751             ok(info.BaseAddress == hlib, "%d: %p != %p\n", i, info.BaseAddress, hlib);
752             ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
753             ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
754             ok(info.RegionSize == ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %lx != expected %x\n",
755                i, info.RegionSize, ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
756             ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
757             if (nt_header.OptionalHeader.SectionAlignment < page_size)
758                 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
759             else
760                 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
761             ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
762 
763             SetLastError(0xdeadbeef);
764             ptr = VirtualAlloc(hlib, page_size, MEM_COMMIT, info.Protect);
765             ok(!ptr, "%d: VirtualAlloc should fail\n", i);
766             ok(GetLastError() == ERROR_ACCESS_DENIED, "%d: expected ERROR_ACCESS_DENIED, got %d\n", i, GetLastError());
767 
768             SetLastError(0xdeadbeef);
769             size = VirtualQuery((char *)hlib + info.RegionSize, &info, sizeof(info));
770             ok(size == sizeof(info),
771                 "%d: VirtualQuery error %d\n", i, GetLastError());
772             if (nt_header.OptionalHeader.SectionAlignment == page_size ||
773                 nt_header.OptionalHeader.SectionAlignment == nt_header.OptionalHeader.FileAlignment)
774             {
775                 ok(info.BaseAddress == (char *)hlib + ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %p != expected %p\n",
776                    i, info.BaseAddress, (char *)hlib + ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
777                 ok(info.AllocationBase == 0, "%d: %p != 0\n", i, info.AllocationBase);
778                 ok(info.AllocationProtect == 0, "%d: %x != 0\n", i, info.AllocationProtect);
779                 /*ok(info.RegionSize == not_practical_value, "%d: %lx != not_practical_value\n", i, info.RegionSize);*/
780                 ok(info.State == MEM_FREE, "%d: %x != MEM_FREE\n", i, info.State);
781                 ok(info.Type == 0, "%d: %x != 0\n", i, info.Type);
782                 ok(info.Protect == PAGE_NOACCESS, "%d: %x != PAGE_NOACCESS\n", i, info.Protect);
783             }
784             else
785             {
786                 ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
787                 ok(info.BaseAddress == hlib, "%d: got %p != expected %p\n", i, info.BaseAddress, hlib);
788                 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
789                 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
790                 ok(info.RegionSize == ALIGN_SIZE(file_size, page_size), "%d: got %lx != expected %x\n",
791                    i, info.RegionSize, ALIGN_SIZE(file_size, page_size));
792                 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
793                 ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
794                 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
795             }
796 
797             /* header: check the zeroing of alignment */
798             if (nt_header.OptionalHeader.SectionAlignment >= page_size)
799             {
800                 const char *start;
801 
802                 start = (const char *)hlib + nt_header.OptionalHeader.SizeOfHeaders;
803                 size = ALIGN_SIZE((ULONG_PTR)start, page_size) - (ULONG_PTR)start;
804                 ok(!memcmp(start, filler, size), "%d: header alignment is not cleared\n", i);
805             }
806 
807             if (nt_header.FileHeader.NumberOfSections)
808             {
809                 SetLastError(0xdeadbeef);
810                 size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
811                 ok(size == sizeof(info),
812                     "%d: VirtualQuery error %d\n", i, GetLastError());
813                 if (nt_header.OptionalHeader.SectionAlignment < page_size)
814                 {
815                     ok(info.BaseAddress == hlib, "%d: got %p != expected %p\n", i, info.BaseAddress, hlib);
816                     ok(info.RegionSize == ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size), "%d: got %lx != expected %x\n",
817                        i, info.RegionSize, ALIGN_SIZE(nt_header.OptionalHeader.SizeOfImage, page_size));
818                     ok(info.Protect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.Protect);
819                 }
820                 else
821                 {
822                     ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
823                     ok(info.RegionSize == ALIGN_SIZE(section.Misc.VirtualSize, page_size), "%d: got %lx != expected %x\n",
824                        i, info.RegionSize, ALIGN_SIZE(section.Misc.VirtualSize, page_size));
825                     ok(info.Protect == PAGE_READONLY, "%d: %x != PAGE_READONLY\n", i, info.Protect);
826                 }
827                 ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
828                 ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
829                 ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
830                 ok(info.Type == SEC_IMAGE, "%d: %x != SEC_IMAGE\n", i, info.Type);
831 
832                 if (nt_header.OptionalHeader.SectionAlignment >= page_size)
833                     ok(!memcmp((const char *)hlib + section.VirtualAddress + section.PointerToRawData, &nt_header, section.SizeOfRawData), "wrong section data\n");
834                 else
835                     ok(!memcmp((const char *)hlib + section.PointerToRawData, section_data, section.SizeOfRawData), "wrong section data\n");
836 
837                 /* check the zeroing of alignment */
838                 if (nt_header.OptionalHeader.SectionAlignment >= page_size)
839                 {
840                     const char *start;
841 
842                     start = (const char *)hlib + section.VirtualAddress + section.PointerToRawData + section.SizeOfRawData;
843                     size = ALIGN_SIZE((ULONG_PTR)start, page_size) - (ULONG_PTR)start;
844                     ok(memcmp(start, filler, size), "%d: alignment should not be cleared\n", i);
845                 }
846 
847                 SetLastError(0xdeadbeef);
848                 ptr = VirtualAlloc((char *)hlib + section.VirtualAddress, page_size, MEM_COMMIT, info.Protect);
849                 ok(!ptr, "%d: VirtualAlloc should fail\n", i);
850                 ok(GetLastError() == ERROR_ACCESS_DENIED || GetLastError() == ERROR_INVALID_ADDRESS,
851                    "%d: expected ERROR_ACCESS_DENIED, got %d\n", i, GetLastError());
852             }
853 
854             SetLastError(0xdeadbeef);
855             hlib_as_data_file = LoadLibraryExA(dll_name, 0, LOAD_LIBRARY_AS_DATAFILE);
856             ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
857             ok(hlib_as_data_file == hlib, "hlib_as_file and hlib are different\n");
858 
859             SetLastError(0xdeadbeef);
860             ret = FreeLibrary(hlib);
861             ok(ret, "FreeLibrary error %d\n", GetLastError());
862 
863             SetLastError(0xdeadbeef);
864             hlib = GetModuleHandleA(dll_name);
865             ok(hlib != 0, "GetModuleHandle error %u\n", GetLastError());
866 
867             SetLastError(0xdeadbeef);
868             ret = FreeLibrary(hlib_as_data_file);
869             ok(ret, "FreeLibrary error %d\n", GetLastError());
870 
871             hlib = GetModuleHandleA(dll_name);
872             ok(!hlib, "GetModuleHandle should fail\n");
873 
874             SetLastError(0xdeadbeef);
875             hlib_as_data_file = LoadLibraryExA(dll_name, 0, LOAD_LIBRARY_AS_DATAFILE);
876             ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
877             ok(((ULONG_PTR)hlib_as_data_file & 3) == 1, "hlib_as_data_file got %p\n", hlib_as_data_file);
878 
879             hlib = GetModuleHandleA(dll_name);
880             ok(!hlib, "GetModuleHandle should fail\n");
881 
882             SetLastError(0xdeadbeef);
883             h = CreateFileA( dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
884             ok( h != INVALID_HANDLE_VALUE, "open failed err %u\n", GetLastError() );
885             CloseHandle( h );
886 
887             SetLastError(0xdeadbeef);
888             ret = FreeLibrary(hlib_as_data_file);
889             ok(ret, "FreeLibrary error %d\n", GetLastError());
890 
891             SetLastError(0xdeadbeef);
892             hlib_as_data_file = LoadLibraryExA(dll_name, 0, LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE);
893             if (!((ULONG_PTR)hlib_as_data_file & 3) ||  /* winxp */
894                 (!hlib_as_data_file && GetLastError() == ERROR_INVALID_PARAMETER))  /* w2k3 */
895             {
896                 win_skip( "LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE not supported\n" );
897                 FreeLibrary(hlib_as_data_file);
898             }
899             else
900             {
901                 ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
902 
903                 SetLastError(0xdeadbeef);
904                 h = CreateFileA( dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
905                 ok( h == INVALID_HANDLE_VALUE, "open succeeded\n" );
906                 ok( GetLastError() == ERROR_SHARING_VIOLATION, "wrong error %u\n", GetLastError() );
907                 CloseHandle( h );
908 
909                 SetLastError(0xdeadbeef);
910                 h = CreateFileA( dll_name, GENERIC_READ | DELETE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
911                 ok( h != INVALID_HANDLE_VALUE, "open failed err %u\n", GetLastError() );
912                 CloseHandle( h );
913 
914                 SetLastError(0xdeadbeef);
915                 ret = FreeLibrary(hlib_as_data_file);
916                 ok(ret, "FreeLibrary error %d\n", GetLastError());
917             }
918 
919             SetLastError(0xdeadbeef);
920             hlib_as_data_file = LoadLibraryExA(dll_name, 0, LOAD_LIBRARY_AS_IMAGE_RESOURCE);
921             if (!((ULONG_PTR)hlib_as_data_file & 3) ||  /* winxp */
922                 (!hlib_as_data_file && GetLastError() == ERROR_INVALID_PARAMETER))  /* w2k3 */
923             {
924                 win_skip( "LOAD_LIBRARY_AS_IMAGE_RESOURCE not supported\n" );
925                 FreeLibrary(hlib_as_data_file);
926             }
927             else
928             {
929                 ok(hlib_as_data_file != 0, "LoadLibraryEx error %u\n", GetLastError());
930                 ok(((ULONG_PTR)hlib_as_data_file & 3) == 2, "hlib_as_data_file got %p\n",
931                    hlib_as_data_file);
932 
933                 hlib = GetModuleHandleA(dll_name);
934                 ok(!hlib, "GetModuleHandle should fail\n");
935 
936                 SetLastError(0xdeadbeef);
937                 ret = FreeLibrary(hlib_as_data_file);
938                 ok(ret, "FreeLibrary error %d\n", GetLastError());
939             }
940 
941             SetLastError(0xdeadbeef);
942             ret = DeleteFileA(dll_name);
943             ok(ret, "DeleteFile error %d\n", GetLastError());
944 
945             nt_header.OptionalHeader.AddressOfEntryPoint = 0x12345678;
946             file_size = create_test_dll( &dos_header, td[i].size_of_dos_header, &nt_header, dll_name );
947             if (!file_size)
948             {
949                 ok(0, "could not create %s\n", dll_name);
950                 break;
951             }
952 
953             query_image_section( i, dll_name, &nt_header, NULL );
954         }
955         else
956         {
957             BOOL error_match;
958             int error_index;
959 
960             error_match = FALSE;
961             for (error_index = 0;
962                  ! error_match && error_index < sizeof(td[i].errors) / sizeof(DWORD);
963                  error_index++)
964             {
965                 error_match = td[i].errors[error_index] == GetLastError();
966             }
967             ok(error_match, "%d: unexpected error %d\n", i, GetLastError());
968         }
969 
970         SetLastError(0xdeadbeef);
971         ret = DeleteFileA(dll_name);
972         ok(ret, "DeleteFile error %d\n", GetLastError());
973     }
974 
975     nt_header = nt_header_template;
976     nt_header.FileHeader.NumberOfSections = 1;
977     nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
978 
979     nt_header.OptionalHeader.SectionAlignment = page_size;
980     nt_header.OptionalHeader.AddressOfEntryPoint = 0x1234;
981     nt_header.OptionalHeader.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
982     nt_header.OptionalHeader.FileAlignment = page_size;
983     nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
984     nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + page_size;
985 
986     section.SizeOfRawData = sizeof(section_data);
987     section.PointerToRawData = page_size;
988     section.VirtualAddress = page_size;
989     section.Misc.VirtualSize = page_size;
990 
991     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
992     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
993 
994     nt_header.OptionalHeader.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
995     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
996     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
997 
998     nt_header.OptionalHeader.SizeOfCode = 0x1000;
999     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1000     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1001     nt_header.OptionalHeader.SizeOfCode = 0;
1002     nt_header.OptionalHeader.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
1003 
1004     dos_header.e_magic = 0;
1005     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1006     ok( status == STATUS_INVALID_IMAGE_NOT_MZ, "NtCreateSection error %08x\n", status );
1007 
1008     dos_header.e_magic = IMAGE_DOS_SIGNATURE;
1009     nt_header.Signature = IMAGE_OS2_SIGNATURE;
1010     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1011     ok( status == STATUS_INVALID_IMAGE_NE_FORMAT, "NtCreateSection error %08x\n", status );
1012 
1013     nt_header.Signature = 0xdeadbeef;
1014     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1015     ok( status == STATUS_INVALID_IMAGE_PROTECT, "NtCreateSection error %08x\n", status );
1016 
1017     nt_header.Signature = IMAGE_NT_SIGNATURE;
1018     nt_header.OptionalHeader.Magic = 0xdead;
1019     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1020     ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
1021 
1022     nt_header.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
1023     nt_header.FileHeader.Machine = 0xdead;
1024     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1025     ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
1026         "NtCreateSection error %08x\n", status );
1027 
1028     nt_header.FileHeader.Machine = IMAGE_FILE_MACHINE_UNKNOWN;
1029     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1030     ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
1031         "NtCreateSection error %08x\n", status );
1032 
1033     switch (orig_machine)
1034     {
1035     case IMAGE_FILE_MACHINE_I386:  alt_machine = IMAGE_FILE_MACHINE_ARMNT; break;
1036     case IMAGE_FILE_MACHINE_AMD64: alt_machine = IMAGE_FILE_MACHINE_ARM64; break;
1037     case IMAGE_FILE_MACHINE_ARMNT: alt_machine = IMAGE_FILE_MACHINE_I386; break;
1038     case IMAGE_FILE_MACHINE_ARM64: alt_machine = IMAGE_FILE_MACHINE_AMD64; break;
1039     }
1040     nt_header.FileHeader.Machine = alt_machine;
1041     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1042     ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
1043         "NtCreateSection error %08x\n", status );
1044 
1045     switch (orig_machine)
1046     {
1047     case IMAGE_FILE_MACHINE_I386:  alt_machine = IMAGE_FILE_MACHINE_AMD64; break;
1048     case IMAGE_FILE_MACHINE_AMD64: alt_machine = IMAGE_FILE_MACHINE_I386; break;
1049     case IMAGE_FILE_MACHINE_ARMNT: alt_machine = IMAGE_FILE_MACHINE_ARM64; break;
1050     case IMAGE_FILE_MACHINE_ARM64: alt_machine = IMAGE_FILE_MACHINE_ARMNT; break;
1051     }
1052     nt_header.FileHeader.Machine = alt_machine;
1053     status = map_image_section( &nt_header, &section, section_data, __LINE__ );
1054     ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(status == STATUS_SUCCESS), /* win2k */
1055                   "NtCreateSection error %08x\n", status );
1056 
1057     nt_header.FileHeader.Machine = orig_machine;
1058     nt_header.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
1059     nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = page_size;
1060     nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = sizeof(cor_header);
1061     section.SizeOfRawData = sizeof(cor_header);
1062 
1063     memset( &cor_header, 0, sizeof(cor_header) );
1064     cor_header.cb = sizeof(cor_header);
1065     cor_header.MajorRuntimeVersion = 2;
1066     cor_header.MinorRuntimeVersion = 4;
1067     cor_header.Flags = COMIMAGE_FLAGS_ILONLY;
1068     U(cor_header).EntryPointToken = 0xbeef;
1069     status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1070     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1071 
1072     cor_header.MinorRuntimeVersion = 5;
1073     status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1074     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1075 
1076     cor_header.MajorRuntimeVersion = 3;
1077     cor_header.MinorRuntimeVersion = 0;
1078     status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1079     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1080 
1081     cor_header.Flags = COMIMAGE_FLAGS_ILONLY | COMIMAGE_FLAGS_32BITREQUIRED;
1082     status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1083     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1084 
1085     cor_header.Flags = COMIMAGE_FLAGS_ILONLY | COMIMAGE_FLAGS_32BITPREFERRED;
1086     status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1087     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1088 
1089     cor_header.Flags = 0;
1090     status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1091     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1092 
1093     nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = 1;
1094     nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = 1;
1095     status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1096     ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1097 
1098     if (nt_header.OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
1099     {
1100         IMAGE_NT_HEADERS64 nt64;
1101 
1102         memset( &nt64, 0, sizeof(nt64) );
1103         nt64.Signature = IMAGE_NT_SIGNATURE;
1104         nt64.FileHeader.Machine = orig_machine;
1105         nt64.FileHeader.NumberOfSections = 1;
1106         nt64.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
1107         nt64.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL;
1108         nt64.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1109         nt64.OptionalHeader.MajorLinkerVersion = 1;
1110         nt64.OptionalHeader.SizeOfCode = 0x1000;
1111         nt64.OptionalHeader.AddressOfEntryPoint = 0x1000;
1112         nt64.OptionalHeader.ImageBase = 0x10000000;
1113         nt64.OptionalHeader.SectionAlignment = 0x1000;
1114         nt64.OptionalHeader.FileAlignment = 0x1000;
1115         nt64.OptionalHeader.MajorOperatingSystemVersion = 4;
1116         nt64.OptionalHeader.MajorImageVersion = 1;
1117         nt64.OptionalHeader.MajorSubsystemVersion = 4;
1118         nt64.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt64) + sizeof(IMAGE_SECTION_HEADER);
1119         nt64.OptionalHeader.SizeOfImage = nt64.OptionalHeader.SizeOfHeaders + 0x1000;
1120         nt64.OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
1121         nt64.OptionalHeader.SizeOfStackReserve = 0x321000;
1122         nt64.OptionalHeader.SizeOfStackCommit = 0x123000;
1123         section.Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE;
1124 
1125         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1126         ok( status == (is_wow64 ? STATUS_INVALID_IMAGE_FORMAT : STATUS_INVALID_IMAGE_WIN_64),
1127             "NtCreateSection error %08x\n", status );
1128 
1129         switch (orig_machine)
1130         {
1131         case IMAGE_FILE_MACHINE_I386: nt64.FileHeader.Machine = IMAGE_FILE_MACHINE_ARM64; break;
1132         case IMAGE_FILE_MACHINE_ARMNT: nt64.FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; break;
1133         }
1134         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1135         ok( status == (is_wow64 ? STATUS_INVALID_IMAGE_FORMAT : STATUS_INVALID_IMAGE_WIN_64),
1136             "NtCreateSection error %08x\n", status );
1137 
1138         nt64.FileHeader.Machine = alt_machine;
1139         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1140         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1141             "NtCreateSection error %08x\n", status );
1142 
1143         nt64.OptionalHeader.SizeOfCode = 0;
1144         nt64.OptionalHeader.AddressOfEntryPoint = 0x1000;
1145         section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE;
1146         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1147         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1148             "NtCreateSection error %08x\n", status );
1149 
1150         nt64.OptionalHeader.SizeOfCode = 0;
1151         nt64.OptionalHeader.AddressOfEntryPoint = 0;
1152         section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE;
1153         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1154         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1155             "NtCreateSection error %08x\n", status );
1156 
1157         nt64.OptionalHeader.SizeOfCode = 0x1000;
1158         nt64.OptionalHeader.AddressOfEntryPoint = 0;
1159         nt64.OptionalHeader.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
1160         section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE;
1161         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1162         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1163             "NtCreateSection error %08x\n", status );
1164 
1165         nt64.OptionalHeader.SizeOfCode = 0;
1166         nt64.OptionalHeader.AddressOfEntryPoint = 0;
1167         section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE;
1168         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1169         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1170             "NtCreateSection error %08x\n", status );
1171 
1172         nt64.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
1173         nt64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = page_size;
1174         nt64.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = sizeof(cor_header);
1175         cor_header.MajorRuntimeVersion = 2;
1176         cor_header.MinorRuntimeVersion = 4;
1177         cor_header.Flags = COMIMAGE_FLAGS_ILONLY;
1178         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1179         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1180             "NtCreateSection error %08x\n", status );
1181 
1182         nt64.OptionalHeader.SizeOfCode = 0x1000;
1183         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1184         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1185             "NtCreateSection error %08x\n", status );
1186 
1187         cor_header.MinorRuntimeVersion = 5;
1188         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1189         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1190             "NtCreateSection error %08x\n", status );
1191 
1192         cor_header.Flags = COMIMAGE_FLAGS_ILONLY | COMIMAGE_FLAGS_32BITREQUIRED;
1193         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1194         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1195             "NtCreateSection error %08x\n", status );
1196 
1197         cor_header.Flags = COMIMAGE_FLAGS_ILONLY | COMIMAGE_FLAGS_32BITPREFERRED;
1198         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1199         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1200             "NtCreateSection error %08x\n", status );
1201 
1202         cor_header.Flags = 0;
1203         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1204         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1205             "NtCreateSection error %08x\n", status );
1206 
1207         nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = 1;
1208         nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = 1;
1209         status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1210         ok( status == (is_wow64 ? STATUS_SUCCESS : STATUS_INVALID_IMAGE_WIN_64),
1211             "NtCreateSection error %08x\n", status );
1212     }
1213     else
1214     {
1215         IMAGE_NT_HEADERS32 nt32;
1216 
1217         memset( &nt32, 0, sizeof(nt32) );
1218         nt32.Signature = IMAGE_NT_SIGNATURE;
1219         nt32.FileHeader.Machine = orig_machine;
1220         nt32.FileHeader.NumberOfSections = 1;
1221         nt32.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER32);
1222         nt32.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL;
1223         nt32.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC;
1224         nt32.OptionalHeader.MajorLinkerVersion = 1;
1225         nt32.OptionalHeader.SizeOfCode = 0x1000;
1226         nt32.OptionalHeader.AddressOfEntryPoint = 0x1000;
1227         nt32.OptionalHeader.ImageBase = 0x10000000;
1228         nt32.OptionalHeader.SectionAlignment = 0x1000;
1229         nt32.OptionalHeader.FileAlignment = 0x1000;
1230         nt32.OptionalHeader.MajorOperatingSystemVersion = 4;
1231         nt32.OptionalHeader.MajorImageVersion = 1;
1232         nt32.OptionalHeader.MajorSubsystemVersion = 4;
1233         nt32.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt32) + sizeof(IMAGE_SECTION_HEADER);
1234         nt32.OptionalHeader.SizeOfImage = nt32.OptionalHeader.SizeOfHeaders + 0x1000;
1235         nt32.OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
1236         nt32.OptionalHeader.SizeOfStackReserve = 0x321000;
1237         nt32.OptionalHeader.SizeOfStackCommit = 0x123000;
1238         section.Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE;
1239 
1240         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, section_data, __LINE__ );
1241         ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
1242 
1243         switch (orig_machine)
1244         {
1245         case IMAGE_FILE_MACHINE_AMD64: nt32.FileHeader.Machine = IMAGE_FILE_MACHINE_ARMNT; break;
1246         case IMAGE_FILE_MACHINE_ARM64: nt32.FileHeader.Machine = IMAGE_FILE_MACHINE_I386; break;
1247         }
1248         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, section_data, __LINE__ );
1249         ok( status == STATUS_INVALID_IMAGE_FORMAT || broken(!status) /* win8 */,
1250             "NtCreateSection error %08x\n", status );
1251 
1252         nt32.FileHeader.Machine = alt_machine;
1253         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, section_data, __LINE__ );
1254         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1255 
1256         nt32.OptionalHeader.SizeOfCode = 0;
1257         nt32.OptionalHeader.AddressOfEntryPoint = 0x1000;
1258         section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE;
1259         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, section_data, __LINE__ );
1260         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1261 
1262         nt32.OptionalHeader.SizeOfCode = 0;
1263         nt32.OptionalHeader.AddressOfEntryPoint = 0;
1264         section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE;
1265         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, section_data, __LINE__ );
1266         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1267 
1268         nt32.OptionalHeader.SizeOfCode = 0x1000;
1269         nt32.OptionalHeader.AddressOfEntryPoint = 0;
1270         nt32.OptionalHeader.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
1271         section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE;
1272         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, section_data, __LINE__ );
1273         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1274 
1275         nt32.OptionalHeader.SizeOfCode = 0;
1276         nt32.OptionalHeader.AddressOfEntryPoint = 0;
1277         section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE;
1278         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, section_data, __LINE__ );
1279         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1280 
1281         nt32.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
1282         nt32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = page_size;
1283         nt32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = sizeof(cor_header);
1284         cor_header.MajorRuntimeVersion = 2;
1285         cor_header.MinorRuntimeVersion = 4;
1286         cor_header.Flags = COMIMAGE_FLAGS_ILONLY;
1287         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, &cor_header, __LINE__ );
1288         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1289 
1290         nt32.OptionalHeader.SizeOfCode = 0x1000;
1291         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, &cor_header, __LINE__ );
1292         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1293 
1294         cor_header.MinorRuntimeVersion = 5;
1295         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, &cor_header, __LINE__ );
1296         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1297 
1298         cor_header.Flags = COMIMAGE_FLAGS_ILONLY | COMIMAGE_FLAGS_32BITREQUIRED;
1299         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, &cor_header, __LINE__ );
1300         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1301 
1302         cor_header.Flags = COMIMAGE_FLAGS_ILONLY | COMIMAGE_FLAGS_32BITPREFERRED;
1303         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, &cor_header, __LINE__ );
1304         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1305 
1306         cor_header.Flags = 0;
1307         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, &cor_header, __LINE__ );
1308         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1309 
1310         nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress = 1;
1311         nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size = 1;
1312         status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, &cor_header, __LINE__ );
1313         ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1314     }
1315 
1316     section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
1317 }
1318 
test_filenames(void)1319 static void test_filenames(void)
1320 {
1321     IMAGE_NT_HEADERS nt_header = nt_header_template;
1322     char dll_name[MAX_PATH], long_path[MAX_PATH], short_path[MAX_PATH], buffer[MAX_PATH];
1323     HMODULE mod, mod2;
1324     BOOL ret;
1325 
1326     nt_header.FileHeader.NumberOfSections = 1;
1327     nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
1328 
1329     nt_header.OptionalHeader.SectionAlignment = page_size;
1330     nt_header.OptionalHeader.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
1331     nt_header.OptionalHeader.FileAlignment = page_size;
1332     nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
1333     nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + page_size;
1334 
1335     create_test_dll( &dos_header, sizeof(dos_header), &nt_header, dll_name );
1336     strcpy( long_path, dll_name );
1337     strcpy( strrchr( long_path, '\\' ), "\\this-is-a-long-name.dll" );
1338     ret = MoveFileA( dll_name, long_path );
1339     ok( ret, "MoveFileA failed err %u\n", GetLastError() );
1340     GetShortPathNameA( long_path, short_path, MAX_PATH );
1341 
1342     mod = LoadLibraryA( short_path );
1343     ok( mod != NULL, "loading failed err %u\n", GetLastError() );
1344     GetModuleFileNameA( mod, buffer, MAX_PATH );
1345     ok( !lstrcmpiA( buffer, short_path ), "got wrong path %s / %s\n", buffer, short_path );
1346     mod2 = GetModuleHandleA( short_path );
1347     ok( mod == mod2, "wrong module %p for %s\n", mod2, short_path );
1348     mod2 = GetModuleHandleA( long_path );
1349     ok( mod == mod2, "wrong module %p for %s\n", mod2, long_path );
1350     mod2 = LoadLibraryA( long_path );
1351     ok( mod2 != NULL, "loading failed err %u\n", GetLastError() );
1352     ok( mod == mod2, "library loaded twice\n" );
1353     GetModuleFileNameA( mod2, buffer, MAX_PATH );
1354     ok( !lstrcmpiA( buffer, short_path ), "got wrong path %s / %s\n", buffer, short_path );
1355     FreeLibrary( mod2 );
1356     FreeLibrary( mod );
1357 
1358     mod = LoadLibraryA( long_path );
1359     ok( mod != NULL, "loading failed err %u\n", GetLastError() );
1360     GetModuleFileNameA( mod, buffer, MAX_PATH );
1361     ok( !lstrcmpiA( buffer, long_path ), "got wrong path %s / %s\n", buffer, long_path );
1362     mod2 = GetModuleHandleA( short_path );
1363     ok( mod == mod2, "wrong module %p for %s\n", mod2, short_path );
1364     mod2 = GetModuleHandleA( long_path );
1365     ok( mod == mod2, "wrong module %p for %s\n", mod2, long_path );
1366     mod2 = LoadLibraryA( short_path );
1367     ok( mod2 != NULL, "loading failed err %u\n", GetLastError() );
1368     ok( mod == mod2, "library loaded twice\n" );
1369     GetModuleFileNameA( mod2, buffer, MAX_PATH );
1370     ok( !lstrcmpiA( buffer, long_path ), "got wrong path %s / %s\n", buffer, long_path );
1371     FreeLibrary( mod2 );
1372     FreeLibrary( mod );
1373 
1374     strcpy( dll_name, long_path );
1375     strcpy( strrchr( dll_name, '\\' ), "\\this-is-another-name.dll" );
1376     ret = CreateHardLinkA( dll_name, long_path, NULL );
1377     ok( ret, "CreateHardLinkA failed err %u\n", GetLastError() );
1378     if (ret)
1379     {
1380         mod = LoadLibraryA( dll_name );
1381         ok( mod != NULL, "loading failed err %u\n", GetLastError() );
1382         GetModuleFileNameA( mod, buffer, MAX_PATH );
1383         ok( !lstrcmpiA( buffer, dll_name ), "got wrong path %s / %s\n", buffer, dll_name );
1384         mod2 = GetModuleHandleA( long_path );
1385         ok( mod == mod2, "wrong module %p for %s\n", mod2, long_path );
1386         mod2 = LoadLibraryA( long_path );
1387         ok( mod2 != NULL, "loading failed err %u\n", GetLastError() );
1388         ok( mod == mod2, "library loaded twice\n" );
1389         GetModuleFileNameA( mod2, buffer, MAX_PATH );
1390         ok( !lstrcmpiA( buffer, dll_name ), "got wrong path %s / %s\n", buffer, short_path );
1391         FreeLibrary( mod2 );
1392         FreeLibrary( mod );
1393         DeleteFileA( dll_name );
1394     }
1395     DeleteFileA( long_path );
1396 }
1397 
test_FakeDLL(void)1398 static void test_FakeDLL(void)
1399 {
1400 #if defined(__i386__) || defined(__x86_64__)
1401     NTSTATUS (WINAPI *pNtSetEvent)(HANDLE, ULONG *) = NULL;
1402     IMAGE_EXPORT_DIRECTORY *dir;
1403     HMODULE module = GetModuleHandleA("ntdll.dll");
1404     HANDLE file, map, event;
1405     WCHAR path[MAX_PATH];
1406     DWORD *names, *funcs;
1407     WORD *ordinals;
1408     ULONG size;
1409     void *ptr;
1410     int i;
1411 
1412     GetModuleFileNameW(module, path, MAX_PATH);
1413 
1414     file = CreateFileW(path, GENERIC_READ | GENERIC_EXECUTE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1415     ok(file != INVALID_HANDLE_VALUE, "Failed to open %s (error %u)\n", wine_dbgstr_w(path), GetLastError());
1416 
1417     map = CreateFileMappingW(file, NULL, PAGE_EXECUTE_READ | SEC_IMAGE, 0, 0, NULL);
1418     ok(map != NULL, "CreateFileMapping failed with error %u\n", GetLastError());
1419     ptr = MapViewOfFile(map, FILE_MAP_READ | FILE_MAP_EXECUTE, 0, 0, 0);
1420     ok(ptr != NULL, "MapViewOfFile failed with error %u\n", GetLastError());
1421 
1422     dir = RtlImageDirectoryEntryToData(ptr, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size);
1423     ok(dir != NULL, "RtlImageDirectoryEntryToData failed\n");
1424 
1425     names    = RVAToAddr(dir->AddressOfNames, ptr);
1426     ordinals = RVAToAddr(dir->AddressOfNameOrdinals, ptr);
1427     funcs    = RVAToAddr(dir->AddressOfFunctions, ptr);
1428     ok(dir->NumberOfNames > 0, "Could not find any exported functions\n");
1429 
1430     for (i = 0; i < dir->NumberOfNames; i++)
1431     {
1432         DWORD map_rva, dll_rva, map_offset, dll_offset;
1433         char *func_name = RVAToAddr(names[i], ptr);
1434         BYTE *dll_func, *map_func;
1435 
1436         /* check only Nt functions for now */
1437         if (strncmp(func_name, "Zw", 2) && strncmp(func_name, "Nt", 2))
1438             continue;
1439 
1440         dll_func = (BYTE *)GetProcAddress(module, func_name);
1441         ok(dll_func != NULL, "%s: GetProcAddress returned NULL\n", func_name);
1442 #if defined(__i386__)
1443         if (dll_func[0] == 0x90 && dll_func[1] == 0x90 &&
1444             dll_func[2] == 0x90 && dll_func[3] == 0x90)
1445 #elif defined(__x86_64__)
1446         if (dll_func[0] == 0x48 && dll_func[1] == 0x83 &&
1447             dll_func[2] == 0xec && dll_func[3] == 0x08)
1448 #endif
1449         {
1450             todo_wine ok(0, "%s: Export is a stub-function, skipping\n", func_name);
1451             continue;
1452         }
1453 
1454         /* check position in memory */
1455         dll_rva = (DWORD_PTR)dll_func - (DWORD_PTR)module;
1456         map_rva = funcs[ordinals[i]];
1457         ok(map_rva == dll_rva, "%s: Rva of mapped function (0x%x) does not match dll (0x%x)\n",
1458            func_name, dll_rva, map_rva);
1459 
1460         /* check position in file */
1461         map_offset = (DWORD_PTR)RtlImageRvaToVa(RtlImageNtHeader(ptr),    ptr,    map_rva, NULL) - (DWORD_PTR)ptr;
1462         dll_offset = (DWORD_PTR)RtlImageRvaToVa(RtlImageNtHeader(module), module, dll_rva, NULL) - (DWORD_PTR)module;
1463         ok(map_offset == dll_offset, "%s: File offset of mapped function (0x%x) does not match dll (0x%x)\n",
1464            func_name, map_offset, dll_offset);
1465 
1466         /* check function content */
1467         map_func = RVAToAddr(map_rva, ptr);
1468         ok(!memcmp(map_func, dll_func, 0x20), "%s: Function content does not match!\n", func_name);
1469 
1470         if (!strcmp(func_name, "NtSetEvent"))
1471             pNtSetEvent = (void *)map_func;
1472     }
1473 
1474     ok(pNtSetEvent != NULL, "Could not find NtSetEvent export\n");
1475     if (pNtSetEvent)
1476     {
1477         event = CreateEventA(NULL, TRUE, FALSE, NULL);
1478         ok(event != NULL, "CreateEvent failed with error %u\n", GetLastError());
1479         pNtSetEvent(event, 0);
1480         ok(WaitForSingleObject(event, 0) == WAIT_OBJECT_0, "Event was not signaled\n");
1481         pNtSetEvent(event, 0);
1482         ok(WaitForSingleObject(event, 0) == WAIT_OBJECT_0, "Event was not signaled\n");
1483         CloseHandle(event);
1484     }
1485 
1486     UnmapViewOfFile(ptr);
1487     CloseHandle(map);
1488     CloseHandle(file);
1489 #endif
1490 }
1491 
1492 /* Verify linking style of import descriptors */
test_ImportDescriptors(void)1493 static void test_ImportDescriptors(void)
1494 {
1495     HMODULE kernel32_module = NULL;
1496     PIMAGE_DOS_HEADER d_header;
1497     PIMAGE_NT_HEADERS nt_headers;
1498     DWORD import_dir_size;
1499     DWORD_PTR dir_offset;
1500     PIMAGE_IMPORT_DESCRIPTOR import_chunk;
1501 
1502     /* Load kernel32 module */
1503     kernel32_module = GetModuleHandleA("kernel32.dll");
1504     assert( kernel32_module != NULL );
1505 
1506     /* Get PE header info from module image */
1507     d_header = (PIMAGE_DOS_HEADER) kernel32_module;
1508     nt_headers = (PIMAGE_NT_HEADERS) (((char*) d_header) +
1509             d_header->e_lfanew);
1510 
1511     /* Get size of import entry directory */
1512     import_dir_size = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size;
1513     if (!import_dir_size)
1514     {
1515         skip("Unable to continue testing due to missing import directory.\n");
1516         return;
1517     }
1518 
1519     /* Get address of first import chunk */
1520     dir_offset = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
1521     import_chunk = RVAToAddr(dir_offset, kernel32_module);
1522     ok(import_chunk != 0, "Invalid import_chunk: %p\n", import_chunk);
1523     if (!import_chunk) return;
1524 
1525     /* Iterate through import descriptors and verify set name,
1526      * OriginalFirstThunk, and FirstThunk.  Core Windows DLLs, such as
1527      * kernel32.dll, don't use Borland-style linking, where the table of
1528      * imported names is stored directly in FirstThunk and overwritten
1529      * by the relocation, instead of being stored in OriginalFirstThunk.
1530      * */
1531     for (; import_chunk->FirstThunk; import_chunk++)
1532     {
1533         LPCSTR module_name = RVAToAddr(import_chunk->Name, kernel32_module);
1534         PIMAGE_THUNK_DATA name_table = RVAToAddr(
1535                 U(*import_chunk).OriginalFirstThunk, kernel32_module);
1536         PIMAGE_THUNK_DATA iat = RVAToAddr(
1537                 import_chunk->FirstThunk, kernel32_module);
1538         ok(module_name != NULL, "Imported module name should not be NULL\n");
1539         ok(name_table != NULL,
1540                 "Name table for imported module %s should not be NULL\n",
1541                 module_name);
1542         ok(iat != NULL, "IAT for imported module %s should not be NULL\n",
1543                 module_name);
1544     }
1545 }
1546 
test_image_mapping(const char * dll_name,DWORD scn_page_access,BOOL is_dll)1547 static void test_image_mapping(const char *dll_name, DWORD scn_page_access, BOOL is_dll)
1548 {
1549     HANDLE hfile, hmap;
1550     NTSTATUS status;
1551     LARGE_INTEGER offset;
1552     SIZE_T size;
1553     void *addr1, *addr2;
1554     MEMORY_BASIC_INFORMATION info;
1555 
1556     if (!pNtMapViewOfSection) return;
1557 
1558     SetLastError(0xdeadbeef);
1559     hfile = CreateFileA(dll_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1560     ok(hfile != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
1561 
1562     SetLastError(0xdeadbeef);
1563     hmap = CreateFileMappingW(hfile, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, 0);
1564     ok(hmap != 0, "CreateFileMapping error %d\n", GetLastError());
1565 
1566     offset.u.LowPart  = 0;
1567     offset.u.HighPart = 0;
1568 
1569     addr1 = NULL;
1570     size = 0;
1571     status = pNtMapViewOfSection(hmap, GetCurrentProcess(), &addr1, 0, 0, &offset,
1572                                  &size, 1 /* ViewShare */, 0, PAGE_READONLY);
1573     ok(status == STATUS_SUCCESS, "NtMapViewOfSection error %x\n", status);
1574     ok(addr1 != 0, "mapped address should be valid\n");
1575 
1576     SetLastError(0xdeadbeef);
1577     size = VirtualQuery((char *)addr1 + section.VirtualAddress, &info, sizeof(info));
1578     ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
1579     ok(info.BaseAddress == (char *)addr1 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr1 + section.VirtualAddress);
1580     ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
1581     ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
1582     ok(info.AllocationBase == addr1, "%p != %p\n", info.AllocationBase, addr1);
1583     ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
1584     ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
1585     ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
1586 
1587     addr2 = NULL;
1588     size = 0;
1589     status = pNtMapViewOfSection(hmap, GetCurrentProcess(), &addr2, 0, 0, &offset,
1590                                  &size, 1 /* ViewShare */, 0, PAGE_READONLY);
1591     ok(status == STATUS_IMAGE_NOT_AT_BASE, "expected STATUS_IMAGE_NOT_AT_BASE, got %x\n", status);
1592     ok(addr2 != 0, "mapped address should be valid\n");
1593     ok(addr2 != addr1, "mapped addresses should be different\n");
1594 
1595     SetLastError(0xdeadbeef);
1596     size = VirtualQuery((char *)addr2 + section.VirtualAddress, &info, sizeof(info));
1597     ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
1598     ok(info.BaseAddress == (char *)addr2 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr2 + section.VirtualAddress);
1599     ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
1600     ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
1601     ok(info.AllocationBase == addr2, "%p != %p\n", info.AllocationBase, addr2);
1602     ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
1603     ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
1604     ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
1605 
1606     status = pNtUnmapViewOfSection(GetCurrentProcess(), addr2);
1607     ok(status == STATUS_SUCCESS, "NtUnmapViewOfSection error %x\n", status);
1608 
1609     addr2 = MapViewOfFile(hmap, 0, 0, 0, 0);
1610     ok(addr2 != 0, "mapped address should be valid\n");
1611     ok(addr2 != addr1, "mapped addresses should be different\n");
1612 
1613     SetLastError(0xdeadbeef);
1614     size = VirtualQuery((char *)addr2 + section.VirtualAddress, &info, sizeof(info));
1615     ok(size == sizeof(info), "VirtualQuery error %d\n", GetLastError());
1616     ok(info.BaseAddress == (char *)addr2 + section.VirtualAddress, "got %p != expected %p\n", info.BaseAddress, (char *)addr2 + section.VirtualAddress);
1617     ok(info.RegionSize == page_size, "got %#lx != expected %#x\n", info.RegionSize, page_size);
1618     ok(info.Protect == scn_page_access, "got %#x != expected %#x\n", info.Protect, scn_page_access);
1619     ok(info.AllocationBase == addr2, "%p != %p\n", info.AllocationBase, addr2);
1620     ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%#x != PAGE_EXECUTE_WRITECOPY\n", info.AllocationProtect);
1621     ok(info.State == MEM_COMMIT, "%#x != MEM_COMMIT\n", info.State);
1622     ok(info.Type == SEC_IMAGE, "%#x != SEC_IMAGE\n", info.Type);
1623 
1624     UnmapViewOfFile(addr2);
1625 
1626     SetLastError(0xdeadbeef);
1627     addr2 = LoadLibraryA(dll_name);
1628     if (is_dll)
1629     {
1630         ok(!addr2, "LoadLibrary should fail, is_dll %d\n", is_dll);
1631         ok(GetLastError() == ERROR_INVALID_ADDRESS, "expected ERROR_INVALID_ADDRESS, got %d\n", GetLastError());
1632     }
1633     else
1634     {
1635         BOOL ret;
1636         ok(addr2 != 0, "LoadLibrary error %d, is_dll %d\n", GetLastError(), is_dll);
1637         ok(addr2 != addr1, "mapped addresses should be different\n");
1638 
1639         SetLastError(0xdeadbeef);
1640         ret = FreeLibrary(addr2);
1641         ok(ret, "FreeLibrary error %d\n", GetLastError());
1642     }
1643 
1644     status = pNtUnmapViewOfSection(GetCurrentProcess(), addr1);
1645     ok(status == STATUS_SUCCESS, "NtUnmapViewOfSection error %x\n", status);
1646 
1647     CloseHandle(hmap);
1648     CloseHandle(hfile);
1649 }
1650 
is_mem_writable(DWORD prot)1651 static BOOL is_mem_writable(DWORD prot)
1652 {
1653     switch (prot & 0xff)
1654     {
1655         case PAGE_READWRITE:
1656         case PAGE_WRITECOPY:
1657         case PAGE_EXECUTE_READWRITE:
1658         case PAGE_EXECUTE_WRITECOPY:
1659             return TRUE;
1660 
1661         default:
1662             return FALSE;
1663     }
1664 }
1665 
test_VirtualProtect(void * base,void * section)1666 static void test_VirtualProtect(void *base, void *section)
1667 {
1668     static const struct test_data
1669     {
1670         DWORD prot_set, prot_get;
1671     } td[] =
1672     {
1673         { 0, 0 }, /* 0x00 */
1674         { PAGE_NOACCESS, PAGE_NOACCESS }, /* 0x01 */
1675         { PAGE_READONLY, PAGE_READONLY }, /* 0x02 */
1676         { PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x03 */
1677         { PAGE_READWRITE, PAGE_WRITECOPY }, /* 0x04 */
1678         { PAGE_READWRITE | PAGE_NOACCESS, 0 }, /* 0x05 */
1679         { PAGE_READWRITE | PAGE_READONLY, 0 }, /* 0x06 */
1680         { PAGE_READWRITE | PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x07 */
1681         { PAGE_WRITECOPY, PAGE_WRITECOPY }, /* 0x08 */
1682         { PAGE_WRITECOPY | PAGE_NOACCESS, 0 }, /* 0x09 */
1683         { PAGE_WRITECOPY | PAGE_READONLY, 0 }, /* 0x0a */
1684         { PAGE_WRITECOPY | PAGE_NOACCESS | PAGE_READONLY, 0 }, /* 0x0b */
1685         { PAGE_WRITECOPY | PAGE_READWRITE, 0 }, /* 0x0c */
1686         { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_NOACCESS, 0 }, /* 0x0d */
1687         { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_READONLY, 0 }, /* 0x0e */
1688         { PAGE_WRITECOPY | PAGE_READWRITE | PAGE_READONLY | PAGE_NOACCESS, 0 }, /* 0x0f */
1689 
1690         { PAGE_EXECUTE, PAGE_EXECUTE }, /* 0x10 */
1691         { PAGE_EXECUTE_READ, PAGE_EXECUTE_READ }, /* 0x20 */
1692         { PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0x30 */
1693         { PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY }, /* 0x40 */
1694         { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0x50 */
1695         { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0x60 */
1696         { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0x70 */
1697         { PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_WRITECOPY }, /* 0x80 */
1698         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE, 0 }, /* 0x90 */
1699         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ, 0 }, /* 0xa0 */
1700         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 }, /* 0xb0 */
1701         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE, 0 }, /* 0xc0 */
1702         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0xd0 */
1703         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0xe0 */
1704         { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE, 0 } /* 0xf0 */
1705     };
1706     DWORD ret, orig_prot, old_prot, rw_prot, exec_prot, i, j;
1707     MEMORY_BASIC_INFORMATION info;
1708 
1709     SetLastError(0xdeadbeef);
1710     ret = VirtualProtect(section, page_size, PAGE_NOACCESS, &old_prot);
1711     ok(ret, "VirtualProtect error %d\n", GetLastError());
1712 
1713     orig_prot = old_prot;
1714 
1715     for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
1716     {
1717         SetLastError(0xdeadbeef);
1718         ret = VirtualQuery(section, &info, sizeof(info));
1719         ok(ret, "VirtualQuery failed %d\n", GetLastError());
1720         ok(info.BaseAddress == section, "%d: got %p != expected %p\n", i, info.BaseAddress, section);
1721         ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
1722         ok(info.Protect == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, info.Protect);
1723         ok(info.AllocationBase == base, "%d: %p != %p\n", i, info.AllocationBase, base);
1724         ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1725         ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1726         ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1727 
1728         old_prot = 0xdeadbeef;
1729         SetLastError(0xdeadbeef);
1730         ret = VirtualProtect(section, page_size, td[i].prot_set, &old_prot);
1731         if (td[i].prot_get)
1732         {
1733             ok(ret, "%d: VirtualProtect error %d, requested prot %#x\n", i, GetLastError(), td[i].prot_set);
1734             ok(old_prot == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, old_prot);
1735 
1736             SetLastError(0xdeadbeef);
1737             ret = VirtualQuery(section, &info, sizeof(info));
1738             ok(ret, "VirtualQuery failed %d\n", GetLastError());
1739             ok(info.BaseAddress == section, "%d: got %p != expected %p\n", i, info.BaseAddress, section);
1740             ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
1741             ok(info.Protect == td[i].prot_get, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].prot_get);
1742             ok(info.AllocationBase == base, "%d: %p != %p\n", i, info.AllocationBase, base);
1743             ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1744             ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1745             ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1746         }
1747         else
1748         {
1749             ok(!ret, "%d: VirtualProtect should fail\n", i);
1750             ok(GetLastError() == ERROR_INVALID_PARAMETER, "%d: expected ERROR_INVALID_PARAMETER, got %d\n", i, GetLastError());
1751         }
1752 
1753         old_prot = 0xdeadbeef;
1754         SetLastError(0xdeadbeef);
1755         ret = VirtualProtect(section, page_size, PAGE_NOACCESS, &old_prot);
1756         ok(ret, "%d: VirtualProtect error %d\n", i, GetLastError());
1757         if (td[i].prot_get)
1758             ok(old_prot == td[i].prot_get, "%d: got %#x != expected %#x\n", i, old_prot, td[i].prot_get);
1759         else
1760             ok(old_prot == PAGE_NOACCESS, "%d: got %#x != expected PAGE_NOACCESS\n", i, old_prot);
1761     }
1762 
1763     exec_prot = 0;
1764 
1765     for (i = 0; i <= 4; i++)
1766     {
1767         rw_prot = 0;
1768 
1769         for (j = 0; j <= 4; j++)
1770         {
1771             DWORD prot = exec_prot | rw_prot;
1772 
1773             SetLastError(0xdeadbeef);
1774             ret = VirtualProtect(section, page_size, prot, &old_prot);
1775             if ((rw_prot && exec_prot) || (!rw_prot && !exec_prot))
1776             {
1777                 ok(!ret, "VirtualProtect(%02x) should fail\n", prot);
1778                 ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
1779             }
1780             else
1781                 ok(ret, "VirtualProtect(%02x) error %d\n", prot, GetLastError());
1782 
1783             rw_prot = 1 << j;
1784         }
1785 
1786         exec_prot = 1 << (i + 4);
1787     }
1788 
1789     SetLastError(0xdeadbeef);
1790     ret = VirtualProtect(section, page_size, orig_prot, &old_prot);
1791     ok(ret, "VirtualProtect error %d\n", GetLastError());
1792 }
1793 
test_section_access(void)1794 static void test_section_access(void)
1795 {
1796     static const struct test_data
1797     {
1798         DWORD scn_file_access, scn_page_access, scn_page_access_after_write;
1799     } td[] =
1800     {
1801         { 0, PAGE_NOACCESS, 0 },
1802         { IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1803         { IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1804         { IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1805         { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1806         { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ },
1807         { IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1808         { IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1809 
1810         { IMAGE_SCN_CNT_INITIALIZED_DATA, PAGE_NOACCESS, 0 },
1811         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1812         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1813         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1814         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1815         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ, 0 },
1816         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1817         { IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1818 
1819         { IMAGE_SCN_CNT_UNINITIALIZED_DATA, PAGE_NOACCESS, 0 },
1820         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ, PAGE_READONLY, 0 },
1821         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1822         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE, 0 },
1823         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READWRITE },
1824         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_READ, 0 },
1825         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE },
1826         { IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READWRITE }
1827     };
1828     char buf[256];
1829     int i;
1830     DWORD dummy, file_align;
1831     HANDLE hfile;
1832     HMODULE hlib;
1833     char temp_path[MAX_PATH];
1834     char dll_name[MAX_PATH];
1835     SIZE_T size;
1836     MEMORY_BASIC_INFORMATION info;
1837     STARTUPINFOA sti;
1838     PROCESS_INFORMATION pi;
1839     DWORD ret;
1840 
1841     /* prevent displaying of the "Unable to load this DLL" message box */
1842     SetErrorMode(SEM_FAILCRITICALERRORS);
1843 
1844     GetTempPathA(MAX_PATH, temp_path);
1845 
1846     for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
1847     {
1848         IMAGE_NT_HEADERS nt_header;
1849 
1850         GetTempFileNameA(temp_path, "ldr", 0, dll_name);
1851 
1852         /*trace("creating %s\n", dll_name);*/
1853         hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
1854         if (hfile == INVALID_HANDLE_VALUE)
1855         {
1856             ok(0, "could not create %s\n", dll_name);
1857             return;
1858         }
1859 
1860         SetLastError(0xdeadbeef);
1861         ret = WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
1862         ok(ret, "WriteFile error %d\n", GetLastError());
1863 
1864         nt_header = nt_header_template;
1865         nt_header.FileHeader.NumberOfSections = 1;
1866         nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
1867         nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_RELOCS_STRIPPED;
1868 
1869         nt_header.OptionalHeader.SectionAlignment = page_size;
1870         nt_header.OptionalHeader.FileAlignment = 0x200;
1871         nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + page_size;
1872         nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
1873         SetLastError(0xdeadbeef);
1874         ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
1875         ok(ret, "WriteFile error %d\n", GetLastError());
1876         SetLastError(0xdeadbeef);
1877         ret = WriteFile(hfile, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
1878         ok(ret, "WriteFile error %d\n", GetLastError());
1879 
1880         section.SizeOfRawData = sizeof(section_data);
1881         section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
1882         section.VirtualAddress = nt_header.OptionalHeader.SectionAlignment;
1883         section.Misc.VirtualSize = section.SizeOfRawData;
1884         section.Characteristics = td[i].scn_file_access;
1885         SetLastError(0xdeadbeef);
1886         ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
1887         ok(ret, "WriteFile error %d\n", GetLastError());
1888 
1889         file_align = nt_header.OptionalHeader.FileAlignment - nt_header.OptionalHeader.SizeOfHeaders;
1890         assert(file_align < sizeof(filler));
1891         SetLastError(0xdeadbeef);
1892         ret = WriteFile(hfile, filler, file_align, &dummy, NULL);
1893         ok(ret, "WriteFile error %d\n", GetLastError());
1894 
1895         /* section data */
1896         SetLastError(0xdeadbeef);
1897         ret = WriteFile(hfile, section_data, sizeof(section_data), &dummy, NULL);
1898         ok(ret, "WriteFile error %d\n", GetLastError());
1899 
1900         CloseHandle(hfile);
1901 
1902         SetLastError(0xdeadbeef);
1903         hlib = LoadLibraryA(dll_name);
1904         ok(hlib != 0, "LoadLibrary error %d\n", GetLastError());
1905 
1906         SetLastError(0xdeadbeef);
1907         size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
1908         ok(size == sizeof(info),
1909             "%d: VirtualQuery error %d\n", i, GetLastError());
1910         ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
1911         ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
1912         ok(info.Protect == td[i].scn_page_access, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access);
1913         ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
1914         ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1915         ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1916         ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1917         if (info.Protect != PAGE_NOACCESS)
1918             ok(!memcmp((const char *)info.BaseAddress, section_data, section.SizeOfRawData), "wrong section data\n");
1919 
1920         test_VirtualProtect(hlib, (char *)hlib + section.VirtualAddress);
1921 
1922         /* Windows changes the WRITECOPY to WRITE protection on an image section write (for a changed page only) */
1923         if (is_mem_writable(info.Protect))
1924         {
1925             char *p = info.BaseAddress;
1926             *p = 0xfe;
1927             SetLastError(0xdeadbeef);
1928             size = VirtualQuery((char *)hlib + section.VirtualAddress, &info, sizeof(info));
1929             ok(size == sizeof(info), "%d: VirtualQuery error %d\n", i, GetLastError());
1930             /* FIXME: remove the condition below once Wine is fixed */
1931             todo_wine_if (info.Protect == PAGE_WRITECOPY || info.Protect == PAGE_EXECUTE_WRITECOPY)
1932                 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);
1933         }
1934 
1935         SetLastError(0xdeadbeef);
1936         ret = FreeLibrary(hlib);
1937         ok(ret, "FreeLibrary error %d\n", GetLastError());
1938 
1939         test_image_mapping(dll_name, td[i].scn_page_access, TRUE);
1940 
1941         /* reset IMAGE_FILE_DLL otherwise CreateProcess fails */
1942         nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_RELOCS_STRIPPED;
1943         SetLastError(0xdeadbeef);
1944         hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1945         /* LoadLibrary called on an already memory-mapped file in
1946          * test_image_mapping() above leads to a file handle leak
1947          * under nt4, and inability to overwrite and delete the file
1948          * due to sharing violation error. Ignore it and skip the test,
1949          * but leave a not deletable temporary file.
1950          */
1951         ok(hfile != INVALID_HANDLE_VALUE || broken(hfile == INVALID_HANDLE_VALUE) /* nt4 */,
1952             "CreateFile error %d\n", GetLastError());
1953         if (hfile == INVALID_HANDLE_VALUE) goto nt4_is_broken;
1954         SetFilePointer(hfile, sizeof(dos_header), NULL, FILE_BEGIN);
1955         SetLastError(0xdeadbeef);
1956         ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
1957         ok(ret, "WriteFile error %d\n", GetLastError());
1958         CloseHandle(hfile);
1959 
1960         memset(&sti, 0, sizeof(sti));
1961         sti.cb = sizeof(sti);
1962         SetLastError(0xdeadbeef);
1963         ret = CreateProcessA(dll_name, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &sti, &pi);
1964         ok(ret, "CreateProcess() error %d\n", GetLastError());
1965 
1966         SetLastError(0xdeadbeef);
1967         size = VirtualQueryEx(pi.hProcess, (char *)hlib + section.VirtualAddress, &info, sizeof(info));
1968         ok(size == sizeof(info),
1969             "%d: VirtualQuery error %d\n", i, GetLastError());
1970         ok(info.BaseAddress == (char *)hlib + section.VirtualAddress, "%d: got %p != expected %p\n", i, info.BaseAddress, (char *)hlib + section.VirtualAddress);
1971         ok(info.RegionSize == page_size, "%d: got %#lx != expected %#x\n", i, info.RegionSize, page_size);
1972         ok(info.Protect == td[i].scn_page_access, "%d: got %#x != expected %#x\n", i, info.Protect, td[i].scn_page_access);
1973         ok(info.AllocationBase == hlib, "%d: %p != %p\n", i, info.AllocationBase, hlib);
1974         ok(info.AllocationProtect == PAGE_EXECUTE_WRITECOPY, "%d: %#x != PAGE_EXECUTE_WRITECOPY\n", i, info.AllocationProtect);
1975         ok(info.State == MEM_COMMIT, "%d: %#x != MEM_COMMIT\n", i, info.State);
1976         ok(info.Type == SEC_IMAGE, "%d: %#x != SEC_IMAGE\n", i, info.Type);
1977         if (info.Protect != PAGE_NOACCESS)
1978         {
1979             SetLastError(0xdeadbeef);
1980             ret = ReadProcessMemory(pi.hProcess, info.BaseAddress, buf, section.SizeOfRawData, NULL);
1981             ok(ret, "ReadProcessMemory() error %d\n", GetLastError());
1982             ok(!memcmp(buf, section_data, section.SizeOfRawData), "wrong section data\n");
1983         }
1984 
1985         SetLastError(0xdeadbeef);
1986         ret = TerminateProcess(pi.hProcess, 0);
1987         ok(ret, "TerminateProcess() error %d\n", GetLastError());
1988         ret = WaitForSingleObject(pi.hProcess, 3000);
1989         ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
1990 
1991         CloseHandle(pi.hThread);
1992         CloseHandle(pi.hProcess);
1993 
1994         test_image_mapping(dll_name, td[i].scn_page_access, FALSE);
1995 
1996 nt4_is_broken:
1997         SetLastError(0xdeadbeef);
1998         ret = DeleteFileA(dll_name);
1999         ok(ret || broken(!ret) /* nt4 */, "DeleteFile error %d\n", GetLastError());
2000     }
2001 }
2002 
test_import_resolution(void)2003 static void test_import_resolution(void)
2004 {
2005     char temp_path[MAX_PATH];
2006     char dll_name[MAX_PATH];
2007     DWORD dummy;
2008     void *expect;
2009     char *str;
2010     HANDLE hfile;
2011     HMODULE mod, mod2;
2012     struct imports
2013     {
2014         IMAGE_IMPORT_DESCRIPTOR descr[2];
2015         IMAGE_THUNK_DATA original_thunks[2];
2016         IMAGE_THUNK_DATA thunks[2];
2017         char module[16];
2018         struct { WORD hint; char name[32]; } function;
2019         IMAGE_TLS_DIRECTORY tls;
2020         char tls_data[16];
2021         SHORT tls_index;
2022     } data, *ptr;
2023     IMAGE_NT_HEADERS nt;
2024     IMAGE_SECTION_HEADER section;
2025     int test;
2026 
2027     for (test = 0; test < 3; test++)
2028     {
2029 #define DATA_RVA(ptr) (page_size + ((char *)(ptr) - (char *)&data))
2030         nt = nt_header_template;
2031         nt.FileHeader.NumberOfSections = 1;
2032         nt.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
2033         nt.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_RELOCS_STRIPPED;
2034         if (test != 2) nt.FileHeader.Characteristics |= IMAGE_FILE_DLL;
2035         nt.OptionalHeader.SectionAlignment = page_size;
2036         nt.OptionalHeader.FileAlignment = 0x200;
2037         nt.OptionalHeader.ImageBase = 0x12340000;
2038         nt.OptionalHeader.SizeOfImage = 2 * page_size;
2039         nt.OptionalHeader.SizeOfHeaders = nt.OptionalHeader.FileAlignment;
2040         nt.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
2041         memset( nt.OptionalHeader.DataDirectory, 0, sizeof(nt.OptionalHeader.DataDirectory) );
2042         nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = sizeof(data.descr);
2043         nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = DATA_RVA(data.descr);
2044         nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size = sizeof(data.tls);
2045         nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress = DATA_RVA(&data.tls);
2046 
2047         memset( &data, 0, sizeof(data) );
2048         U(data.descr[0]).OriginalFirstThunk = DATA_RVA( data.original_thunks );
2049         data.descr[0].FirstThunk = DATA_RVA( data.thunks );
2050         data.descr[0].Name = DATA_RVA( data.module );
2051         strcpy( data.module, "kernel32.dll" );
2052         strcpy( data.function.name, "CreateEventA" );
2053         data.original_thunks[0].u1.AddressOfData = DATA_RVA( &data.function );
2054         data.thunks[0].u1.AddressOfData = 0xdeadbeef;
2055 
2056         data.tls.StartAddressOfRawData = nt.OptionalHeader.ImageBase + DATA_RVA( data.tls_data );
2057         data.tls.EndAddressOfRawData = data.tls.StartAddressOfRawData + sizeof(data.tls_data);
2058         data.tls.AddressOfIndex = nt.OptionalHeader.ImageBase + DATA_RVA( &data.tls_index );
2059         strcpy( data.tls_data, "hello world" );
2060         data.tls_index = 9999;
2061 
2062         GetTempPathA(MAX_PATH, temp_path);
2063         GetTempFileNameA(temp_path, "ldr", 0, dll_name);
2064 
2065         hfile = CreateFileA(dll_name, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, 0);
2066         ok( hfile != INVALID_HANDLE_VALUE, "creation failed\n" );
2067 
2068         memset( &section, 0, sizeof(section) );
2069         memcpy( section.Name, ".text", sizeof(".text") );
2070         section.PointerToRawData = nt.OptionalHeader.FileAlignment;
2071         section.VirtualAddress = nt.OptionalHeader.SectionAlignment;
2072         section.Misc.VirtualSize = sizeof(data);
2073         section.SizeOfRawData = sizeof(data);
2074         section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
2075 
2076         WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
2077         WriteFile(hfile, &nt, sizeof(nt), &dummy, NULL);
2078         WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
2079 
2080         SetFilePointer( hfile, section.PointerToRawData, NULL, SEEK_SET );
2081         WriteFile(hfile, &data, sizeof(data), &dummy, NULL);
2082 
2083         CloseHandle( hfile );
2084 
2085         switch (test)
2086         {
2087         case 0:  /* normal load */
2088             mod = LoadLibraryA( dll_name );
2089             ok( mod != NULL, "failed to load err %u\n", GetLastError() );
2090             if (!mod) break;
2091             ptr = (struct imports *)((char *)mod + page_size);
2092             expect = GetProcAddress( GetModuleHandleA( data.module ), data.function.name );
2093             ok( (void *)ptr->thunks[0].u1.Function == expect, "thunk %p instead of %p for %s.%s\n",
2094                 (void *)ptr->thunks[0].u1.Function, expect, data.module, data.function.name );
2095             ok( ptr->tls_index < 32 || broken(ptr->tls_index == 9999), /* before vista */
2096                 "wrong tls index %d\n", ptr->tls_index );
2097             if (ptr->tls_index != 9999)
2098             {
2099                 str = ((char **)NtCurrentTeb()->ThreadLocalStoragePointer)[ptr->tls_index];
2100                 ok( !strcmp( str, "hello world" ), "wrong tls data '%s' at %p\n", str, str );
2101             }
2102             FreeLibrary( mod );
2103             break;
2104         case 1:  /* load with DONT_RESOLVE_DLL_REFERENCES doesn't resolve imports */
2105             mod = LoadLibraryExA( dll_name, 0, DONT_RESOLVE_DLL_REFERENCES );
2106             ok( mod != NULL, "failed to load err %u\n", GetLastError() );
2107             if (!mod) break;
2108             ptr = (struct imports *)((char *)mod + page_size);
2109             ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
2110                 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
2111             ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
2112 
2113             mod2 = LoadLibraryA( dll_name );
2114             ok( mod2 == mod, "loaded twice %p / %p\n", mod, mod2 );
2115             ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
2116                 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
2117             ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
2118             FreeLibrary( mod2 );
2119             FreeLibrary( mod );
2120             break;
2121         case 2:  /* load without IMAGE_FILE_DLL doesn't resolve imports */
2122             mod = LoadLibraryA( dll_name );
2123             ok( mod != NULL, "failed to load err %u\n", GetLastError() );
2124             if (!mod) break;
2125             ptr = (struct imports *)((char *)mod + page_size);
2126             ok( ptr->thunks[0].u1.Function == 0xdeadbeef, "thunk resolved to %p for %s.%s\n",
2127                 (void *)ptr->thunks[0].u1.Function, data.module, data.function.name );
2128             ok( ptr->tls_index == 9999, "wrong tls index %d\n", ptr->tls_index );
2129             FreeLibrary( mod );
2130             break;
2131         }
2132         DeleteFileA( dll_name );
2133 #undef DATA_RVA
2134     }
2135 }
2136 
2137 #define MAX_COUNT 10
2138 static HANDLE attached_thread[MAX_COUNT];
2139 static DWORD attached_thread_count;
2140 HANDLE stop_event, event, mutex, semaphore, loader_lock_event, peb_lock_event, heap_lock_event, ack_event;
2141 static int test_dll_phase, inside_loader_lock, inside_peb_lock, inside_heap_lock;
2142 static LONG fls_callback_count;
2143 
mutex_thread_proc(void * param)2144 static DWORD WINAPI mutex_thread_proc(void *param)
2145 {
2146     HANDLE wait_list[4];
2147     DWORD ret;
2148 
2149     ret = WaitForSingleObject(mutex, 0);
2150     ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2151 
2152     SetEvent(param);
2153 
2154     wait_list[0] = stop_event;
2155     wait_list[1] = loader_lock_event;
2156     wait_list[2] = peb_lock_event;
2157     wait_list[3] = heap_lock_event;
2158 
2159     trace("%04x: mutex_thread_proc: starting\n", GetCurrentThreadId());
2160     while (1)
2161     {
2162         ret = WaitForMultipleObjects(sizeof(wait_list)/sizeof(wait_list[0]), wait_list, FALSE, 50);
2163         if (ret == WAIT_OBJECT_0) break;
2164         else if (ret == WAIT_OBJECT_0 + 1)
2165         {
2166             ULONG_PTR loader_lock_magic;
2167             trace("%04x: mutex_thread_proc: Entering loader lock\n", GetCurrentThreadId());
2168             ret = pLdrLockLoaderLock(0, NULL, &loader_lock_magic);
2169             ok(!ret, "LdrLockLoaderLock error %#x\n", ret);
2170             inside_loader_lock++;
2171             SetEvent(ack_event);
2172         }
2173         else if (ret == WAIT_OBJECT_0 + 2)
2174         {
2175             trace("%04x: mutex_thread_proc: Entering PEB lock\n", GetCurrentThreadId());
2176             pRtlAcquirePebLock();
2177             inside_peb_lock++;
2178             SetEvent(ack_event);
2179         }
2180         else if (ret == WAIT_OBJECT_0 + 3)
2181         {
2182             trace("%04x: mutex_thread_proc: Entering heap lock\n", GetCurrentThreadId());
2183             HeapLock(GetProcessHeap());
2184             inside_heap_lock++;
2185             SetEvent(ack_event);
2186         }
2187     }
2188 
2189     trace("%04x: mutex_thread_proc: exiting\n", GetCurrentThreadId());
2190     return 196;
2191 }
2192 
semaphore_thread_proc(void * param)2193 static DWORD WINAPI semaphore_thread_proc(void *param)
2194 {
2195     DWORD ret;
2196 
2197     ret = WaitForSingleObject(semaphore, 0);
2198     ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2199 
2200     SetEvent(param);
2201 
2202     while (1)
2203     {
2204         if (winetest_debug > 1)
2205             trace("%04x: semaphore_thread_proc: still alive\n", GetCurrentThreadId());
2206         if (WaitForSingleObject(stop_event, 50) != WAIT_TIMEOUT) break;
2207     }
2208 
2209     trace("%04x: semaphore_thread_proc: exiting\n", GetCurrentThreadId());
2210     return 196;
2211 }
2212 
noop_thread_proc(void * param)2213 static DWORD WINAPI noop_thread_proc(void *param)
2214 {
2215     if (param)
2216     {
2217         LONG *noop_thread_started = param;
2218         InterlockedIncrement(noop_thread_started);
2219     }
2220 
2221     trace("%04x: noop_thread_proc: exiting\n", GetCurrentThreadId());
2222     return 195;
2223 }
2224 
fls_callback(PVOID lpFlsData)2225 static VOID WINAPI fls_callback(PVOID lpFlsData)
2226 {
2227     ok(lpFlsData == (void*) 0x31415, "lpFlsData is %p, expected %p\n", lpFlsData, (void*) 0x31415);
2228     InterlockedIncrement(&fls_callback_count);
2229 }
2230 
dll_entry_point(HINSTANCE hinst,DWORD reason,LPVOID param)2231 static BOOL WINAPI dll_entry_point(HINSTANCE hinst, DWORD reason, LPVOID param)
2232 {
2233     static LONG noop_thread_started;
2234     static DWORD fls_index = FLS_OUT_OF_INDEXES;
2235     static int fls_count = 0;
2236     static int thread_detach_count = 0;
2237     DWORD ret;
2238 
2239     ok(!inside_loader_lock, "inside_loader_lock should not be set\n");
2240     ok(!inside_peb_lock, "inside_peb_lock should not be set\n");
2241 
2242     switch (reason)
2243     {
2244     case DLL_PROCESS_ATTACH:
2245         trace("dll: %p, DLL_PROCESS_ATTACH, %p\n", hinst, param);
2246 
2247         ret = pRtlDllShutdownInProgress();
2248         ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2249 
2250         /* Set up the FLS slot, if FLS is available */
2251         if (pFlsGetValue)
2252         {
2253             void* value;
2254             BOOL bret;
2255             ret = pFlsAlloc(&fls_callback);
2256             ok(ret != FLS_OUT_OF_INDEXES, "FlsAlloc returned %d\n", ret);
2257             fls_index = ret;
2258             SetLastError(0xdeadbeef);
2259             value = pFlsGetValue(fls_index);
2260             ok(!value, "FlsGetValue returned %p, expected NULL\n", value);
2261             ok(GetLastError() == ERROR_SUCCESS, "FlsGetValue failed with error %u\n", GetLastError());
2262             bret = pFlsSetValue(fls_index, (void*) 0x31415);
2263             ok(bret, "FlsSetValue failed\n");
2264             fls_count++;
2265         }
2266 
2267         break;
2268     case DLL_PROCESS_DETACH:
2269     {
2270         DWORD code, expected_code, i;
2271         HANDLE handle, process;
2272         void *addr;
2273         SIZE_T size;
2274         LARGE_INTEGER offset;
2275         DEBUG_EVENT de;
2276 
2277         trace("dll: %p, DLL_PROCESS_DETACH, %p\n", hinst, param);
2278 
2279         if (test_dll_phase == 4 || test_dll_phase == 5)
2280         {
2281             ok(0, "dll_entry_point(DLL_PROCESS_DETACH) should not be called\n");
2282             break;
2283         }
2284 
2285         /* The process should already deadlock at this point */
2286         if (test_dll_phase == 6)
2287         {
2288             /* In reality, code below never gets executed, probably some other
2289              * code tries to access process heap and deadlocks earlier, even XP
2290              * doesn't call the DLL entry point on process detach either.
2291              */
2292             HeapLock(GetProcessHeap());
2293             ok(0, "dll_entry_point: process should already deadlock\n");
2294             break;
2295         }
2296 
2297         if (test_dll_phase == 0 || test_dll_phase == 1 || test_dll_phase == 3)
2298             ok(param != NULL, "dll: param %p\n", param);
2299         else
2300             ok(!param, "dll: param %p\n", param);
2301 
2302         if (test_dll_phase == 0 || test_dll_phase == 1) expected_code = 195;
2303         else if (test_dll_phase == 3) expected_code = 196;
2304         else expected_code = STILL_ACTIVE;
2305 
2306         if (test_dll_phase == 3)
2307         {
2308             ret = pRtlDllShutdownInProgress();
2309             ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
2310         }
2311         else
2312         {
2313             ret = pRtlDllShutdownInProgress();
2314 
2315             /* FIXME: remove once Wine is fixed */
2316             todo_wine_if (!(expected_code == STILL_ACTIVE || expected_code == 196))
2317                 ok(!ret || broken(ret) /* before Vista */, "RtlDllShutdownInProgress returned %d\n", ret);
2318         }
2319 
2320         /* In the case that the process is terminating, FLS slots should still be accessible, but
2321          * the callback should be already run for this thread and the contents already NULL.
2322          * Note that this is broken for Win2k3, which runs the callbacks *after* the DLL entry
2323          * point has already run.
2324          */
2325         if (param && pFlsGetValue)
2326         {
2327             void* value;
2328             SetLastError(0xdeadbeef);
2329             value = pFlsGetValue(fls_index);
2330             todo_wine
2331             {
2332                 ok(broken(value == (void*) 0x31415) || /* Win2k3 */
2333                    value == NULL, "FlsGetValue returned %p, expected NULL\n", value);
2334             }
2335             ok(GetLastError() == ERROR_SUCCESS, "FlsGetValue failed with error %u\n", GetLastError());
2336             todo_wine
2337             {
2338                 ok(broken(fls_callback_count == thread_detach_count) || /* Win2k3 */
2339                    fls_callback_count == thread_detach_count + 1,
2340                    "wrong FLS callback count %d, expected %d\n", fls_callback_count, thread_detach_count + 1);
2341             }
2342         }
2343         if (pFlsFree)
2344         {
2345             BOOL ret;
2346             /* Call FlsFree now and run the remaining callbacks from uncleanly terminated threads */
2347             ret = pFlsFree(fls_index);
2348             ok(ret, "FlsFree failed with error %u\n", GetLastError());
2349             fls_index = FLS_OUT_OF_INDEXES;
2350             todo_wine
2351             {
2352                 ok(fls_callback_count == fls_count,
2353                    "wrong FLS callback count %d, expected %d\n", fls_callback_count, fls_count);
2354             }
2355         }
2356 
2357         ok(attached_thread_count >= 2, "attached thread count should be >= 2\n");
2358 
2359         for (i = 0; i < attached_thread_count; i++)
2360         {
2361             /* Calling GetExitCodeThread() without waiting for thread termination
2362              * leads to different results due to a race condition.
2363              */
2364             if (expected_code != STILL_ACTIVE)
2365             {
2366                 ret = WaitForSingleObject(attached_thread[i], 1000);
2367                 ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2368             }
2369             ret = GetExitCodeThread(attached_thread[i], &code);
2370             trace("dll: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
2371             ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
2372             ok(code == expected_code, "expected thread exit code %u, got %u\n", expected_code, code);
2373         }
2374 
2375         ret = WaitForSingleObject(event, 0);
2376         ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2377 
2378         ret = WaitForSingleObject(mutex, 0);
2379         if (expected_code == STILL_ACTIVE)
2380             ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2381         else
2382             ok(ret == WAIT_ABANDONED, "expected WAIT_ABANDONED, got %#x\n", ret);
2383 
2384         /* semaphore is not abandoned on thread termination */
2385         ret = WaitForSingleObject(semaphore, 0);
2386         ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2387 
2388         if (expected_code == STILL_ACTIVE)
2389         {
2390             ret = WaitForSingleObject(attached_thread[0], 0);
2391             ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2392             ret = WaitForSingleObject(attached_thread[1], 0);
2393             ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2394         }
2395         else
2396         {
2397             ret = WaitForSingleObject(attached_thread[0], 0);
2398             ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2399             ret = WaitForSingleObject(attached_thread[1], 0);
2400             ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2401         }
2402 
2403         /* win7 doesn't allow creating a thread during process shutdown but
2404          * earlier Windows versions allow it.
2405          */
2406         noop_thread_started = 0;
2407         SetLastError(0xdeadbeef);
2408         handle = CreateThread(NULL, 0, noop_thread_proc, &noop_thread_started, 0, &ret);
2409         if (param)
2410         {
2411             ok(!handle || broken(handle != 0) /* before win7 */, "CreateThread should fail\n");
2412             if (!handle)
2413                 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2414             else
2415             {
2416                 ret = WaitForSingleObject(handle, 1000);
2417                 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2418                 CloseHandle(handle);
2419             }
2420         }
2421         else
2422         {
2423             ok(handle != 0, "CreateThread error %d\n", GetLastError());
2424             ret = WaitForSingleObject(handle, 1000);
2425             ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2426             ok(!noop_thread_started || broken(noop_thread_started) /* XP64 */, "thread shouldn't start yet\n");
2427             CloseHandle(handle);
2428         }
2429 
2430         SetLastError(0xdeadbeef);
2431         process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, GetCurrentProcessId());
2432         ok(process != NULL, "OpenProcess error %d\n", GetLastError());
2433 
2434         noop_thread_started = 0;
2435         SetLastError(0xdeadbeef);
2436         handle = CreateRemoteThread(process, NULL, 0, noop_thread_proc, &noop_thread_started, 0, &ret);
2437         if (param)
2438         {
2439             ok(!handle || broken(handle != 0) /* before win7 */, "CreateRemoteThread should fail\n");
2440             if (!handle)
2441                 ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2442             else
2443             {
2444                 ret = WaitForSingleObject(handle, 1000);
2445                 ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2446                 CloseHandle(handle);
2447             }
2448         }
2449         else
2450         {
2451             ok(handle != 0, "CreateRemoteThread error %d\n", GetLastError());
2452             ret = WaitForSingleObject(handle, 1000);
2453             ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2454             ok(!noop_thread_started || broken(noop_thread_started) /* XP64 */, "thread shouldn't start yet\n");
2455             CloseHandle(handle);
2456         }
2457 
2458         SetLastError(0xdeadbeef);
2459         handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, NULL);
2460         ok(handle != 0, "CreateFileMapping error %d\n", GetLastError());
2461 
2462         offset.u.LowPart = 0;
2463         offset.u.HighPart = 0;
2464         addr = NULL;
2465         size = 0;
2466         ret = pNtMapViewOfSection(handle, process, &addr, 0, 0, &offset,
2467                                   &size, 1 /* ViewShare */, 0, PAGE_READONLY);
2468         ok(ret == STATUS_SUCCESS, "NtMapViewOfSection error %#x\n", ret);
2469         ret = pNtUnmapViewOfSection(process, addr);
2470         ok(ret == STATUS_SUCCESS, "NtUnmapViewOfSection error %#x\n", ret);
2471 
2472         CloseHandle(handle);
2473         CloseHandle(process);
2474 
2475         handle = GetModuleHandleA("winver.exe");
2476         ok(!handle, "winver.exe shouldn't be loaded yet\n");
2477         SetLastError(0xdeadbeef);
2478         handle = LoadLibraryA("winver.exe");
2479         ok(handle != 0, "LoadLibrary error %d\n", GetLastError());
2480         SetLastError(0xdeadbeef);
2481         ret = FreeLibrary(handle);
2482         ok(ret, "FreeLibrary error %d\n", GetLastError());
2483         handle = GetModuleHandleA("winver.exe");
2484         if (param)
2485             ok(handle != 0, "winver.exe should not be unloaded\n");
2486         else
2487         todo_wine
2488             ok(!handle || broken(handle != 0) /* before win7 */, "winver.exe should be unloaded\n");
2489 
2490         SetLastError(0xdeadbeef);
2491         ret = WaitForDebugEvent(&de, 0);
2492         ok(!ret, "WaitForDebugEvent should fail\n");
2493 todo_wine
2494         ok(GetLastError() == ERROR_INVALID_HANDLE, "expected ERROR_INVALID_HANDLE, got %d\n", GetLastError());
2495 
2496         SetLastError(0xdeadbeef);
2497         ret = DebugActiveProcess(GetCurrentProcessId());
2498         ok(!ret, "DebugActiveProcess should fail\n");
2499         ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2500 
2501         SetLastError(0xdeadbeef);
2502         ret = WaitForDebugEvent(&de, 0);
2503         ok(!ret, "WaitForDebugEvent should fail\n");
2504         ok(GetLastError() == ERROR_SEM_TIMEOUT, "expected ERROR_SEM_TIMEOUT, got %d\n", GetLastError());
2505 
2506         if (test_dll_phase == 2)
2507         {
2508             trace("dll: call ExitProcess()\n");
2509             *child_failures = winetest_get_failures();
2510             ExitProcess(197);
2511         }
2512         trace("dll: %p, DLL_PROCESS_DETACH, %p => DONE\n", hinst, param);
2513         break;
2514     }
2515     case DLL_THREAD_ATTACH:
2516         trace("dll: %p, DLL_THREAD_ATTACH, %p\n", hinst, param);
2517 
2518         ret = pRtlDllShutdownInProgress();
2519         ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2520 
2521         if (attached_thread_count < MAX_COUNT)
2522         {
2523             DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &attached_thread[attached_thread_count],
2524                             0, TRUE, DUPLICATE_SAME_ACCESS);
2525             attached_thread_count++;
2526         }
2527 
2528         /* Make sure the FLS slot is empty, if FLS is available */
2529         if (pFlsGetValue)
2530         {
2531             void* value;
2532             BOOL ret;
2533             SetLastError(0xdeadbeef);
2534             value = pFlsGetValue(fls_index);
2535             ok(!value, "FlsGetValue returned %p, expected NULL\n", value);
2536             todo_wine
2537                 ok(GetLastError() == ERROR_SUCCESS, "FlsGetValue failed with error %u\n", GetLastError());
2538             ret = pFlsSetValue(fls_index, (void*) 0x31415);
2539             ok(ret, "FlsSetValue failed\n");
2540             fls_count++;
2541         }
2542 
2543         break;
2544     case DLL_THREAD_DETACH:
2545         trace("dll: %p, DLL_THREAD_DETACH, %p\n", hinst, param);
2546         thread_detach_count++;
2547 
2548         ret = pRtlDllShutdownInProgress();
2549         /* win7 doesn't allow creating a thread during process shutdown but
2550          * earlier Windows versions allow it. In that case DLL_THREAD_DETACH is
2551          * sent on thread exit, but DLL_THREAD_ATTACH is never received.
2552          */
2553         if (noop_thread_started)
2554             ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
2555         else
2556             ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2557 
2558         /* FLS data should already be destroyed, if FLS is available.
2559          * Note that this is broken for Win2k3, which runs the callbacks *after* the DLL entry
2560          * point has already run.
2561          */
2562         if (pFlsGetValue && fls_index != FLS_OUT_OF_INDEXES)
2563         {
2564             void* value;
2565             SetLastError(0xdeadbeef);
2566             value = pFlsGetValue(fls_index);
2567             todo_wine
2568             {
2569                 ok(broken(value == (void*) 0x31415) || /* Win2k3 */
2570                    !value, "FlsGetValue returned %p, expected NULL\n", value);
2571             }
2572             ok(GetLastError() == ERROR_SUCCESS, "FlsGetValue failed with error %u\n", GetLastError());
2573         }
2574 
2575         break;
2576     default:
2577         trace("dll: %p, %d, %p\n", hinst, reason, param);
2578         break;
2579     }
2580 
2581     *child_failures = winetest_get_failures();
2582 
2583     return TRUE;
2584 }
2585 
child_process(const char * dll_name,DWORD target_offset)2586 static void child_process(const char *dll_name, DWORD target_offset)
2587 {
2588     void *target;
2589     DWORD ret, dummy, i, code, expected_code;
2590     HANDLE file, thread, process;
2591     HMODULE hmod;
2592     struct PROCESS_BASIC_INFORMATION_PRIVATE pbi;
2593     DWORD_PTR affinity;
2594 
2595     trace("phase %d: writing %p at %#x\n", test_dll_phase, dll_entry_point, target_offset);
2596 
2597     SetLastError(0xdeadbeef);
2598     mutex = CreateMutexW(NULL, FALSE, NULL);
2599     ok(mutex != 0, "CreateMutex error %d\n", GetLastError());
2600 
2601     SetLastError(0xdeadbeef);
2602     semaphore = CreateSemaphoreW(NULL, 1, 1, NULL);
2603     ok(semaphore != 0, "CreateSemaphore error %d\n", GetLastError());
2604 
2605     SetLastError(0xdeadbeef);
2606     event = CreateEventW(NULL, TRUE, FALSE, NULL);
2607     ok(event != 0, "CreateEvent error %d\n", GetLastError());
2608 
2609     SetLastError(0xdeadbeef);
2610     loader_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2611     ok(loader_lock_event != 0, "CreateEvent error %d\n", GetLastError());
2612 
2613     SetLastError(0xdeadbeef);
2614     peb_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2615     ok(peb_lock_event != 0, "CreateEvent error %d\n", GetLastError());
2616 
2617     SetLastError(0xdeadbeef);
2618     heap_lock_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2619     ok(heap_lock_event != 0, "CreateEvent error %d\n", GetLastError());
2620 
2621     SetLastError(0xdeadbeef);
2622     ack_event = CreateEventW(NULL, FALSE, FALSE, NULL);
2623     ok(ack_event != 0, "CreateEvent error %d\n", GetLastError());
2624 
2625     file = CreateFileA(dll_name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
2626     if (file == INVALID_HANDLE_VALUE)
2627     {
2628         ok(0, "could not open %s\n", dll_name);
2629         return;
2630     }
2631     SetFilePointer(file, target_offset, NULL, FILE_BEGIN);
2632     SetLastError(0xdeadbeef);
2633     target = dll_entry_point;
2634     ret = WriteFile(file, &target, sizeof(target), &dummy, NULL);
2635     ok(ret, "WriteFile error %d\n", GetLastError());
2636     CloseHandle(file);
2637 
2638     SetLastError(0xdeadbeef);
2639     hmod = LoadLibraryA(dll_name);
2640     ok(hmod != 0, "LoadLibrary error %d\n", GetLastError());
2641 
2642     SetLastError(0xdeadbeef);
2643     stop_event = CreateEventW(NULL, TRUE, FALSE, NULL);
2644     ok(stop_event != 0, "CreateEvent error %d\n", GetLastError());
2645 
2646     SetLastError(0xdeadbeef);
2647     thread = CreateThread(NULL, 0, mutex_thread_proc, event, 0, &dummy);
2648     ok(thread != 0, "CreateThread error %d\n", GetLastError());
2649     WaitForSingleObject(event, 3000);
2650     CloseHandle(thread);
2651 
2652     ResetEvent(event);
2653 
2654     SetLastError(0xdeadbeef);
2655     thread = CreateThread(NULL, 0, semaphore_thread_proc, event, 0, &dummy);
2656     ok(thread != 0, "CreateThread error %d\n", GetLastError());
2657     WaitForSingleObject(event, 3000);
2658     CloseHandle(thread);
2659 
2660     ResetEvent(event);
2661     Sleep(100);
2662 
2663     ok(attached_thread_count == 2, "attached thread count should be 2\n");
2664     for (i = 0; i < attached_thread_count; i++)
2665     {
2666         ret = GetExitCodeThread(attached_thread[i], &code);
2667         trace("child: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
2668         ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
2669         ok(code == STILL_ACTIVE, "expected thread exit code STILL_ACTIVE, got %u\n", code);
2670     }
2671 
2672     ret = WaitForSingleObject(attached_thread[0], 0);
2673     ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2674     ret = WaitForSingleObject(attached_thread[1], 0);
2675     ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2676 
2677     ret = WaitForSingleObject(event, 0);
2678     ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2679     ret = WaitForSingleObject(mutex, 0);
2680     ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2681     ret = WaitForSingleObject(semaphore, 0);
2682     ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2683 
2684     ret = pRtlDllShutdownInProgress();
2685     ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2686 
2687     SetLastError(0xdeadbeef);
2688     process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, GetCurrentProcessId());
2689     ok(process != NULL, "OpenProcess error %d\n", GetLastError());
2690 
2691     SetLastError(0xdeadbeef);
2692     ret = TerminateProcess(0, 195);
2693     ok(!ret, "TerminateProcess(0) should fail\n");
2694     ok(GetLastError() == ERROR_INVALID_HANDLE, "expected ERROR_INVALID_HANDLE, got %d\n", GetLastError());
2695 
2696     Sleep(100);
2697 
2698     affinity = 1;
2699     ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
2700     ok(!ret, "NtSetInformationProcess error %#x\n", ret);
2701 
2702     switch (test_dll_phase)
2703     {
2704     case 0:
2705         ret = pRtlDllShutdownInProgress();
2706         ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2707 
2708         trace("call NtTerminateProcess(0, 195)\n");
2709         ret = pNtTerminateProcess(0, 195);
2710         ok(!ret, "NtTerminateProcess error %#x\n", ret);
2711 
2712         memset(&pbi, 0, sizeof(pbi));
2713         ret = pNtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2714         ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
2715         ok(pbi.ExitStatus == STILL_ACTIVE || pbi.ExitStatus == 195,
2716            "expected STILL_ACTIVE, got %lu\n", pbi.ExitStatus);
2717         affinity = 1;
2718         ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
2719         ok(!ret, "NtSetInformationProcess error %#x\n", ret);
2720 
2721         ret = pRtlDllShutdownInProgress();
2722         ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2723 
2724         hmod = GetModuleHandleA(dll_name);
2725         ok(hmod != 0, "DLL should not be unloaded\n");
2726 
2727         SetLastError(0xdeadbeef);
2728         thread = CreateThread(NULL, 0, noop_thread_proc, &dummy, 0, &ret);
2729         ok(!thread || broken(thread != 0) /* before win7 */, "CreateThread should fail\n");
2730         if (!thread)
2731             ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
2732         else
2733         {
2734             ret = WaitForSingleObject(thread, 1000);
2735             ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2736             CloseHandle(thread);
2737         }
2738 
2739         trace("call LdrShutdownProcess()\n");
2740         pLdrShutdownProcess();
2741 
2742         ret = pRtlDllShutdownInProgress();
2743         ok(ret, "RtlDllShutdownInProgress returned %d\n", ret);
2744 
2745         hmod = GetModuleHandleA(dll_name);
2746         ok(hmod != 0, "DLL should not be unloaded\n");
2747 
2748         memset(&pbi, 0, sizeof(pbi));
2749         ret = pNtQueryInformationProcess(process, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
2750         ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
2751         ok(pbi.ExitStatus == STILL_ACTIVE || pbi.ExitStatus == 195,
2752            "expected STILL_ACTIVE, got %lu\n", pbi.ExitStatus);
2753         affinity = 1;
2754         ret = pNtSetInformationProcess(process, ProcessAffinityMask, &affinity, sizeof(affinity));
2755         ok(!ret, "NtSetInformationProcess error %#x\n", ret);
2756         break;
2757 
2758     case 1: /* normal ExitProcess */
2759         ret = pRtlDllShutdownInProgress();
2760         ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2761         break;
2762 
2763     case 2: /* ExitProcess will be called by the PROCESS_DETACH handler */
2764         ret = pRtlDllShutdownInProgress();
2765         ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2766 
2767         trace("call FreeLibrary(%p)\n", hmod);
2768         SetLastError(0xdeadbeef);
2769         ret = FreeLibrary(hmod);
2770         ok(ret, "FreeLibrary error %d\n", GetLastError());
2771         hmod = GetModuleHandleA(dll_name);
2772         ok(!hmod, "DLL should be unloaded\n");
2773 
2774         if (test_dll_phase == 2)
2775             ok(0, "FreeLibrary+ExitProcess should never return\n");
2776 
2777         ret = pRtlDllShutdownInProgress();
2778         ok(!ret, "RtlDllShutdownInProgress returned %d\n", ret);
2779 
2780         break;
2781 
2782     case 3:
2783         trace("signalling thread exit\n");
2784         SetEvent(stop_event);
2785         break;
2786 
2787     case 4:
2788         trace("setting loader_lock_event\n");
2789         SetEvent(loader_lock_event);
2790         WaitForSingleObject(ack_event, 1000);
2791         ok(inside_loader_lock != 0, "inside_loader_lock is not set\n");
2792 
2793         /* calling NtTerminateProcess should not cause a deadlock */
2794         trace("call NtTerminateProcess(0, 198)\n");
2795         ret = pNtTerminateProcess(0, 198);
2796         ok(!ret, "NtTerminateProcess error %#x\n", ret);
2797 
2798         *child_failures = winetest_get_failures();
2799 
2800         /* Windows fails to release loader lock acquired from another thread,
2801          * so the LdrUnlockLoaderLock call fails here and ExitProcess deadlocks
2802          * later on, so NtTerminateProcess is used instead.
2803          */
2804         trace("call NtTerminateProcess(GetCurrentProcess(), 198)\n");
2805         pNtTerminateProcess(GetCurrentProcess(), 198);
2806         ok(0, "NtTerminateProcess should not return\n");
2807         break;
2808 
2809     case 5:
2810         trace("setting peb_lock_event\n");
2811         SetEvent(peb_lock_event);
2812         WaitForSingleObject(ack_event, 1000);
2813         ok(inside_peb_lock != 0, "inside_peb_lock is not set\n");
2814 
2815         *child_failures = winetest_get_failures();
2816 
2817         /* calling ExitProcess should cause a deadlock */
2818         trace("call ExitProcess(198)\n");
2819         ExitProcess(198);
2820         ok(0, "ExitProcess should not return\n");
2821         break;
2822 
2823     case 6:
2824         trace("setting heap_lock_event\n");
2825         SetEvent(heap_lock_event);
2826         WaitForSingleObject(ack_event, 1000);
2827         ok(inside_heap_lock != 0, "inside_heap_lock is not set\n");
2828 
2829         *child_failures = winetest_get_failures();
2830 
2831         /* calling ExitProcess should cause a deadlock */
2832         trace("call ExitProcess(1)\n");
2833         ExitProcess(1);
2834         ok(0, "ExitProcess should not return\n");
2835         break;
2836 
2837     default:
2838         assert(0);
2839         break;
2840     }
2841 
2842     if (test_dll_phase == 0) expected_code = 195;
2843     else if (test_dll_phase == 3) expected_code = 196;
2844     else if (test_dll_phase == 4) expected_code = 198;
2845     else expected_code = STILL_ACTIVE;
2846 
2847     if (expected_code == STILL_ACTIVE)
2848     {
2849         ret = WaitForSingleObject(attached_thread[0], 100);
2850         ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2851         ret = WaitForSingleObject(attached_thread[1], 100);
2852         ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2853     }
2854     else
2855     {
2856         ret = WaitForSingleObject(attached_thread[0], 2000);
2857         ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2858         ret = WaitForSingleObject(attached_thread[1], 2000);
2859         ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2860     }
2861 
2862     for (i = 0; i < attached_thread_count; i++)
2863     {
2864         ret = GetExitCodeThread(attached_thread[i], &code);
2865         trace("child: GetExitCodeThread(%u) => %d,%u\n", i, ret, code);
2866         ok(ret == 1, "GetExitCodeThread returned %d, expected 1\n", ret);
2867         ok(code == expected_code, "expected thread exit code %u, got %u\n", expected_code, code);
2868     }
2869 
2870     *child_failures = winetest_get_failures();
2871 
2872     trace("call ExitProcess(195)\n");
2873     ExitProcess(195);
2874 }
2875 
test_ExitProcess(void)2876 static void test_ExitProcess(void)
2877 {
2878 #include "pshpack1.h"
2879 #ifdef __x86_64__
2880     static struct section_data
2881     {
2882         BYTE mov_rax[2];
2883         void *target;
2884         BYTE jmp_rax[2];
2885     } section_data = { { 0x48,0xb8 }, dll_entry_point, { 0xff,0xe0 } };
2886 #else
2887     static struct section_data
2888     {
2889         BYTE mov_eax;
2890         void *target;
2891         BYTE jmp_eax[2];
2892     } section_data = { 0xb8, dll_entry_point, { 0xff,0xe0 } };
2893 #endif
2894 #include "poppack.h"
2895     DWORD dummy, file_align;
2896     HANDLE file, thread, process, hmap, hmap_dup;
2897     char temp_path[MAX_PATH], dll_name[MAX_PATH], cmdline[MAX_PATH * 2];
2898     DWORD ret, target_offset, old_prot;
2899     char **argv, buf[256];
2900     PROCESS_INFORMATION pi;
2901     STARTUPINFOA si = { sizeof(si) };
2902     CONTEXT ctx;
2903     struct PROCESS_BASIC_INFORMATION_PRIVATE pbi;
2904     MEMORY_BASIC_INFORMATION mbi;
2905     DWORD_PTR affinity;
2906     void *addr;
2907     LARGE_INTEGER offset;
2908     SIZE_T size;
2909     IMAGE_NT_HEADERS nt_header;
2910 
2911 #if !defined(__i386__) && !defined(__x86_64__)
2912     skip("x86 specific ExitProcess test\n");
2913     return;
2914 #endif
2915 
2916     if (!pRtlDllShutdownInProgress)
2917     {
2918         win_skip("RtlDllShutdownInProgress is not available on this platform (XP+)\n");
2919         return;
2920     }
2921     if (!pNtQueryInformationProcess || !pNtSetInformationProcess)
2922     {
2923         win_skip("NtQueryInformationProcess/NtSetInformationProcess are not available on this platform\n");
2924         return;
2925     }
2926     if (!pNtAllocateVirtualMemory || !pNtFreeVirtualMemory)
2927     {
2928         win_skip("NtAllocateVirtualMemory/NtFreeVirtualMemory are not available on this platform\n");
2929         return;
2930     }
2931 
2932     /* prevent displaying of the "Unable to load this DLL" message box */
2933     SetErrorMode(SEM_FAILCRITICALERRORS);
2934 
2935     GetTempPathA(MAX_PATH, temp_path);
2936     GetTempFileNameA(temp_path, "ldr", 0, dll_name);
2937 
2938     /*trace("creating %s\n", dll_name);*/
2939     file = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
2940     if (file == INVALID_HANDLE_VALUE)
2941     {
2942         ok(0, "could not create %s\n", dll_name);
2943         return;
2944     }
2945 
2946     SetLastError(0xdeadbeef);
2947     ret = WriteFile(file, &dos_header, sizeof(dos_header), &dummy, NULL);
2948     ok(ret, "WriteFile error %d\n", GetLastError());
2949 
2950     nt_header = nt_header_template;
2951     nt_header.FileHeader.NumberOfSections = 1;
2952     nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
2953     nt_header.FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_RELOCS_STRIPPED;
2954 
2955     nt_header.OptionalHeader.AddressOfEntryPoint = 0x1000;
2956     nt_header.OptionalHeader.SectionAlignment = 0x1000;
2957     nt_header.OptionalHeader.FileAlignment = 0x200;
2958     nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000;
2959     nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER);
2960     SetLastError(0xdeadbeef);
2961     ret = WriteFile(file, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
2962     ok(ret, "WriteFile error %d\n", GetLastError());
2963     SetLastError(0xdeadbeef);
2964     ret = WriteFile(file, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
2965     ok(ret, "WriteFile error %d\n", GetLastError());
2966 
2967     section.SizeOfRawData = sizeof(section_data);
2968     section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
2969     section.VirtualAddress = nt_header.OptionalHeader.SectionAlignment;
2970     section.Misc.VirtualSize = sizeof(section_data);
2971     section.Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE;
2972     SetLastError(0xdeadbeef);
2973     ret = WriteFile(file, &section, sizeof(section), &dummy, NULL);
2974     ok(ret, "WriteFile error %d\n", GetLastError());
2975 
2976     file_align = nt_header.OptionalHeader.FileAlignment - nt_header.OptionalHeader.SizeOfHeaders;
2977     assert(file_align < sizeof(filler));
2978     SetLastError(0xdeadbeef);
2979     ret = WriteFile(file, filler, file_align, &dummy, NULL);
2980     ok(ret, "WriteFile error %d\n", GetLastError());
2981 
2982     target_offset = SetFilePointer(file, 0, NULL, FILE_CURRENT) + FIELD_OFFSET(struct section_data, target);
2983 
2984     /* section data */
2985     SetLastError(0xdeadbeef);
2986     ret = WriteFile(file, &section_data, sizeof(section_data), &dummy, NULL);
2987     ok(ret, "WriteFile error %d\n", GetLastError());
2988 
2989     CloseHandle(file);
2990 
2991     winetest_get_mainargs(&argv);
2992 
2993     /* phase 0 */
2994     *child_failures = -1;
2995     sprintf(cmdline, "\"%s\" loader %s %u 0", argv[0], dll_name, target_offset);
2996     ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2997     ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
2998     ret = WaitForSingleObject(pi.hProcess, 10000);
2999     ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
3000     if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
3001     GetExitCodeProcess(pi.hProcess, &ret);
3002     ok(ret == 195, "expected exit code 195, got %u\n", ret);
3003     if (*child_failures)
3004     {
3005         trace("%d failures in child process\n", *child_failures);
3006         winetest_add_failures(*child_failures);
3007     }
3008     CloseHandle(pi.hThread);
3009     CloseHandle(pi.hProcess);
3010 
3011     /* phase 1 */
3012     *child_failures = -1;
3013     sprintf(cmdline, "\"%s\" loader %s %u 1", argv[0], dll_name, target_offset);
3014     ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3015     ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
3016     ret = WaitForSingleObject(pi.hProcess, 10000);
3017     ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
3018     if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
3019     GetExitCodeProcess(pi.hProcess, &ret);
3020     ok(ret == 195, "expected exit code 195, got %u\n", ret);
3021     if (*child_failures)
3022     {
3023         trace("%d failures in child process\n", *child_failures);
3024         winetest_add_failures(*child_failures);
3025     }
3026     CloseHandle(pi.hThread);
3027     CloseHandle(pi.hProcess);
3028 
3029     /* phase 2 */
3030     *child_failures = -1;
3031     sprintf(cmdline, "\"%s\" loader %s %u 2", argv[0], dll_name, target_offset);
3032     ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3033     ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
3034     ret = WaitForSingleObject(pi.hProcess, 10000);
3035     ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
3036     if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
3037     GetExitCodeProcess(pi.hProcess, &ret);
3038     ok(ret == 197, "expected exit code 197, got %u\n", ret);
3039     if (*child_failures)
3040     {
3041         trace("%d failures in child process\n", *child_failures);
3042         winetest_add_failures(*child_failures);
3043     }
3044     CloseHandle(pi.hThread);
3045     CloseHandle(pi.hProcess);
3046 
3047     /* phase 3 */
3048     *child_failures = -1;
3049     sprintf(cmdline, "\"%s\" loader %s %u 3", argv[0], dll_name, target_offset);
3050     ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3051     ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
3052     ret = WaitForSingleObject(pi.hProcess, 10000);
3053     ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
3054     if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
3055     GetExitCodeProcess(pi.hProcess, &ret);
3056     ok(ret == 195, "expected exit code 195, got %u\n", ret);
3057     if (*child_failures)
3058     {
3059         trace("%d failures in child process\n", *child_failures);
3060         winetest_add_failures(*child_failures);
3061     }
3062     CloseHandle(pi.hThread);
3063     CloseHandle(pi.hProcess);
3064 
3065     /* phase 4 */
3066     if (pLdrLockLoaderLock && pLdrUnlockLoaderLock)
3067     {
3068         *child_failures = -1;
3069         sprintf(cmdline, "\"%s\" loader %s %u 4", argv[0], dll_name, target_offset);
3070         ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3071         ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
3072         ret = WaitForSingleObject(pi.hProcess, 10000);
3073         ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
3074         if (ret != WAIT_OBJECT_0) TerminateProcess(pi.hProcess, 0);
3075         GetExitCodeProcess(pi.hProcess, &ret);
3076         ok(ret == 198, "expected exit code 198, got %u\n", ret);
3077         if (*child_failures)
3078         {
3079             trace("%d failures in child process\n", *child_failures);
3080             winetest_add_failures(*child_failures);
3081         }
3082         CloseHandle(pi.hThread);
3083         CloseHandle(pi.hProcess);
3084     }
3085     else
3086         win_skip("LdrLockLoaderLock/LdrUnlockLoaderLock are not available on this platform\n");
3087 
3088     /* phase 5 */
3089     if (pRtlAcquirePebLock && pRtlReleasePebLock)
3090     {
3091         *child_failures = -1;
3092         sprintf(cmdline, "\"%s\" loader %s %u 5", argv[0], dll_name, target_offset);
3093         ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3094         ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
3095         ret = WaitForSingleObject(pi.hProcess, 5000);
3096         ok(ret == WAIT_TIMEOUT, "child process should fail to terminate\n");
3097         if (ret != WAIT_OBJECT_0)
3098         {
3099             trace("terminating child process\n");
3100             TerminateProcess(pi.hProcess, 199);
3101         }
3102         ret = WaitForSingleObject(pi.hProcess, 1000);
3103         ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
3104         GetExitCodeProcess(pi.hProcess, &ret);
3105         ok(ret == 199, "expected exit code 199, got %u\n", ret);
3106         if (*child_failures)
3107         {
3108             trace("%d failures in child process\n", *child_failures);
3109             winetest_add_failures(*child_failures);
3110         }
3111         CloseHandle(pi.hThread);
3112         CloseHandle(pi.hProcess);
3113     }
3114     else
3115         win_skip("RtlAcquirePebLock/RtlReleasePebLock are not available on this platform\n");
3116 
3117     /* phase 6 */
3118     *child_failures = -1;
3119     sprintf(cmdline, "\"%s\" loader %s %u 6", argv[0], dll_name, target_offset);
3120     ret = CreateProcessA(argv[0], cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
3121     ok(ret, "CreateProcess(%s) error %d\n", cmdline, GetLastError());
3122     ret = WaitForSingleObject(pi.hProcess, 5000);
3123     ok(ret == WAIT_TIMEOUT || broken(ret == WAIT_OBJECT_0) /* XP */, "child process should fail to terminate\n");
3124     if (ret != WAIT_OBJECT_0)
3125     {
3126         trace("terminating child process\n");
3127         TerminateProcess(pi.hProcess, 201);
3128     }
3129     ret = WaitForSingleObject(pi.hProcess, 1000);
3130     ok(ret == WAIT_OBJECT_0, "child process failed to terminate\n");
3131     GetExitCodeProcess(pi.hProcess, &ret);
3132     ok(ret == 201 || broken(ret == 1) /* XP */, "expected exit code 201, got %u\n", ret);
3133     if (*child_failures)
3134     {
3135         trace("%d failures in child process\n", *child_failures);
3136         winetest_add_failures(*child_failures);
3137     }
3138     CloseHandle(pi.hThread);
3139     CloseHandle(pi.hProcess);
3140 
3141     /* test remote process termination */
3142     SetLastError(0xdeadbeef);
3143     ret = CreateProcessA(argv[0], NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi);
3144     ok(ret, "CreateProcess(%s) error %d\n", argv[0], GetLastError());
3145 
3146     SetLastError(0xdeadbeef);
3147     addr = VirtualAllocEx(pi.hProcess, NULL, 4096, MEM_COMMIT, PAGE_READWRITE);
3148     ok(addr != NULL, "VirtualAllocEx error %d\n", GetLastError());
3149     SetLastError(0xdeadbeef);
3150     ret = VirtualProtectEx(pi.hProcess, addr, 4096, PAGE_READONLY, &old_prot);
3151     ok(ret, "VirtualProtectEx error %d\n", GetLastError());
3152     ok(old_prot == PAGE_READWRITE, "expected PAGE_READWRITE, got %#x\n", old_prot);
3153     SetLastError(0xdeadbeef);
3154     size = VirtualQueryEx(pi.hProcess, NULL, &mbi, sizeof(mbi));
3155     ok(size == sizeof(mbi), "VirtualQueryEx error %d\n", GetLastError());
3156 
3157     SetLastError(0xdeadbeef);
3158     ret = ReadProcessMemory(pi.hProcess, addr, buf, 4, &size);
3159     ok(ret, "ReadProcessMemory error %d\n", GetLastError());
3160     ok(size == 4, "expected 4, got %lu\n", size);
3161 
3162     SetLastError(0xdeadbeef);
3163     hmap = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, NULL);
3164     ok(hmap != 0, "CreateFileMapping error %d\n", GetLastError());
3165 
3166     SetLastError(0xdeadbeef);
3167     ret = DuplicateHandle(GetCurrentProcess(), hmap, pi.hProcess, &hmap_dup,
3168                           0, FALSE, DUPLICATE_SAME_ACCESS);
3169     ok(ret, "DuplicateHandle error %d\n", GetLastError());
3170 
3171     offset.u.LowPart = 0;
3172     offset.u.HighPart = 0;
3173     addr = NULL;
3174     size = 0;
3175     ret = pNtMapViewOfSection(hmap, pi.hProcess, &addr, 0, 0, &offset,
3176                               &size, 1 /* ViewShare */, 0, PAGE_READONLY);
3177     ok(!ret, "NtMapViewOfSection error %#x\n", ret);
3178     ret = pNtUnmapViewOfSection(pi.hProcess, addr);
3179     ok(!ret, "NtUnmapViewOfSection error %#x\n", ret);
3180 
3181     SetLastError(0xdeadbeef);
3182     thread = CreateRemoteThread(pi.hProcess, NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
3183     ok(thread != 0, "CreateRemoteThread error %d\n", GetLastError());
3184     SetLastError(0xdeadbeef);
3185     ctx.ContextFlags = CONTEXT_INTEGER;
3186     ret = GetThreadContext(thread, &ctx);
3187     ok(ret, "GetThreadContext error %d\n", GetLastError());
3188     SetLastError(0xdeadbeef);
3189     ctx.ContextFlags = CONTEXT_INTEGER;
3190     ret = SetThreadContext(thread, &ctx);
3191     ok(ret, "SetThreadContext error %d\n", GetLastError());
3192     SetLastError(0xdeadbeef);
3193     ret = SetThreadPriority(thread, 0);
3194     ok(ret, "SetThreadPriority error %d\n", GetLastError());
3195 
3196     SetLastError(0xdeadbeef);
3197     ret = TerminateThread(thread, 199);
3198     ok(ret, "TerminateThread error %d\n", GetLastError());
3199     /* Calling GetExitCodeThread() without waiting for thread termination
3200      * leads to different results due to a race condition.
3201      */
3202     ret = WaitForSingleObject(thread, 1000);
3203     ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
3204     GetExitCodeThread(thread, &ret);
3205     ok(ret == 199, "expected exit code 199, got %u\n", ret);
3206 
3207     SetLastError(0xdeadbeef);
3208     ret = TerminateProcess(pi.hProcess, 198);
3209     ok(ret, "TerminateProcess error %d\n", GetLastError());
3210     /* Checking process state without waiting for process termination
3211      * leads to different results due to a race condition.
3212      */
3213     ret = WaitForSingleObject(pi.hProcess, 1000);
3214     ok(ret == WAIT_OBJECT_0, "WaitForSingleObject failed: %x\n", ret);
3215 
3216     SetLastError(0xdeadbeef);
3217     process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, pi.dwProcessId);
3218     ok(process != NULL, "OpenProcess error %d\n", GetLastError());
3219     CloseHandle(process);
3220 
3221     memset(&pbi, 0, sizeof(pbi));
3222     ret = pNtQueryInformationProcess(pi.hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
3223     ok(!ret, "NtQueryInformationProcess error %#x\n", ret);
3224     ok(pbi.ExitStatus == 198, "expected 198, got %lu\n", pbi.ExitStatus);
3225     affinity = 1;
3226     ret = pNtSetInformationProcess(pi.hProcess, ProcessAffinityMask, &affinity, sizeof(affinity));
3227     ok(ret == STATUS_PROCESS_IS_TERMINATING, "expected STATUS_PROCESS_IS_TERMINATING, got %#x\n", ret);
3228 
3229     SetLastError(0xdeadbeef);
3230     ctx.ContextFlags = CONTEXT_INTEGER;
3231     ret = GetThreadContext(thread, &ctx);
3232     ok(!ret || broken(ret) /* XP 64-bit */, "GetThreadContext should fail\n");
3233     if (!ret)
3234         ok(GetLastError() == ERROR_INVALID_PARAMETER ||
3235            GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
3236            GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
3237            "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
3238     SetLastError(0xdeadbeef);
3239     ctx.ContextFlags = CONTEXT_INTEGER;
3240     ret = SetThreadContext(thread, &ctx);
3241     ok(!ret || broken(ret) /* XP 64-bit */, "SetThreadContext should fail\n");
3242     if (!ret)
3243         ok(GetLastError() == ERROR_ACCESS_DENIED ||
3244            GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
3245            GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
3246            "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3247     SetLastError(0xdeadbeef);
3248     ret = SetThreadPriority(thread, 0);
3249     ok(ret, "SetThreadPriority error %d\n", GetLastError());
3250     CloseHandle(thread);
3251 
3252     SetLastError(0xdeadbeef);
3253     ctx.ContextFlags = CONTEXT_INTEGER;
3254     ret = GetThreadContext(pi.hThread, &ctx);
3255     ok(!ret || broken(ret) /* XP 64-bit */, "GetThreadContext should fail\n");
3256     if (!ret)
3257         ok(GetLastError() == ERROR_INVALID_PARAMETER ||
3258            GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
3259            GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
3260            "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
3261     SetLastError(0xdeadbeef);
3262     ctx.ContextFlags = CONTEXT_INTEGER;
3263     ret = SetThreadContext(pi.hThread, &ctx);
3264     ok(!ret || broken(ret) /* XP 64-bit */, "SetThreadContext should fail\n");
3265     if (!ret)
3266         ok(GetLastError() == ERROR_ACCESS_DENIED ||
3267            GetLastError() == ERROR_GEN_FAILURE /* win7 64-bit */ ||
3268            GetLastError() == ERROR_INVALID_FUNCTION /* vista 64-bit */,
3269            "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3270     SetLastError(0xdeadbeef);
3271     ret = VirtualProtectEx(pi.hProcess, addr, 4096, PAGE_READWRITE, &old_prot);
3272     ok(!ret, "VirtualProtectEx should fail\n");
3273     ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3274     SetLastError(0xdeadbeef);
3275     size = 0;
3276     ret = ReadProcessMemory(pi.hProcess, addr, buf, 4, &size);
3277     ok(!ret, "ReadProcessMemory should fail\n");
3278     ok(GetLastError() == ERROR_PARTIAL_COPY || GetLastError() == ERROR_ACCESS_DENIED,
3279        "expected ERROR_PARTIAL_COPY, got %d\n", GetLastError());
3280     ok(!size, "expected 0, got %lu\n", size);
3281     SetLastError(0xdeadbeef);
3282     ret = VirtualFreeEx(pi.hProcess, addr, 0, MEM_RELEASE);
3283     ok(!ret, "VirtualFreeEx should fail\n");
3284     ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3285     SetLastError(0xdeadbeef);
3286     addr = VirtualAllocEx(pi.hProcess, NULL, 4096, MEM_COMMIT, PAGE_READWRITE);
3287     ok(!addr, "VirtualAllocEx should fail\n");
3288     ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3289     SetLastError(0xdeadbeef);
3290     size = VirtualQueryEx(pi.hProcess, NULL, &mbi, sizeof(mbi));
3291     ok(!size, "VirtualQueryEx should fail\n");
3292     ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3293 
3294     /* CloseHandle() call below leads to premature process termination
3295      * under some Windows versions.
3296      */
3297 if (0)
3298 {
3299     SetLastError(0xdeadbeef);
3300     ret = CloseHandle(hmap_dup);
3301     ok(ret, "CloseHandle should not fail\n");
3302 }
3303 
3304     SetLastError(0xdeadbeef);
3305     ret = DuplicateHandle(GetCurrentProcess(), hmap, pi.hProcess, &hmap_dup,
3306                           0, FALSE, DUPLICATE_SAME_ACCESS);
3307     ok(!ret, "DuplicateHandle should fail\n");
3308     ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3309 
3310     offset.u.LowPart = 0;
3311     offset.u.HighPart = 0;
3312     addr = NULL;
3313     size = 0;
3314     ret = pNtMapViewOfSection(hmap, pi.hProcess, &addr, 0, 0, &offset,
3315                               &size, 1 /* ViewShare */, 0, PAGE_READONLY);
3316     ok(ret == STATUS_PROCESS_IS_TERMINATING, "expected STATUS_PROCESS_IS_TERMINATING, got %#x\n", ret);
3317 
3318     SetLastError(0xdeadbeef);
3319     thread = CreateRemoteThread(pi.hProcess, NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
3320     ok(!thread, "CreateRemoteThread should fail\n");
3321     ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3322 
3323     SetLastError(0xdeadbeef);
3324     ret = DebugActiveProcess(pi.dwProcessId);
3325     ok(!ret, "DebugActiveProcess should fail\n");
3326     ok(GetLastError() == ERROR_ACCESS_DENIED /* 64-bit */ || GetLastError() == ERROR_NOT_SUPPORTED /* 32-bit */,
3327       "ERROR_ACCESS_DENIED, got %d\n", GetLastError());
3328 
3329     GetExitCodeProcess(pi.hProcess, &ret);
3330     ok(ret == 198 || broken(ret != 198) /* some 32-bit XP version in a VM returns random exit code */,
3331        "expected exit code 198, got %u\n", ret);
3332     CloseHandle(pi.hThread);
3333     CloseHandle(pi.hProcess);
3334 
3335     ret = DeleteFileA(dll_name);
3336     ok(ret, "DeleteFile error %d\n", GetLastError());
3337 }
3338 
failuredllhook(ULONG ul,DELAYLOAD_INFO * pd)3339 static PVOID WINAPI failuredllhook(ULONG ul, DELAYLOAD_INFO* pd)
3340 {
3341     ok(ul == 4, "expected 4, got %u\n", ul);
3342     ok(!!pd, "no delayload info supplied\n");
3343     if (pd)
3344     {
3345         ok(pd->Size == sizeof(*pd), "got %u\n", pd->Size);
3346         ok(!!pd->DelayloadDescriptor, "no DelayloadDescriptor supplied\n");
3347         if (pd->DelayloadDescriptor)
3348         {
3349             ok(pd->DelayloadDescriptor->Attributes.AllAttributes == 1,
3350                "expected 1, got %u\n", pd->DelayloadDescriptor->Attributes.AllAttributes);
3351             ok(pd->DelayloadDescriptor->DllNameRVA == 0x2000,
3352                "expected 0x2000, got %x\n", pd->DelayloadDescriptor->DllNameRVA);
3353             ok(pd->DelayloadDescriptor->ModuleHandleRVA == 0x201a,
3354                "expected 0x201a, got %x\n", pd->DelayloadDescriptor->ModuleHandleRVA);
3355             ok(pd->DelayloadDescriptor->ImportAddressTableRVA > pd->DelayloadDescriptor->ModuleHandleRVA,
3356                "expected %x > %x\n", pd->DelayloadDescriptor->ImportAddressTableRVA,
3357                pd->DelayloadDescriptor->ModuleHandleRVA);
3358             ok(pd->DelayloadDescriptor->ImportNameTableRVA > pd->DelayloadDescriptor->ImportAddressTableRVA,
3359                "expected %x > %x\n", pd->DelayloadDescriptor->ImportNameTableRVA,
3360                pd->DelayloadDescriptor->ImportAddressTableRVA);
3361             ok(pd->DelayloadDescriptor->BoundImportAddressTableRVA == 0,
3362                "expected 0, got %x\n", pd->DelayloadDescriptor->BoundImportAddressTableRVA);
3363             ok(pd->DelayloadDescriptor->UnloadInformationTableRVA == 0,
3364                "expected 0, got %x\n", pd->DelayloadDescriptor->UnloadInformationTableRVA);
3365             ok(pd->DelayloadDescriptor->TimeDateStamp == 0,
3366                "expected 0, got %x\n", pd->DelayloadDescriptor->TimeDateStamp);
3367         }
3368 
3369         ok(!!pd->ThunkAddress, "no ThunkAddress supplied\n");
3370         if (pd->ThunkAddress)
3371             ok(pd->ThunkAddress->u1.Ordinal, "no ThunkAddress value supplied\n");
3372 
3373         ok(!!pd->TargetDllName, "no TargetDllName supplied\n");
3374         if (pd->TargetDllName)
3375             ok(!strcmp(pd->TargetDllName, "secur32.dll"),
3376                "expected \"secur32.dll\", got \"%s\"\n", pd->TargetDllName);
3377 
3378         ok(pd->TargetApiDescriptor.ImportDescribedByName == 0,
3379            "expected 0, got %x\n", pd->TargetApiDescriptor.ImportDescribedByName);
3380         ok(pd->TargetApiDescriptor.Description.Ordinal == 0 ||
3381            pd->TargetApiDescriptor.Description.Ordinal == 999,
3382            "expected 0, got %x\n", pd->TargetApiDescriptor.Description.Ordinal);
3383 
3384         ok(!!pd->TargetModuleBase, "no TargetModuleBase supplied\n");
3385         ok(pd->Unused == NULL, "expected NULL, got %p\n", pd->Unused);
3386         ok(pd->LastError, "no LastError supplied\n");
3387     }
3388     cb_count++;
3389     return (void*)0xdeadbeef;
3390 }
3391 
test_ResolveDelayLoadedAPI(void)3392 static void test_ResolveDelayLoadedAPI(void)
3393 {
3394     static const char test_dll[] = "secur32.dll";
3395     static const char test_func[] = "SealMessage";
3396     char temp_path[MAX_PATH];
3397     char dll_name[MAX_PATH];
3398     IMAGE_DELAYLOAD_DESCRIPTOR idd, *delaydir;
3399     IMAGE_THUNK_DATA itd32;
3400     HANDLE hfile;
3401     HMODULE hlib;
3402     DWORD dummy, file_size, i;
3403     WORD hint = 0;
3404     BOOL ret;
3405     IMAGE_NT_HEADERS nt_header;
3406 
3407     static const struct test_data
3408     {
3409         BOOL func;
3410         UINT_PTR ordinal;
3411         BOOL succeeds;
3412     } td[] =
3413     {
3414         {
3415             TRUE, 0, TRUE
3416         },
3417         {
3418             FALSE, IMAGE_ORDINAL_FLAG | 2, TRUE
3419         },
3420         {
3421             FALSE, IMAGE_ORDINAL_FLAG | 5, TRUE
3422         },
3423         {
3424             FALSE, IMAGE_ORDINAL_FLAG | 0, FALSE
3425         },
3426         {
3427             FALSE, IMAGE_ORDINAL_FLAG | 999, FALSE
3428         },
3429     };
3430 
3431     if (!pResolveDelayLoadedAPI)
3432     {
3433         win_skip("ResolveDelayLoadedAPI is not available\n");
3434         return;
3435     }
3436 
3437     if (0) /* crashes on native */
3438     {
3439         SetLastError(0xdeadbeef);
3440         ok(!pResolveDelayLoadedAPI(NULL, NULL, NULL, NULL, NULL, 0),
3441            "ResolveDelayLoadedAPI succeeded\n");
3442         ok(GetLastError() == 0xdeadbeef, "GetLastError changed to %x\n", GetLastError());
3443 
3444         cb_count = 0;
3445         SetLastError(0xdeadbeef);
3446         ok(!pResolveDelayLoadedAPI(NULL, NULL, failuredllhook, NULL, NULL, 0),
3447            "ResolveDelayLoadedAPI succeeded\n");
3448         ok(GetLastError() == 0xdeadbeef, "GetLastError changed to %x\n", GetLastError());
3449         ok(cb_count == 1, "Wrong callback count: %d\n", cb_count);
3450     }
3451 
3452     GetTempPathA(MAX_PATH, temp_path);
3453     GetTempFileNameA(temp_path, "ldr", 0, dll_name);
3454     trace("creating %s\n", dll_name);
3455     hfile = CreateFileA(dll_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
3456     if (hfile == INVALID_HANDLE_VALUE)
3457     {
3458         ok(0, "could not create %s\n", dll_name);
3459         return;
3460     }
3461 
3462     SetLastError(0xdeadbeef);
3463     ret = WriteFile(hfile, &dos_header, sizeof(dos_header), &dummy, NULL);
3464     ok(ret, "WriteFile error %d\n", GetLastError());
3465 
3466     nt_header = nt_header_template;
3467     nt_header.FileHeader.NumberOfSections = 2;
3468     nt_header.FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER);
3469 
3470     nt_header.OptionalHeader.SectionAlignment = 0x1000;
3471     nt_header.OptionalHeader.FileAlignment = 0x1000;
3472     nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x2200;
3473     nt_header.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt_header) + 2 * sizeof(IMAGE_SECTION_HEADER);
3474     nt_header.OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
3475     nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress = 0x1000;
3476     nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size = 0x100;
3477 
3478     SetLastError(0xdeadbeef);
3479     ret = WriteFile(hfile, &nt_header, sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER), &dummy, NULL);
3480     ok(ret, "WriteFile error %d\n", GetLastError());
3481 
3482     SetLastError(0xdeadbeef);
3483     ret = WriteFile(hfile, &nt_header.OptionalHeader, sizeof(IMAGE_OPTIONAL_HEADER), &dummy, NULL);
3484     ok(ret, "WriteFile error %d\n", GetLastError());
3485 
3486     /* sections */
3487     section.PointerToRawData = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress;
3488     section.VirtualAddress = nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress;
3489     section.Misc.VirtualSize = 2 * sizeof(idd);
3490     section.SizeOfRawData = section.Misc.VirtualSize;
3491     section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
3492     SetLastError(0xdeadbeef);
3493     ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
3494     ok(ret, "WriteFile error %d\n", GetLastError());
3495 
3496     section.PointerToRawData = 0x2000;
3497     section.VirtualAddress = 0x2000;
3498     i = sizeof(td)/sizeof(td[0]);
3499     section.Misc.VirtualSize = sizeof(test_dll) + sizeof(hint) + sizeof(test_func) + sizeof(HMODULE) +
3500                                2 * (i + 1) * sizeof(IMAGE_THUNK_DATA);
3501     ok(section.Misc.VirtualSize <= 0x1000, "Too much tests, add a new section!\n");
3502     section.SizeOfRawData = section.Misc.VirtualSize;
3503     section.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE;
3504     SetLastError(0xdeadbeef);
3505     ret = WriteFile(hfile, &section, sizeof(section), &dummy, NULL);
3506     ok(ret, "WriteFile error %d\n", GetLastError());
3507 
3508     /* fill up to delay data */
3509     SetFilePointer( hfile, nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress, NULL, SEEK_SET );
3510 
3511     /* delay data */
3512     idd.Attributes.AllAttributes = 1;
3513     idd.DllNameRVA = 0x2000;
3514     idd.ModuleHandleRVA = idd.DllNameRVA + sizeof(test_dll) + sizeof(hint) + sizeof(test_func);
3515     idd.ImportAddressTableRVA = idd.ModuleHandleRVA + sizeof(HMODULE);
3516     idd.ImportNameTableRVA = idd.ImportAddressTableRVA + (i + 1) * sizeof(IMAGE_THUNK_DATA);
3517     idd.BoundImportAddressTableRVA = 0;
3518     idd.UnloadInformationTableRVA = 0;
3519     idd.TimeDateStamp = 0;
3520 
3521     SetLastError(0xdeadbeef);
3522     ret = WriteFile(hfile, &idd, sizeof(idd), &dummy, NULL);
3523     ok(ret, "WriteFile error %d\n", GetLastError());
3524 
3525     SetLastError(0xdeadbeef);
3526     ret = WriteFile(hfile, filler, sizeof(idd), &dummy, NULL);
3527     ok(ret, "WriteFile error %d\n", GetLastError());
3528 
3529     /* fill up to extended delay data */
3530     SetFilePointer( hfile, idd.DllNameRVA, NULL, SEEK_SET );
3531 
3532     /* extended delay data */
3533     SetLastError(0xdeadbeef);
3534     ret = WriteFile(hfile, test_dll, sizeof(test_dll), &dummy, NULL);
3535     ok(ret, "WriteFile error %d\n", GetLastError());
3536 
3537     SetLastError(0xdeadbeef);
3538     ret = WriteFile(hfile, &hint, sizeof(hint), &dummy, NULL);
3539     ok(ret, "WriteFile error %d\n", GetLastError());
3540 
3541     SetLastError(0xdeadbeef);
3542     ret = WriteFile(hfile, test_func, sizeof(test_func), &dummy, NULL);
3543     ok(ret, "WriteFile error %d\n", GetLastError());
3544 
3545     SetFilePointer( hfile, idd.ImportAddressTableRVA, NULL, SEEK_SET );
3546 
3547     for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
3548     {
3549         /* 0x1a00 is an empty space between delay data and extended delay data, real thunks are not necessary */
3550         itd32.u1.Function = nt_header.OptionalHeader.ImageBase + 0x1a00 + i * 0x20;
3551         SetLastError(0xdeadbeef);
3552         ret = WriteFile(hfile, &itd32, sizeof(itd32), &dummy, NULL);
3553         ok(ret, "WriteFile error %d\n", GetLastError());
3554     }
3555 
3556     itd32.u1.Function = 0;
3557     SetLastError(0xdeadbeef);
3558     ret = WriteFile(hfile, &itd32, sizeof(itd32), &dummy, NULL);
3559     ok(ret, "WriteFile error %d\n", GetLastError());
3560 
3561     for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
3562     {
3563         if (td[i].func)
3564             itd32.u1.AddressOfData = idd.DllNameRVA + sizeof(test_dll);
3565         else
3566             itd32.u1.Ordinal = td[i].ordinal;
3567         SetLastError(0xdeadbeef);
3568         ret = WriteFile(hfile, &itd32, sizeof(itd32), &dummy, NULL);
3569         ok(ret, "WriteFile error %d\n", GetLastError());
3570     }
3571 
3572     itd32.u1.Ordinal = 0;
3573     SetLastError(0xdeadbeef);
3574     ret = WriteFile(hfile, &itd32, sizeof(itd32), &dummy, NULL);
3575     ok(ret, "WriteFile error %d\n", GetLastError());
3576 
3577     /* fill up to eof */
3578     SetFilePointer( hfile, section.VirtualAddress + section.Misc.VirtualSize, NULL, SEEK_SET );
3579     SetEndOfFile( hfile );
3580     CloseHandle(hfile);
3581 
3582     SetLastError(0xdeadbeef);
3583     hlib = LoadLibraryA(dll_name);
3584     ok(hlib != NULL, "LoadLibrary error %u\n", GetLastError());
3585     if (!hlib)
3586     {
3587         skip("couldn't load %s.\n", dll_name);
3588         DeleteFileA(dll_name);
3589         return;
3590     }
3591 
3592     delaydir = pRtlImageDirectoryEntryToData(hlib, TRUE, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT, &file_size);
3593     if (!delaydir)
3594     {
3595         skip("haven't found section for delay import directory.\n");
3596         FreeLibrary(hlib);
3597         DeleteFileA(dll_name);
3598         return;
3599     }
3600 
3601     for (;;)
3602     {
3603         IMAGE_THUNK_DATA *itdn, *itda;
3604         HMODULE htarget;
3605 
3606         if (!delaydir->DllNameRVA ||
3607             !delaydir->ImportAddressTableRVA ||
3608             !delaydir->ImportNameTableRVA) break;
3609 
3610         itdn = RVAToAddr(delaydir->ImportNameTableRVA, hlib);
3611         itda = RVAToAddr(delaydir->ImportAddressTableRVA, hlib);
3612         htarget = LoadLibraryA(RVAToAddr(delaydir->DllNameRVA, hlib));
3613 
3614         for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
3615         {
3616             void *ret, *load;
3617 
3618             if (IMAGE_SNAP_BY_ORDINAL(itdn[i].u1.Ordinal))
3619                 load = (void *)GetProcAddress(htarget, (LPSTR)IMAGE_ORDINAL(itdn[i].u1.Ordinal));
3620             else
3621             {
3622                 const IMAGE_IMPORT_BY_NAME* iibn = RVAToAddr(itdn[i].u1.AddressOfData, hlib);
3623                 load = (void *)GetProcAddress(htarget, (char*)iibn->Name);
3624             }
3625 
3626             cb_count = 0;
3627             ret = pResolveDelayLoadedAPI(hlib, delaydir, failuredllhook, NULL, &itda[i], 0);
3628             if (td[i].succeeds)
3629             {
3630                 ok(ret != NULL, "Test %u: ResolveDelayLoadedAPI failed\n", i);
3631                 ok(ret == load, "Test %u: expected %p, got %p\n", i, load, ret);
3632                 ok(ret == (void*)itda[i].u1.AddressOfData, "Test %u: expected %p, got %p\n",
3633                    i, ret, (void*)itda[i].u1.AddressOfData);
3634                 ok(!cb_count, "Test %u: Wrong callback count: %d\n", i, cb_count);
3635             }
3636             else
3637             {
3638                 ok(ret == (void*)0xdeadbeef, "Test %u: ResolveDelayLoadedAPI succeeded with %p\n", i, ret);
3639                 ok(cb_count, "Test %u: Wrong callback count: %d\n", i, cb_count);
3640             }
3641         }
3642         delaydir++;
3643     }
3644 
3645     FreeLibrary(hlib);
3646     trace("deleting %s\n", dll_name);
3647     DeleteFileA(dll_name);
3648 }
3649 
test_InMemoryOrderModuleList(void)3650 static void test_InMemoryOrderModuleList(void)
3651 {
3652     PEB_LDR_DATA *ldr = NtCurrentTeb()->Peb->LdrData;
3653     LIST_ENTRY *entry1, *mark1 = &ldr->InLoadOrderModuleList;
3654     LIST_ENTRY *entry2, *mark2 = &ldr->InMemoryOrderModuleList;
3655     LDR_MODULE *module1, *module2;
3656 
3657     ok(ldr->Initialized == TRUE, "expected TRUE, got %u\n", ldr->Initialized);
3658 
3659     for (entry1 = mark1->Flink, entry2 = mark2->Flink;
3660          entry1 != mark1 && entry2 != mark2;
3661          entry1 = entry1->Flink, entry2 = entry2->Flink)
3662     {
3663         module1 = CONTAINING_RECORD(entry1, LDR_MODULE, InLoadOrderModuleList);
3664         module2 = CONTAINING_RECORD(entry2, LDR_MODULE, InMemoryOrderModuleList);
3665         ok(module1 == module2, "expected module1 == module2, got %p and %p\n", module1, module2);
3666     }
3667     ok(entry1 == mark1, "expected entry1 == mark1, got %p and %p\n", entry1, mark1);
3668     ok(entry2 == mark2, "expected entry2 == mark2, got %p and %p\n", entry2, mark2);
3669 }
3670 
toupperW(WCHAR c)3671 static inline WCHAR toupperW(WCHAR c)
3672 {
3673     WCHAR tmp = c;
3674     CharUpperBuffW(&tmp, 1);
3675     return tmp;
3676 }
3677 
hash_basename(const WCHAR * basename)3678 static ULONG hash_basename(const WCHAR *basename)
3679 {
3680     WORD version = MAKEWORD(NtCurrentTeb()->Peb->OSMinorVersion,
3681                             NtCurrentTeb()->Peb->OSMajorVersion);
3682     ULONG hash = 0;
3683 
3684     if (version >= 0x0602)
3685     {
3686         for (; *basename; basename++)
3687             hash = hash * 65599 + toupperW(*basename);
3688     }
3689     else if (version == 0x0601)
3690     {
3691         for (; *basename; basename++)
3692             hash = hash + 65599 * toupperW(*basename);
3693     }
3694     else
3695         hash = toupperW(basename[0]) - 'A';
3696 
3697     return hash & 31;
3698 }
3699 
test_HashLinks(void)3700 static void test_HashLinks(void)
3701 {
3702     static WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
3703     static WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3704 
3705     LIST_ENTRY *hash_map, *entry, *mark;
3706     LDR_MODULE *module;
3707     BOOL found;
3708 
3709     entry = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3710     entry = entry->Flink;
3711 
3712     module = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
3713     entry = module->HashLinks.Blink;
3714 
3715     hash_map = entry - hash_basename(module->BaseDllName.Buffer);
3716 
3717     mark = &hash_map[hash_basename(ntdllW)];
3718     found = FALSE;
3719     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3720     {
3721         module = CONTAINING_RECORD(entry, LDR_MODULE, HashLinks);
3722         if (!lstrcmpiW(module->BaseDllName.Buffer, ntdllW))
3723         {
3724             found = TRUE;
3725             break;
3726         }
3727     }
3728     ok(found, "Could not find ntdll\n");
3729 
3730     mark = &hash_map[hash_basename(kernel32W)];
3731     found = FALSE;
3732     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3733     {
3734         module = CONTAINING_RECORD(entry, LDR_MODULE, HashLinks);
3735         if (!lstrcmpiW(module->BaseDllName.Buffer, kernel32W))
3736         {
3737             found = TRUE;
3738             break;
3739         }
3740     }
3741     ok(found, "Could not find kernel32\n");
3742 }
3743 
START_TEST(loader)3744 START_TEST(loader)
3745 {
3746     int argc;
3747     char **argv;
3748     HANDLE ntdll, mapping, kernel32;
3749     SYSTEM_INFO si;
3750 
3751     ntdll = GetModuleHandleA("ntdll.dll");
3752     kernel32 = GetModuleHandleA("kernel32.dll");
3753     pNtCreateSection = (void *)GetProcAddress(ntdll, "NtCreateSection");
3754     pNtQuerySection = (void *)GetProcAddress(ntdll, "NtQuerySection");
3755     pNtMapViewOfSection = (void *)GetProcAddress(ntdll, "NtMapViewOfSection");
3756     pNtUnmapViewOfSection = (void *)GetProcAddress(ntdll, "NtUnmapViewOfSection");
3757     pNtTerminateProcess = (void *)GetProcAddress(ntdll, "NtTerminateProcess");
3758     pNtQueryInformationProcess = (void *)GetProcAddress(ntdll, "NtQueryInformationProcess");
3759     pNtSetInformationProcess = (void *)GetProcAddress(ntdll, "NtSetInformationProcess");
3760     pLdrShutdownProcess = (void *)GetProcAddress(ntdll, "LdrShutdownProcess");
3761     pRtlDllShutdownInProgress = (void *)GetProcAddress(ntdll, "RtlDllShutdownInProgress");
3762     pNtAllocateVirtualMemory = (void *)GetProcAddress(ntdll, "NtAllocateVirtualMemory");
3763     pNtFreeVirtualMemory = (void *)GetProcAddress(ntdll, "NtFreeVirtualMemory");
3764     pLdrLockLoaderLock = (void *)GetProcAddress(ntdll, "LdrLockLoaderLock");
3765     pLdrUnlockLoaderLock = (void *)GetProcAddress(ntdll, "LdrUnlockLoaderLock");
3766     pRtlAcquirePebLock = (void *)GetProcAddress(ntdll, "RtlAcquirePebLock");
3767     pRtlReleasePebLock = (void *)GetProcAddress(ntdll, "RtlReleasePebLock");
3768     pRtlImageDirectoryEntryToData = (void *)GetProcAddress(ntdll, "RtlImageDirectoryEntryToData");
3769     pFlsAlloc = (void *)GetProcAddress(kernel32, "FlsAlloc");
3770     pFlsSetValue = (void *)GetProcAddress(kernel32, "FlsSetValue");
3771     pFlsGetValue = (void *)GetProcAddress(kernel32, "FlsGetValue");
3772     pFlsFree = (void *)GetProcAddress(kernel32, "FlsFree");
3773     pIsWow64Process = (void *)GetProcAddress(kernel32, "IsWow64Process");
3774     pResolveDelayLoadedAPI = (void *)GetProcAddress(kernel32, "ResolveDelayLoadedAPI");
3775 
3776     if (pIsWow64Process) pIsWow64Process( GetCurrentProcess(), &is_wow64 );
3777     GetSystemInfo( &si );
3778     page_size = si.dwPageSize;
3779     dos_header.e_magic = IMAGE_DOS_SIGNATURE;
3780     dos_header.e_lfanew = sizeof(dos_header);
3781 
3782     mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 4096, "winetest_loader");
3783     ok(mapping != 0, "CreateFileMapping failed\n");
3784     child_failures = MapViewOfFile(mapping, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 4096);
3785     if (*child_failures == -1)
3786     {
3787         *child_failures = 0;
3788     }
3789     else
3790         *child_failures = -1;
3791 
3792     argc = winetest_get_mainargs(&argv);
3793     if (argc > 4)
3794     {
3795         test_dll_phase = atoi(argv[4]);
3796         child_process(argv[2], atol(argv[3]));
3797         return;
3798     }
3799 
3800     test_Loader();
3801     test_FakeDLL();
3802     test_filenames();
3803     test_ResolveDelayLoadedAPI();
3804     test_ImportDescriptors();
3805     test_section_access();
3806     test_import_resolution();
3807     test_ExitProcess();
3808     test_InMemoryOrderModuleList();
3809     test_HashLinks();
3810 }
3811