ReactOS  0.4.13-dev-92-gf251225
loader.c
Go to the documentation of this file.
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 
42 {
49 };
50 
52 static WORD cb_count;
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,
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 
84 {
85  if (rva == 0)
86  return NULL;
87  return ((char*) module) + rva;
88 }
89 
91 
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 
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 
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 
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 
194  {
195  SetLastError(0xdeadbeef);
197  sizeof(IMAGE_OPTIONAL_HEADER),
198  &dummy, NULL);
199  ok(ret, "WriteFile error %d\n", GetLastError());
201  {
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 
212  {
214 
215  section.SizeOfRawData = 10;
216 
218  {
219  section.PointerToRawData = dos_size;
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 
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 
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);
277  ok(ret, "WriteFile error %d\n", GetLastError());
278 
279  SetLastError(0xdeadbeef);
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 
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;
302  const IMAGE_COR20_HEADER *cor_header = NULL;
303  SIZE_T info_size = (SIZE_T)0xdeadbeef << 16;
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 
315  NULL, OPEN_EXISTING, 0, 0 );
316  ok( file != INVALID_HANDLE_VALUE, "%u: CreateFile error %d\n", id, GetLastError() );
318 
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 );
332  {
337  if (!truncated &&
340  cor_header = section_data;
341  }
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;
349  if (!truncated &&
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;
361  if (!truncated &&
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 
404  ok( image.ImageContainsCode == TRUE, "%u: ImageContainsCode wrong %u\n", id,
405  image.ImageContainsCode );
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 );
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  }
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  }
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);
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++;
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 );
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;
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 */
501  const void *section_data, int line )
502 {
503  char dll_name[MAX_PATH];
505  HANDLE file, map;
508  BOOL has_code;
509  HMODULE mod;
510 
512 
514  ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
515 
516  size.QuadPart = file_size;
519  if (!status)
520  {
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 */
534  {
535  SetLastError( 0xdeadbeef );
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 
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,
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,
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),
660  1,
661  0,
662  { ERROR_SUCCESS, ERROR_BAD_EXE_FORMAT } /* vista is more strict */
663  },
664  { sizeof(dos_header),
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,
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;
712  HANDLE h;
713  HMODULE hlib, hlib_as_data_file;
714  char dll_name[MAX_PATH];
715  SIZE_T size;
716  BOOL ret;
718  WORD alt_machine, orig_machine = nt_header_template.FileHeader.Machine;
720  IMAGE_COR20_HEADER cor_header;
721 
722  /* prevent displaying of the "Unable to load this DLL" message box */
724 
725  for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
726  {
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  {
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",
756  ok(info.State == MEM_COMMIT, "%d: %x != MEM_COMMIT\n", i, info.State);
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());
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 */
799  {
800  const char *start;
801 
802  start = (const char *)hlib + nt_header.OptionalHeader.SizeOfHeaders;
804  ok(!memcmp(start, filler, size), "%d: header alignment is not cleared\n", i);
805  }
806 
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());
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",
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 
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 */
839  {
840  const char *start;
841 
842  start = (const char *)hlib + section.VirtualAddress + section.PointerToRawData + section.SizeOfRawData;
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);
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);
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);
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);
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 
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 
978 
985 
986  section.SizeOfRawData = sizeof(section_data);
987  section.PointerToRawData = page_size;
988  section.VirtualAddress = page_size;
989  section.Misc.VirtualSize = page_size;
990 
992  ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
993 
996  ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
997 
1000  ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1003 
1004  dos_header.e_magic = 0;
1006  ok( status == STATUS_INVALID_IMAGE_NOT_MZ, "NtCreateSection error %08x\n", status );
1007 
1011  ok( status == STATUS_INVALID_IMAGE_NE_FORMAT, "NtCreateSection error %08x\n", status );
1012 
1013  nt_header.Signature = 0xdeadbeef;
1015  ok( status == STATUS_INVALID_IMAGE_PROTECT, "NtCreateSection error %08x\n", status );
1016 
1018  nt_header.OptionalHeader.Magic = 0xdead;
1020  ok( status == STATUS_INVALID_IMAGE_FORMAT, "NtCreateSection error %08x\n", status );
1021 
1023  nt_header.FileHeader.Machine = 0xdead;
1026  "NtCreateSection error %08x\n", status );
1027 
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;
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;
1055  "NtCreateSection error %08x\n", status );
1056 
1057  nt_header.FileHeader.Machine = orig_machine;
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 
1082  status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1083  ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1084 
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 
1095  status = map_image_section( &nt_header, &section, &cor_header, __LINE__ );
1096  ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1097 
1099  {
1100  IMAGE_NT_HEADERS64 nt64;
1101 
1102  memset( &nt64, 0, sizeof(nt64) );
1104  nt64.FileHeader.Machine = orig_machine;
1105  nt64.FileHeader.NumberOfSections = 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;
1118  nt64.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt64) + sizeof(IMAGE_SECTION_HEADER);
1121  nt64.OptionalHeader.SizeOfStackReserve = 0x321000;
1122  nt64.OptionalHeader.SizeOfStackCommit = 0x123000;
1124 
1125  status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1127  "NtCreateSection error %08x\n", status );
1128 
1129  switch (orig_machine)
1130  {
1133  }
1134  status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
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__ );
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__ );
1148  "NtCreateSection error %08x\n", status );
1149 
1150  nt64.OptionalHeader.SizeOfCode = 0;
1153  status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1155  "NtCreateSection error %08x\n", status );
1156 
1157  nt64.OptionalHeader.SizeOfCode = 0x1000;
1160  section.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE;
1161  status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, section_data, __LINE__ );
1163  "NtCreateSection error %08x\n", status );
1164 
1165  nt64.OptionalHeader.SizeOfCode = 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__ );
1170  "NtCreateSection error %08x\n", status );
1171 
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__ );
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__ );
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__ );
1190  "NtCreateSection error %08x\n", status );
1191 
1193  status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1195  "NtCreateSection error %08x\n", status );
1196 
1198  status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
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__ );
1205  "NtCreateSection error %08x\n", status );
1206 
1209  status = map_image_section( (IMAGE_NT_HEADERS *)&nt64, &section, &cor_header, __LINE__ );
1211  "NtCreateSection error %08x\n", status );
1212  }
1213  else
1214  {
1215  IMAGE_NT_HEADERS32 nt32;
1216 
1217  memset( &nt32, 0, sizeof(nt32) );
1219  nt32.FileHeader.Machine = orig_machine;
1220  nt32.FileHeader.NumberOfSections = 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;
1233  nt32.OptionalHeader.SizeOfHeaders = sizeof(dos_header) + sizeof(nt32) + sizeof(IMAGE_SECTION_HEADER);
1236  nt32.OptionalHeader.SizeOfStackReserve = 0x321000;
1237  nt32.OptionalHeader.SizeOfStackCommit = 0x123000;
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  {
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;
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;
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;
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 
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 
1299  status = map_image_section( (IMAGE_NT_HEADERS *)&nt32, &section, &cor_header, __LINE__ );
1300  ok( status == STATUS_SUCCESS, "NtCreateSection error %08x\n", status );
1301 
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 
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 
1317 }
1318 
1319 static void test_filenames(void)
1320 {
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 
1328 
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() );
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" );
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() );
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" );
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() );
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" );
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 
1398 static void test_FakeDLL(void)
1399 {
1400 #if defined(__i386__) || defined(__x86_64__)
1401  NTSTATUS (WINAPI *pNtSetEvent)(HANDLE, ULONG *) = NULL;
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 
1413 
1415  ok(file != INVALID_HANDLE_VALUE, "Failed to open %s (error %u)\n", wine_dbgstr_w(path), GetLastError());
1416 
1418  ok(map != NULL, "CreateFileMapping failed with error %u\n", GetLastError());
1420  ok(ptr != NULL, "MapViewOfFile failed with error %u\n", GetLastError());
1421 
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;
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 
1487  CloseHandle(map);
1488  CloseHandle(file);
1489 #endif
1490 }
1491 
1492 /* Verify linking style of import descriptors */
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 */
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);
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 
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;
1552  SIZE_T size;
1553  void *addr1, *addr2;
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 
1652 {
1653  switch (prot & 0xff)
1654  {
1655  case PAGE_READWRITE:
1656  case PAGE_WRITECOPY:
1659  return TRUE;
1660 
1661  default:
1662  return FALSE;
1663  }
1664 }
1665 
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 */
1694  { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE, 0 }, /* 0x50 */
1695  { PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READ, 0 }, /* 0x60 */
1698  { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE, 0 }, /* 0x90 */
1699  { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READ, 0 }, /* 0xa0 */
1701  { PAGE_EXECUTE_WRITECOPY | PAGE_EXECUTE_READWRITE, 0 }, /* 0xc0 */
1705  };
1706  DWORD ret, orig_prot, old_prot, rw_prot, exec_prot, i, j;
1708 
1709  SetLastError(0xdeadbeef);
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);
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 
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 },
1809 
1818 
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;
1837  STARTUPINFOA sti;
1839  DWORD ret;
1840 
1841  /* prevent displaying of the "Unable to load this DLL" message box */
1843 
1845 
1846  for (i = 0; i < sizeof(td)/sizeof(td[0]); i++)
1847  {
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 
1868 
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);
1878  ok(ret, "WriteFile error %d\n", GetLastError());
1879 
1880  section.SizeOfRawData = sizeof(section_data);
1881  section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
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 
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 */
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 
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  {
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;
2020  char tls_data[16];
2021  SHORT tls_index;
2022  } data, *ptr;
2025  int test;
2026 
2027  for (test = 0; test < 3; test++)
2028  {
2029 #define DATA_RVA(ptr) (page_size + ((char *)(ptr) - (char *)&data))
2037  nt.OptionalHeader.ImageBase = 0x12340000;
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 
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);
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 */
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
2143 
2145 {
2146  HANDLE wait_list[4];
2147  DWORD ret;
2148 
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);
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++;
2179  }
2180  else if (ret == WAIT_OBJECT_0 + 3)
2181  {
2182  trace("%04x: mutex_thread_proc: Entering heap lock\n", GetCurrentThreadId());
2184  inside_heap_lock++;
2186  }
2187  }
2188 
2189  trace("%04x: mutex_thread_proc: exiting\n", GetCurrentThreadId());
2190  return 196;
2191 }
2192 
2194 {
2195  DWORD ret;
2196 
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 
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 
2225 static VOID WINAPI fls_callback(PVOID lpFlsData)
2226 {
2227  ok(lpFlsData == (void*) 0x31415, "lpFlsData is %p, expected %p\n", lpFlsData, (void*) 0x31415);
2229 }
2230 
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;
2272  void *addr;
2273  SIZE_T size;
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  */
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  {
2367  ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
2368  }
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 
2376  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2377 
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 */
2386  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2387 
2388  if (expected_code == STILL_ACTIVE)
2389  {
2391  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2393  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2394  }
2395  else
2396  {
2398  ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
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);
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");
2428  }
2429 
2430  SetLastError(0xdeadbeef);
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);
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");
2456  }
2457 
2458  SetLastError(0xdeadbeef);
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 
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);
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");
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 
2522  {
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 
2582 
2583  return TRUE;
2584 }
2585 
2586 static void child_process(const char *dll_name, DWORD target_offset)
2587 {
2588  void *target;
2589  DWORD ret, dummy, i, code, expected_code;
2591  HMODULE hmod;
2594 
2595  trace("phase %d: writing %p at %#x\n", test_dll_phase, dll_entry_point, target_offset);
2596 
2597  SetLastError(0xdeadbeef);
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);
2611  ok(loader_lock_event != 0, "CreateEvent error %d\n", GetLastError());
2612 
2613  SetLastError(0xdeadbeef);
2615  ok(peb_lock_event != 0, "CreateEvent error %d\n", GetLastError());
2616 
2617  SetLastError(0xdeadbeef);
2619  ok(heap_lock_event != 0, "CreateEvent error %d\n", GetLastError());
2620 
2621  SetLastError(0xdeadbeef);
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);
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);
2644  ok(stop_event != 0, "CreateEvent error %d\n", GetLastError());
2645 
2646  SetLastError(0xdeadbeef);
2648  ok(thread != 0, "CreateThread error %d\n", GetLastError());
2649  WaitForSingleObject(event, 3000);
2651 
2652  ResetEvent(event);
2653 
2654  SetLastError(0xdeadbeef);
2656  ok(thread != 0, "CreateThread error %d\n", GetLastError());
2657  WaitForSingleObject(event, 3000);
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  {
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 
2673  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2675  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2676 
2678  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2680  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
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);
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);
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);
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");
2785  break;
2786 
2787  case 4:
2788  trace("setting loader_lock_event\n");
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 
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");
2813  ok(inside_peb_lock != 0, "inside_peb_lock is not set\n");
2814 
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");
2827  ok(inside_heap_lock != 0, "inside_heap_lock is not set\n");
2828 
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  {
2850  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2852  ok(ret == WAIT_TIMEOUT, "expected WAIT_TIMEOUT, got %#x\n", ret);
2853  }
2854  else
2855  {
2857  ok(ret == WAIT_OBJECT_0, "expected WAIT_OBJECT_0, got %#x\n", ret);
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  {
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 
2871 
2872  trace("call ExitProcess(195)\n");
2873  ExitProcess(195);
2874 }
2875 
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];
2901  STARTUPINFOA si = { sizeof(si) };
2902  CONTEXT ctx;
2906  void *addr;
2908  SIZE_T size;
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 */
2934 
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 
2954 
2958  nt_header.OptionalHeader.SizeOfImage = sizeof(dos_header) + sizeof(nt_header) + sizeof(IMAGE_SECTION_HEADER) + 0x1000;
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);
2965  ok(ret, "WriteFile error %d\n", GetLastError());
2966 
2967  section.SizeOfRawData = sizeof(section_data);
2968  section.PointerToRawData = nt_header.OptionalHeader.FileAlignment;
2970  section.Misc.VirtualSize = sizeof(section_data);
2972  SetLastError(0xdeadbeef);
2973  ret = WriteFile(file, &section, sizeof(section), &dummy, NULL);
2974  ok(ret, "WriteFile error %d\n", GetLastError());
2975 
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);
2987  ok(ret, "WriteFile error %d\n", GetLastError());
2988 
2989  CloseHandle(file);
2990 
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);
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);
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);
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);
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);
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);
3110  }
3111  CloseHandle(pi.hThread);