1 /*
2  * Unit test suite for process functions
3  *
4  * Copyright 2002 Eric Pouech
5  * Copyright 2006 Dmitry Timoshkov
6  * Copyright 2014 Michael M�ller
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22 
23 #include "precomp.h"
24 
25 /* PROCESS_ALL_ACCESS in Vista+ PSDKs is incompatible with older Windows versions */
26 #define PROCESS_ALL_ACCESS_NT4 (PROCESS_ALL_ACCESS & ~0xf000)
27 /* THREAD_ALL_ACCESS in Vista+ PSDKs is incompatible with older Windows versions */
28 #define THREAD_ALL_ACCESS_NT4 (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3ff)
29 
30 #define expect_eq_d(expected, actual) \
31     do { \
32       int value = (actual); \
33       ok((expected) == value, "Expected " #actual " to be %d (" #expected ") is %d\n", \
34           (expected), value); \
35     } while (0)
36 #define expect_eq_s(expected, actual) \
37     do { \
38       LPCSTR value = (actual); \
39       ok(lstrcmpA((expected), value) == 0, "Expected " #actual " to be L\"%s\" (" #expected ") is L\"%s\"\n", \
40           expected, value); \
41     } while (0)
42 #define expect_eq_ws_i(expected, actual) \
43     do { \
44       LPCWSTR value = (actual); \
45       ok(lstrcmpiW((expected), value) == 0, "Expected " #actual " to be L\"%s\" (" #expected ") is L\"%s\"\n", \
46           wine_dbgstr_w(expected), wine_dbgstr_w(value)); \
47     } while (0)
48 
49 static HINSTANCE hkernel32, hntdll;
50 static void   (WINAPI *pGetNativeSystemInfo)(LPSYSTEM_INFO);
51 static BOOL   (WINAPI *pGetSystemRegistryQuota)(PDWORD, PDWORD);
52 static BOOL   (WINAPI *pIsWow64Process)(HANDLE,PBOOL);
53 static LPVOID (WINAPI *pVirtualAllocEx)(HANDLE, LPVOID, SIZE_T, DWORD, DWORD);
54 static BOOL   (WINAPI *pVirtualFreeEx)(HANDLE, LPVOID, SIZE_T, DWORD);
55 static BOOL   (WINAPI *pQueryFullProcessImageNameA)(HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD lpdwSize);
56 static BOOL   (WINAPI *pQueryFullProcessImageNameW)(HANDLE hProcess, DWORD dwFlags, LPWSTR lpExeName, PDWORD lpdwSize);
57 static DWORD  (WINAPI *pK32GetProcessImageFileNameA)(HANDLE,LPSTR,DWORD);
58 static HANDLE (WINAPI *pCreateJobObjectW)(LPSECURITY_ATTRIBUTES sa, LPCWSTR name);
59 static BOOL   (WINAPI *pAssignProcessToJobObject)(HANDLE job, HANDLE process);
60 static BOOL   (WINAPI *pIsProcessInJob)(HANDLE process, HANDLE job, PBOOL result);
61 static BOOL   (WINAPI *pTerminateJobObject)(HANDLE job, UINT exit_code);
62 static BOOL   (WINAPI *pQueryInformationJobObject)(HANDLE job, JOBOBJECTINFOCLASS class, LPVOID info, DWORD len, LPDWORD ret_len);
63 static BOOL   (WINAPI *pSetInformationJobObject)(HANDLE job, JOBOBJECTINFOCLASS class, LPVOID info, DWORD len);
64 static HANDLE (WINAPI *pCreateIoCompletionPort)(HANDLE file, HANDLE existing_port, ULONG_PTR key, DWORD threads);
65 static BOOL   (WINAPI *pGetNumaProcessorNode)(UCHAR, PUCHAR);
66 static NTSTATUS (WINAPI *pNtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
67 static BOOL   (WINAPI *pProcessIdToSessionId)(DWORD,DWORD*);
68 static DWORD  (WINAPI *pWTSGetActiveConsoleSessionId)(void);
69 static HANDLE (WINAPI *pCreateToolhelp32Snapshot)(DWORD, DWORD);
70 static BOOL   (WINAPI *pProcess32First)(HANDLE, PROCESSENTRY32*);
71 static BOOL   (WINAPI *pProcess32Next)(HANDLE, PROCESSENTRY32*);
72 static BOOL   (WINAPI *pThread32First)(HANDLE, THREADENTRY32*);
73 static BOOL   (WINAPI *pThread32Next)(HANDLE, THREADENTRY32*);
74 static BOOL   (WINAPI *pGetLogicalProcessorInformationEx)(LOGICAL_PROCESSOR_RELATIONSHIP,SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*,DWORD*);
75 static SIZE_T (WINAPI *pGetLargePageMinimum)(void);
76 static BOOL   (WINAPI *pInitializeProcThreadAttributeList)(struct _PROC_THREAD_ATTRIBUTE_LIST*, DWORD, DWORD, SIZE_T*);
77 static BOOL   (WINAPI *pUpdateProcThreadAttribute)(struct _PROC_THREAD_ATTRIBUTE_LIST*, DWORD, DWORD_PTR, void *,SIZE_T,void*,SIZE_T*);
78 static void   (WINAPI *pDeleteProcThreadAttributeList)(struct _PROC_THREAD_ATTRIBUTE_LIST*);
79 static DWORD  (WINAPI *pGetActiveProcessorCount)(WORD);
80 
81 /* ############################### */
82 static char     base[MAX_PATH];
83 static char     selfname[MAX_PATH];
84 static char*    exename;
85 static char     resfile[MAX_PATH];
86 
87 static int      myARGC;
88 static char**   myARGV;
89 
90 /* As some environment variables get very long on Unix, we only test for
91  * the first 127 bytes.
92  * Note that increasing this value past 256 may exceed the buffer size
93  * limitations of the *Profile functions (at least on Wine).
94  */
95 #define MAX_LISTED_ENV_VAR      128
96 
97 /* ---------------- portable memory allocation thingie */
98 
99 static char     memory[1024*256];
100 static char*    memory_index = memory;
101 
102 static char*    grab_memory(size_t len)
103 {
104     char*       ret = memory_index;
105     /* align on dword */
106     len = (len + 3) & ~3;
107     memory_index += len;
108     assert(memory_index <= memory + sizeof(memory));
109     return ret;
110 }
111 
112 static void     release_memory(void)
113 {
114     memory_index = memory;
115 }
116 
117 /* ---------------- simplistic tool to encode/decode strings (to hide \ " ' and such) */
118 
119 static const char* encodeA(const char* str)
120 {
121     char*       ptr;
122     size_t      len,i;
123 
124     if (!str) return "";
125     len = strlen(str) + 1;
126     ptr = grab_memory(len * 2 + 1);
127     for (i = 0; i < len; i++)
128         sprintf(&ptr[i * 2], "%02x", (unsigned char)str[i]);
129     ptr[2 * len] = '\0';
130     return ptr;
131 }
132 
133 static const char* encodeW(const WCHAR* str)
134 {
135     char*       ptr;
136     size_t      len,i;
137 
138     if (!str) return "";
139     len = lstrlenW(str) + 1;
140     ptr = grab_memory(len * 4 + 1);
141     assert(ptr);
142     for (i = 0; i < len; i++)
143         sprintf(&ptr[i * 4], "%04x", (unsigned int)(unsigned short)str[i]);
144     ptr[4 * len] = '\0';
145     return ptr;
146 }
147 
148 static unsigned decode_char(char c)
149 {
150     if (c >= '0' && c <= '9') return c - '0';
151     if (c >= 'a' && c <= 'f') return c - 'a' + 10;
152     assert(c >= 'A' && c <= 'F');
153     return c - 'A' + 10;
154 }
155 
156 static char*    decodeA(const char* str)
157 {
158     char*       ptr;
159     size_t      len,i;
160 
161     len = strlen(str) / 2;
162     if (!len--) return NULL;
163     ptr = grab_memory(len + 1);
164     for (i = 0; i < len; i++)
165         ptr[i] = (decode_char(str[2 * i]) << 4) | decode_char(str[2 * i + 1]);
166     ptr[len] = '\0';
167     return ptr;
168 }
169 
170 /* This will be needed to decode Unicode strings saved by the child process
171  * when we test Unicode functions.
172  */
173 static WCHAR*   decodeW(const char* str)
174 {
175     size_t      len;
176     WCHAR*      ptr;
177     int         i;
178 
179     len = strlen(str) / 4;
180     if (!len--) return NULL;
181     ptr = (WCHAR*)grab_memory(len * 2 + 1);
182     for (i = 0; i < len; i++)
183         ptr[i] = (decode_char(str[4 * i]) << 12) |
184             (decode_char(str[4 * i + 1]) << 8) |
185             (decode_char(str[4 * i + 2]) << 4) |
186             (decode_char(str[4 * i + 3]) << 0);
187     ptr[len] = '\0';
188     return ptr;
189 }
190 
191 /******************************************************************
192  *		init
193  *
194  * generates basic information like:
195  *      base:           absolute path to curr dir
196  *      selfname:       the way to reinvoke ourselves
197  *      exename:        executable without the path
198  * function-pointers, which are not implemented in all windows versions
199  */
200 static BOOL init(void)
201 {
202     char *p;
203 
204     myARGC = winetest_get_mainargs( &myARGV );
205     if (!GetCurrentDirectoryA(sizeof(base), base)) return FALSE;
206     strcpy(selfname, myARGV[0]);
207 
208     /* Strip the path of selfname */
209     if ((p = strrchr(selfname, '\\')) != NULL) exename = p + 1;
210     else exename = selfname;
211 
212     if ((p = strrchr(exename, '/')) != NULL) exename = p + 1;
213 
214     hkernel32 = GetModuleHandleA("kernel32");
215     hntdll    = GetModuleHandleA("ntdll.dll");
216 
217     pNtQueryInformationProcess = (void *)GetProcAddress(hntdll, "NtQueryInformationProcess");
218 
219     pGetNativeSystemInfo = (void *) GetProcAddress(hkernel32, "GetNativeSystemInfo");
220     pGetSystemRegistryQuota = (void *) GetProcAddress(hkernel32, "GetSystemRegistryQuota");
221     pIsWow64Process = (void *) GetProcAddress(hkernel32, "IsWow64Process");
222     pVirtualAllocEx = (void *) GetProcAddress(hkernel32, "VirtualAllocEx");
223     pVirtualFreeEx = (void *) GetProcAddress(hkernel32, "VirtualFreeEx");
224     pQueryFullProcessImageNameA = (void *) GetProcAddress(hkernel32, "QueryFullProcessImageNameA");
225     pQueryFullProcessImageNameW = (void *) GetProcAddress(hkernel32, "QueryFullProcessImageNameW");
226     pK32GetProcessImageFileNameA = (void *) GetProcAddress(hkernel32, "K32GetProcessImageFileNameA");
227     pCreateJobObjectW = (void *)GetProcAddress(hkernel32, "CreateJobObjectW");
228     pAssignProcessToJobObject = (void *)GetProcAddress(hkernel32, "AssignProcessToJobObject");
229     pIsProcessInJob = (void *)GetProcAddress(hkernel32, "IsProcessInJob");
230     pTerminateJobObject = (void *)GetProcAddress(hkernel32, "TerminateJobObject");
231     pQueryInformationJobObject = (void *)GetProcAddress(hkernel32, "QueryInformationJobObject");
232     pSetInformationJobObject = (void *)GetProcAddress(hkernel32, "SetInformationJobObject");
233     pCreateIoCompletionPort = (void *)GetProcAddress(hkernel32, "CreateIoCompletionPort");
234     pGetNumaProcessorNode = (void *)GetProcAddress(hkernel32, "GetNumaProcessorNode");
235     pProcessIdToSessionId = (void *)GetProcAddress(hkernel32, "ProcessIdToSessionId");
236     pWTSGetActiveConsoleSessionId = (void *)GetProcAddress(hkernel32, "WTSGetActiveConsoleSessionId");
237     pCreateToolhelp32Snapshot = (void *)GetProcAddress(hkernel32, "CreateToolhelp32Snapshot");
238     pProcess32First = (void *)GetProcAddress(hkernel32, "Process32First");
239     pProcess32Next = (void *)GetProcAddress(hkernel32, "Process32Next");
240     pThread32First = (void *)GetProcAddress(hkernel32, "Thread32First");
241     pThread32Next = (void *)GetProcAddress(hkernel32, "Thread32Next");
242     pGetLogicalProcessorInformationEx = (void *)GetProcAddress(hkernel32, "GetLogicalProcessorInformationEx");
243     pGetLargePageMinimum = (void *)GetProcAddress(hkernel32, "GetLargePageMinimum");
244     pInitializeProcThreadAttributeList = (void *)GetProcAddress(hkernel32, "InitializeProcThreadAttributeList");
245     pUpdateProcThreadAttribute = (void *)GetProcAddress(hkernel32, "UpdateProcThreadAttribute");
246     pDeleteProcThreadAttributeList = (void *)GetProcAddress(hkernel32, "DeleteProcThreadAttributeList");
247     pGetActiveProcessorCount = (void *)GetProcAddress(hkernel32, "GetActiveProcessorCount");
248 
249     return TRUE;
250 }
251 
252 /******************************************************************
253  *		get_file_name
254  *
255  * generates an absolute file_name for temporary file
256  *
257  */
258 static void     get_file_name(char* buf)
259 {
260     char        path[MAX_PATH];
261 
262     buf[0] = '\0';
263     GetTempPathA(sizeof(path), path);
264     GetTempFileNameA(path, "wt", 0, buf);
265 }
266 
267 /******************************************************************
268  *		static void     childPrintf
269  *
270  */
271 static void WINETEST_PRINTF_ATTR(2,3) childPrintf(HANDLE h, const char* fmt, ...)
272 {
273     va_list     valist;
274     char        buffer[1024+4*MAX_LISTED_ENV_VAR];
275     DWORD       w;
276 
277     va_start(valist, fmt);
278     vsprintf(buffer, fmt, valist);
279     va_end(valist);
280     WriteFile(h, buffer, strlen(buffer), &w, NULL);
281 }
282 
283 
284 /******************************************************************
285  *		doChild
286  *
287  * output most of the information in the child process
288  */
289 static void     doChild(const char* file, const char* option)
290 {
291     RTL_USER_PROCESS_PARAMETERS *params = NtCurrentTeb()->Peb->ProcessParameters;
292     STARTUPINFOA        siA;
293     STARTUPINFOW        siW;
294     int                 i;
295     char                *ptrA, *ptrA_save;
296     WCHAR               *ptrW, *ptrW_save;
297     char                bufA[MAX_PATH];
298     WCHAR               bufW[MAX_PATH];
299     HANDLE              hFile = CreateFileA(file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
300     HANDLE              snapshot;
301     PROCESSENTRY32      pe;
302     BOOL ret;
303 
304     if (hFile == INVALID_HANDLE_VALUE) return;
305 
306     /* output of startup info (Ansi) */
307     GetStartupInfoA(&siA);
308     childPrintf(hFile,
309                 "[StartupInfoA]\ncb=%08u\nlpDesktop=%s\nlpTitle=%s\n"
310                 "dwX=%u\ndwY=%u\ndwXSize=%u\ndwYSize=%u\n"
311                 "dwXCountChars=%u\ndwYCountChars=%u\ndwFillAttribute=%u\n"
312                 "dwFlags=%u\nwShowWindow=%u\n"
313                 "hStdInput=%lu\nhStdOutput=%lu\nhStdError=%lu\n\n",
314                 siA.cb, encodeA(siA.lpDesktop), encodeA(siA.lpTitle),
315                 siA.dwX, siA.dwY, siA.dwXSize, siA.dwYSize,
316                 siA.dwXCountChars, siA.dwYCountChars, siA.dwFillAttribute,
317                 siA.dwFlags, siA.wShowWindow,
318                 (DWORD_PTR)siA.hStdInput, (DWORD_PTR)siA.hStdOutput, (DWORD_PTR)siA.hStdError);
319 
320     /* check the console handles in the TEB */
321     childPrintf(hFile, "[TEB]\nhStdInput=%lu\nhStdOutput=%lu\nhStdError=%lu\n\n",
322                 (DWORD_PTR)params->hStdInput, (DWORD_PTR)params->hStdOutput,
323                 (DWORD_PTR)params->hStdError);
324 
325     /* since GetStartupInfoW is only implemented in win2k,
326      * zero out before calling so we can notice the difference
327      */
328     memset(&siW, 0, sizeof(siW));
329     GetStartupInfoW(&siW);
330     childPrintf(hFile,
331                 "[StartupInfoW]\ncb=%08u\nlpDesktop=%s\nlpTitle=%s\n"
332                 "dwX=%u\ndwY=%u\ndwXSize=%u\ndwYSize=%u\n"
333                 "dwXCountChars=%u\ndwYCountChars=%u\ndwFillAttribute=%u\n"
334                 "dwFlags=%u\nwShowWindow=%u\n"
335                 "hStdInput=%lu\nhStdOutput=%lu\nhStdError=%lu\n\n",
336                 siW.cb, encodeW(siW.lpDesktop), encodeW(siW.lpTitle),
337                 siW.dwX, siW.dwY, siW.dwXSize, siW.dwYSize,
338                 siW.dwXCountChars, siW.dwYCountChars, siW.dwFillAttribute,
339                 siW.dwFlags, siW.wShowWindow,
340                 (DWORD_PTR)siW.hStdInput, (DWORD_PTR)siW.hStdOutput, (DWORD_PTR)siW.hStdError);
341 
342     /* Arguments */
343     childPrintf(hFile, "[Arguments]\nargcA=%d\n", myARGC);
344     for (i = 0; i < myARGC; i++)
345     {
346         childPrintf(hFile, "argvA%d=%s\n", i, encodeA(myARGV[i]));
347     }
348     childPrintf(hFile, "CommandLineA=%s\n", encodeA(GetCommandLineA()));
349     childPrintf(hFile, "CommandLineW=%s\n\n", encodeW(GetCommandLineW()));
350 
351     /* output toolhelp information */
352     snapshot = pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
353     ok(snapshot != INVALID_HANDLE_VALUE, "CreateToolhelp32Snapshot failed %u\n", GetLastError());
354     memset(&pe, 0, sizeof(pe));
355     pe.dwSize = sizeof(pe);
356     if (pProcess32First(snapshot, &pe))
357     {
358         while (pe.th32ProcessID != GetCurrentProcessId())
359             if (!pProcess32Next(snapshot, &pe)) break;
360     }
361     CloseHandle(snapshot);
362     ok(pe.th32ProcessID == GetCurrentProcessId(), "failed to find current process in snapshot\n");
363     childPrintf(hFile,
364                 "[Toolhelp]\ncntUsage=%u\nth32DefaultHeapID=%lu\n"
365                 "th32ModuleID=%u\ncntThreads=%u\nth32ParentProcessID=%u\n"
366                 "pcPriClassBase=%u\ndwFlags=%u\nszExeFile=%s\n\n",
367                 pe.cntUsage, pe.th32DefaultHeapID, pe.th32ModuleID,
368                 pe.cntThreads, pe.th32ParentProcessID, pe.pcPriClassBase,
369                 pe.dwFlags, encodeA(pe.szExeFile));
370 
371     /* output of environment (Ansi) */
372     ptrA_save = ptrA = GetEnvironmentStringsA();
373     if (ptrA)
374     {
375         char    env_var[MAX_LISTED_ENV_VAR];
376 
377         childPrintf(hFile, "[EnvironmentA]\n");
378         i = 0;
379         while (*ptrA)
380         {
381             lstrcpynA(env_var, ptrA, MAX_LISTED_ENV_VAR);
382             childPrintf(hFile, "env%d=%s\n", i, encodeA(env_var));
383             i++;
384             ptrA += strlen(ptrA) + 1;
385         }
386         childPrintf(hFile, "len=%d\n\n", i);
387         FreeEnvironmentStringsA(ptrA_save);
388     }
389 
390     /* output of environment (Unicode) */
391     ptrW_save = ptrW = GetEnvironmentStringsW();
392     if (ptrW)
393     {
394         WCHAR   env_var[MAX_LISTED_ENV_VAR];
395 
396         childPrintf(hFile, "[EnvironmentW]\n");
397         i = 0;
398         while (*ptrW)
399         {
400             lstrcpynW(env_var, ptrW, MAX_LISTED_ENV_VAR - 1);
401             env_var[MAX_LISTED_ENV_VAR - 1] = '\0';
402             childPrintf(hFile, "env%d=%s\n", i, encodeW(env_var));
403             i++;
404             ptrW += lstrlenW(ptrW) + 1;
405         }
406         childPrintf(hFile, "len=%d\n\n", i);
407         FreeEnvironmentStringsW(ptrW_save);
408     }
409 
410     childPrintf(hFile, "[Misc]\n");
411     if (GetCurrentDirectoryA(sizeof(bufA), bufA))
412         childPrintf(hFile, "CurrDirA=%s\n", encodeA(bufA));
413     if (GetCurrentDirectoryW(sizeof(bufW) / sizeof(bufW[0]), bufW))
414         childPrintf(hFile, "CurrDirW=%s\n", encodeW(bufW));
415     childPrintf(hFile, "\n");
416 
417     if (option && strcmp(option, "console") == 0)
418     {
419         CONSOLE_SCREEN_BUFFER_INFO	sbi;
420         HANDLE hConIn  = GetStdHandle(STD_INPUT_HANDLE);
421         HANDLE hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
422         DWORD modeIn, modeOut;
423 
424         childPrintf(hFile, "[Console]\n");
425         if (GetConsoleScreenBufferInfo(hConOut, &sbi))
426         {
427             childPrintf(hFile, "SizeX=%d\nSizeY=%d\nCursorX=%d\nCursorY=%d\nAttributes=%d\n",
428                         sbi.dwSize.X, sbi.dwSize.Y, sbi.dwCursorPosition.X, sbi.dwCursorPosition.Y, sbi.wAttributes);
429             childPrintf(hFile, "winLeft=%d\nwinTop=%d\nwinRight=%d\nwinBottom=%d\n",
430                         sbi.srWindow.Left, sbi.srWindow.Top, sbi.srWindow.Right, sbi.srWindow.Bottom);
431             childPrintf(hFile, "maxWinWidth=%d\nmaxWinHeight=%d\n",
432                         sbi.dwMaximumWindowSize.X, sbi.dwMaximumWindowSize.Y);
433         }
434         childPrintf(hFile, "InputCP=%d\nOutputCP=%d\n",
435                     GetConsoleCP(), GetConsoleOutputCP());
436         if (GetConsoleMode(hConIn, &modeIn))
437             childPrintf(hFile, "InputMode=%u\n", modeIn);
438         if (GetConsoleMode(hConOut, &modeOut))
439             childPrintf(hFile, "OutputMode=%u\n", modeOut);
440 
441         /* now that we have written all relevant information, let's change it */
442         SetLastError(0xdeadbeef);
443         ret = SetConsoleCP(1252);
444         if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
445         {
446             win_skip("Setting the codepage is not implemented\n");
447         }
448         else
449         {
450             ok(ret, "Setting CP\n");
451             ok(SetConsoleOutputCP(1252), "Setting SB CP\n");
452         }
453 
454         ret = SetConsoleMode(hConIn, modeIn ^ 1);
455         ok( ret, "Setting mode (%d)\n", GetLastError());
456         ret = SetConsoleMode(hConOut, modeOut ^ 1);
457         ok( ret, "Setting mode (%d)\n", GetLastError());
458         sbi.dwCursorPosition.X ^= 1;
459         sbi.dwCursorPosition.Y ^= 1;
460         ret = SetConsoleCursorPosition(hConOut, sbi.dwCursorPosition);
461         ok( ret, "Setting cursor position (%d)\n", GetLastError());
462     }
463     if (option && strcmp(option, "stdhandle") == 0)
464     {
465         HANDLE hStdIn  = GetStdHandle(STD_INPUT_HANDLE);
466         HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
467 
468         if (hStdIn != INVALID_HANDLE_VALUE || hStdOut != INVALID_HANDLE_VALUE)
469         {
470             char buf[1024];
471             DWORD r, w;
472 
473             ok(ReadFile(hStdIn, buf, sizeof(buf), &r, NULL) && r > 0, "Reading message from input pipe\n");
474             childPrintf(hFile, "[StdHandle]\nmsg=%s\n\n", encodeA(buf));
475             ok(WriteFile(hStdOut, buf, r, &w, NULL) && w == r, "Writing message to output pipe\n");
476         }
477     }
478 
479     if (option && strcmp(option, "exit_code") == 0)
480     {
481         childPrintf(hFile, "[ExitCode]\nvalue=%d\n\n", 123);
482         CloseHandle(hFile);
483         ExitProcess(123);
484     }
485 
486     CloseHandle(hFile);
487 }
488 
489 static char* getChildString(const char* sect, const char* key)
490 {
491     char        buf[1024+4*MAX_LISTED_ENV_VAR];
492     char*       ret;
493 
494     GetPrivateProfileStringA(sect, key, "-", buf, sizeof(buf), resfile);
495     if (buf[0] == '\0' || (buf[0] == '-' && buf[1] == '\0')) return NULL;
496     assert(!(strlen(buf) & 1));
497     ret = decodeA(buf);
498     return ret;
499 }
500 
501 static WCHAR* getChildStringW(const char* sect, const char* key)
502 {
503     char        buf[1024+4*MAX_LISTED_ENV_VAR];
504     WCHAR*       ret;
505 
506     GetPrivateProfileStringA(sect, key, "-", buf, sizeof(buf), resfile);
507     if (buf[0] == '\0' || (buf[0] == '-' && buf[1] == '\0')) return NULL;
508     assert(!(strlen(buf) & 1));
509     ret = decodeW(buf);
510     return ret;
511 }
512 
513 /* FIXME: this may be moved to the wtmain.c file, because it may be needed by
514  * others... (windows uses stricmp while Un*x uses strcasecmp...)
515  */
516 static int wtstrcasecmp(const char* p1, const char* p2)
517 {
518     char c1, c2;
519 
520     c1 = c2 = '@';
521     while (c1 == c2 && c1)
522     {
523         c1 = *p1++; c2 = *p2++;
524         if (c1 != c2)
525         {
526             c1 = toupper(c1); c2 = toupper(c2);
527         }
528     }
529     return c1 - c2;
530 }
531 
532 static int strCmp(const char* s1, const char* s2, BOOL sensitive)
533 {
534     if (!s1 && !s2) return 0;
535     if (!s2) return -1;
536     if (!s1) return 1;
537     return (sensitive) ? strcmp(s1, s2) : wtstrcasecmp(s1, s2);
538 }
539 
540 static void ok_child_string( int line, const char *sect, const char *key,
541                              const char *expect, int sensitive )
542 {
543     char* result = getChildString( sect, key );
544     ok_(__FILE__, line)( strCmp(result, expect, sensitive) == 0, "%s:%s expected '%s', got '%s'\n",
545                          sect, key, expect ? expect : "(null)", result );
546 }
547 
548 static void ok_child_stringWA( int line, const char *sect, const char *key,
549                              const char *expect, int sensitive )
550 {
551     WCHAR* expectW;
552     CHAR* resultA;
553     DWORD len;
554     WCHAR* result = getChildStringW( sect, key );
555 
556     len = MultiByteToWideChar( CP_ACP, 0, expect, -1, NULL, 0);
557     expectW = HeapAlloc(GetProcessHeap(),0,len*sizeof(WCHAR));
558     MultiByteToWideChar( CP_ACP, 0, expect, -1, expectW, len);
559 
560     len = WideCharToMultiByte( CP_ACP, 0, result, -1, NULL, 0, NULL, NULL);
561     resultA = HeapAlloc(GetProcessHeap(),0,len*sizeof(CHAR));
562     WideCharToMultiByte( CP_ACP, 0, result, -1, resultA, len, NULL, NULL);
563 
564     if (sensitive)
565         ok_(__FILE__, line)( lstrcmpW(result, expectW) == 0, "%s:%s expected '%s', got '%s'\n",
566                          sect, key, expect ? expect : "(null)", resultA );
567     else
568         ok_(__FILE__, line)( lstrcmpiW(result, expectW) == 0, "%s:%s expected '%s', got '%s'\n",
569                          sect, key, expect ? expect : "(null)", resultA );
570     HeapFree(GetProcessHeap(),0,expectW);
571     HeapFree(GetProcessHeap(),0,resultA);
572 }
573 
574 static void ok_child_int( int line, const char *sect, const char *key, UINT expect )
575 {
576     UINT result = GetPrivateProfileIntA( sect, key, !expect, resfile );
577     ok_(__FILE__, line)( result == expect, "%s:%s expected %u, but got %u\n", sect, key, expect, result );
578 }
579 
580 #define okChildString(sect, key, expect) ok_child_string(__LINE__, (sect), (key), (expect), 1 )
581 #define okChildIString(sect, key, expect) ok_child_string(__LINE__, (sect), (key), (expect), 0 )
582 #define okChildStringWA(sect, key, expect) ok_child_stringWA(__LINE__, (sect), (key), (expect), 1 )
583 #define okChildInt(sect, key, expect) ok_child_int(__LINE__, (sect), (key), (expect))
584 
585 static void test_Startup(void)
586 {
587     char                buffer[MAX_PATH];
588     PROCESS_INFORMATION	info;
589     STARTUPINFOA	startup,si;
590     char *result;
591     static CHAR title[]   = "I'm the title string",
592                 desktop[] = "winsta0\\default",
593                 empty[]   = "";
594 
595     /* let's start simplistic */
596     memset(&startup, 0, sizeof(startup));
597     startup.cb = sizeof(startup);
598     startup.dwFlags = STARTF_USESHOWWINDOW;
599     startup.wShowWindow = SW_SHOWNORMAL;
600 
601     get_file_name(resfile);
602     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
603     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
604     /* wait for child to terminate */
605     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
606     /* child process has changed result file, so let profile functions know about it */
607     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
608     CloseHandle(info.hThread);
609     CloseHandle(info.hProcess);
610 
611     GetStartupInfoA(&si);
612     okChildInt("StartupInfoA", "cb", startup.cb);
613     okChildString("StartupInfoA", "lpDesktop", si.lpDesktop);
614     okChildInt("StartupInfoA", "dwX", startup.dwX);
615     okChildInt("StartupInfoA", "dwY", startup.dwY);
616     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
617     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
618     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
619     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
620     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
621     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
622     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
623     release_memory();
624     DeleteFileA(resfile);
625 
626     /* not so simplistic now */
627     memset(&startup, 0, sizeof(startup));
628     startup.cb = sizeof(startup);
629     startup.dwFlags = STARTF_USESHOWWINDOW;
630     startup.wShowWindow = SW_SHOWNORMAL;
631     startup.lpTitle = title;
632     startup.lpDesktop = desktop;
633     startup.dwXCountChars = 0x12121212;
634     startup.dwYCountChars = 0x23232323;
635     startup.dwX = 0x34343434;
636     startup.dwY = 0x45454545;
637     startup.dwXSize = 0x56565656;
638     startup.dwYSize = 0x67676767;
639     startup.dwFillAttribute = 0xA55A;
640 
641     get_file_name(resfile);
642     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
643     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
644     /* wait for child to terminate */
645     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
646     /* child process has changed result file, so let profile functions know about it */
647     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
648     CloseHandle(info.hThread);
649     CloseHandle(info.hProcess);
650 
651     okChildInt("StartupInfoA", "cb", startup.cb);
652     okChildString("StartupInfoA", "lpDesktop", startup.lpDesktop);
653     okChildString("StartupInfoA", "lpTitle", startup.lpTitle);
654     okChildInt("StartupInfoA", "dwX", startup.dwX);
655     okChildInt("StartupInfoA", "dwY", startup.dwY);
656     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
657     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
658     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
659     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
660     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
661     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
662     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
663     release_memory();
664     DeleteFileA(resfile);
665 
666     /* not so simplistic now */
667     memset(&startup, 0, sizeof(startup));
668     startup.cb = sizeof(startup);
669     startup.dwFlags = STARTF_USESHOWWINDOW;
670     startup.wShowWindow = SW_SHOWNORMAL;
671     startup.lpTitle = title;
672     startup.lpDesktop = NULL;
673     startup.dwXCountChars = 0x12121212;
674     startup.dwYCountChars = 0x23232323;
675     startup.dwX = 0x34343434;
676     startup.dwY = 0x45454545;
677     startup.dwXSize = 0x56565656;
678     startup.dwYSize = 0x67676767;
679     startup.dwFillAttribute = 0xA55A;
680 
681     get_file_name(resfile);
682     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
683     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
684     /* wait for child to terminate */
685     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
686     /* child process has changed result file, so let profile functions know about it */
687     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
688     CloseHandle(info.hThread);
689     CloseHandle(info.hProcess);
690 
691     okChildInt("StartupInfoA", "cb", startup.cb);
692     okChildString("StartupInfoA", "lpDesktop", si.lpDesktop);
693     okChildString("StartupInfoA", "lpTitle", startup.lpTitle);
694     okChildInt("StartupInfoA", "dwX", startup.dwX);
695     okChildInt("StartupInfoA", "dwY", startup.dwY);
696     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
697     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
698     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
699     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
700     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
701     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
702     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
703     release_memory();
704     DeleteFileA(resfile);
705 
706     /* not so simplistic now */
707     memset(&startup, 0, sizeof(startup));
708     startup.cb = sizeof(startup);
709     startup.dwFlags = STARTF_USESHOWWINDOW;
710     startup.wShowWindow = SW_SHOWNORMAL;
711     startup.lpTitle = title;
712     startup.lpDesktop = empty;
713     startup.dwXCountChars = 0x12121212;
714     startup.dwYCountChars = 0x23232323;
715     startup.dwX = 0x34343434;
716     startup.dwY = 0x45454545;
717     startup.dwXSize = 0x56565656;
718     startup.dwYSize = 0x67676767;
719     startup.dwFillAttribute = 0xA55A;
720 
721     get_file_name(resfile);
722     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
723     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
724     /* wait for child to terminate */
725     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
726     /* child process has changed result file, so let profile functions know about it */
727     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
728     CloseHandle(info.hThread);
729     CloseHandle(info.hProcess);
730 
731     okChildInt("StartupInfoA", "cb", startup.cb);
732     okChildString("StartupInfoA", "lpDesktop", startup.lpDesktop);
733     okChildString("StartupInfoA", "lpTitle", startup.lpTitle);
734     okChildInt("StartupInfoA", "dwX", startup.dwX);
735     okChildInt("StartupInfoA", "dwY", startup.dwY);
736     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
737     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
738     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
739     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
740     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
741     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
742     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
743     release_memory();
744     DeleteFileA(resfile);
745 
746     /* not so simplistic now */
747     memset(&startup, 0, sizeof(startup));
748     startup.cb = sizeof(startup);
749     startup.dwFlags = STARTF_USESHOWWINDOW;
750     startup.wShowWindow = SW_SHOWNORMAL;
751     startup.lpTitle = NULL;
752     startup.lpDesktop = desktop;
753     startup.dwXCountChars = 0x12121212;
754     startup.dwYCountChars = 0x23232323;
755     startup.dwX = 0x34343434;
756     startup.dwY = 0x45454545;
757     startup.dwXSize = 0x56565656;
758     startup.dwYSize = 0x67676767;
759     startup.dwFillAttribute = 0xA55A;
760 
761     get_file_name(resfile);
762     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
763     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
764     /* wait for child to terminate */
765     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
766     /* child process has changed result file, so let profile functions know about it */
767     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
768     CloseHandle(info.hThread);
769     CloseHandle(info.hProcess);
770 
771     okChildInt("StartupInfoA", "cb", startup.cb);
772     okChildString("StartupInfoA", "lpDesktop", startup.lpDesktop);
773     result = getChildString( "StartupInfoA", "lpTitle" );
774     ok( broken(!result) || (result && !strCmp( result, selfname, 0 )),
775         "expected '%s' or null, got '%s'\n", selfname, result );
776     okChildInt("StartupInfoA", "dwX", startup.dwX);
777     okChildInt("StartupInfoA", "dwY", startup.dwY);
778     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
779     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
780     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
781     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
782     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
783     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
784     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
785     release_memory();
786     DeleteFileA(resfile);
787 
788     /* not so simplistic now */
789     memset(&startup, 0, sizeof(startup));
790     startup.cb = sizeof(startup);
791     startup.dwFlags = STARTF_USESHOWWINDOW;
792     startup.wShowWindow = SW_SHOWNORMAL;
793     startup.lpTitle = empty;
794     startup.lpDesktop = desktop;
795     startup.dwXCountChars = 0x12121212;
796     startup.dwYCountChars = 0x23232323;
797     startup.dwX = 0x34343434;
798     startup.dwY = 0x45454545;
799     startup.dwXSize = 0x56565656;
800     startup.dwYSize = 0x67676767;
801     startup.dwFillAttribute = 0xA55A;
802 
803     get_file_name(resfile);
804     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
805     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
806     /* wait for child to terminate */
807     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
808     /* child process has changed result file, so let profile functions know about it */
809     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
810     CloseHandle(info.hThread);
811     CloseHandle(info.hProcess);
812 
813     okChildInt("StartupInfoA", "cb", startup.cb);
814     okChildString("StartupInfoA", "lpDesktop", startup.lpDesktop);
815     okChildString("StartupInfoA", "lpTitle", startup.lpTitle);
816     okChildInt("StartupInfoA", "dwX", startup.dwX);
817     okChildInt("StartupInfoA", "dwY", startup.dwY);
818     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
819     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
820     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
821     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
822     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
823     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
824     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
825     release_memory();
826     DeleteFileA(resfile);
827 
828     /* not so simplistic now */
829     memset(&startup, 0, sizeof(startup));
830     startup.cb = sizeof(startup);
831     startup.dwFlags = STARTF_USESHOWWINDOW;
832     startup.wShowWindow = SW_SHOWNORMAL;
833     startup.lpTitle = empty;
834     startup.lpDesktop = empty;
835     startup.dwXCountChars = 0x12121212;
836     startup.dwYCountChars = 0x23232323;
837     startup.dwX = 0x34343434;
838     startup.dwY = 0x45454545;
839     startup.dwXSize = 0x56565656;
840     startup.dwYSize = 0x67676767;
841     startup.dwFillAttribute = 0xA55A;
842 
843     get_file_name(resfile);
844     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
845     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
846     /* wait for child to terminate */
847     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
848     /* child process has changed result file, so let profile functions know about it */
849     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
850     CloseHandle(info.hThread);
851     CloseHandle(info.hProcess);
852 
853     okChildInt("StartupInfoA", "cb", startup.cb);
854     okChildString("StartupInfoA", "lpDesktop", startup.lpDesktop);
855     okChildString("StartupInfoA", "lpTitle", startup.lpTitle);
856     okChildInt("StartupInfoA", "dwX", startup.dwX);
857     okChildInt("StartupInfoA", "dwY", startup.dwY);
858     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
859     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
860     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
861     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
862     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
863     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
864     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
865     release_memory();
866     DeleteFileA(resfile);
867 
868     /* TODO: test for A/W and W/A and W/W */
869 }
870 
871 static void test_CommandLine(void)
872 {
873     char                buffer[MAX_PATH], fullpath[MAX_PATH], *lpFilePart, *p;
874     char                buffer2[MAX_PATH];
875     PROCESS_INFORMATION	info;
876     STARTUPINFOA	startup;
877     BOOL                ret;
878 
879     memset(&startup, 0, sizeof(startup));
880     startup.cb = sizeof(startup);
881     startup.dwFlags = STARTF_USESHOWWINDOW;
882     startup.wShowWindow = SW_SHOWNORMAL;
883 
884     /* the basics */
885     get_file_name(resfile);
886     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\" \"C:\\Program Files\\my nice app.exe\"", selfname, resfile);
887     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
888     /* wait for child to terminate */
889     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
890     /* child process has changed result file, so let profile functions know about it */
891     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
892     CloseHandle(info.hThread);
893     CloseHandle(info.hProcess);
894 
895     okChildInt("Arguments", "argcA", 5);
896     okChildString("Arguments", "argvA4", "C:\\Program Files\\my nice app.exe");
897     okChildString("Arguments", "argvA5", NULL);
898     okChildString("Arguments", "CommandLineA", buffer);
899     release_memory();
900     DeleteFileA(resfile);
901 
902     memset(&startup, 0, sizeof(startup));
903     startup.cb = sizeof(startup);
904     startup.dwFlags = STARTF_USESHOWWINDOW;
905     startup.wShowWindow = SW_SHOWNORMAL;
906 
907     /* from Fran�ois */
908     get_file_name(resfile);
909     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\" \"a\\\"b\\\\\" c\\\" d", selfname, resfile);
910     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
911     /* wait for child to terminate */
912     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
913     /* child process has changed result file, so let profile functions know about it */
914     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
915     CloseHandle(info.hThread);
916     CloseHandle(info.hProcess);
917 
918     okChildInt("Arguments", "argcA", 7);
919     okChildString("Arguments", "argvA4", "a\"b\\");
920     okChildString("Arguments", "argvA5", "c\"");
921     okChildString("Arguments", "argvA6", "d");
922     okChildString("Arguments", "argvA7", NULL);
923     okChildString("Arguments", "CommandLineA", buffer);
924     release_memory();
925     DeleteFileA(resfile);
926 
927     /* Test for Bug1330 to show that XP doesn't change '/' to '\\' in argv[0]*/
928     get_file_name(resfile);
929     /* Use exename to avoid buffer containing things like 'C:' */
930     sprintf(buffer, "./%s tests/process.c dump \"%s\" \"a\\\"b\\\\\" c\\\" d", exename, resfile);
931     SetLastError(0xdeadbeef);
932     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
933     ok(ret, "CreateProcess (%s) failed : %d\n", buffer, GetLastError());
934     /* wait for child to terminate */
935     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
936     /* child process has changed result file, so let profile functions know about it */
937     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
938     CloseHandle(info.hThread);
939     CloseHandle(info.hProcess);
940     sprintf(buffer, "./%s", exename);
941     okChildString("Arguments", "argvA0", buffer);
942     release_memory();
943     DeleteFileA(resfile);
944 
945     get_file_name(resfile);
946     /* Use exename to avoid buffer containing things like 'C:' */
947     sprintf(buffer, ".\\%s tests/process.c dump \"%s\" \"a\\\"b\\\\\" c\\\" d", exename, resfile);
948     SetLastError(0xdeadbeef);
949     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
950     ok(ret, "CreateProcess (%s) failed : %d\n", buffer, GetLastError());
951     /* wait for child to terminate */
952     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
953     /* child process has changed result file, so let profile functions know about it */
954     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
955     CloseHandle(info.hThread);
956     CloseHandle(info.hProcess);
957     sprintf(buffer, ".\\%s", exename);
958     okChildString("Arguments", "argvA0", buffer);
959     release_memory();
960     DeleteFileA(resfile);
961 
962     get_file_name(resfile);
963     GetFullPathNameA(selfname, MAX_PATH, fullpath, &lpFilePart);
964     assert ( lpFilePart != 0);
965     *(lpFilePart -1 ) = 0;
966     p = strrchr(fullpath, '\\');
967     /* Use exename to avoid buffer containing things like 'C:' */
968     if (p) sprintf(buffer, "..%s/%s tests/process.c dump \"%s\" \"a\\\"b\\\\\" c\\\" d", p, exename, resfile);
969     else sprintf(buffer, "./%s tests/process.c dump \"%s\" \"a\\\"b\\\\\" c\\\" d", exename, resfile);
970     SetLastError(0xdeadbeef);
971     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
972     ok(ret, "CreateProcess (%s) failed : %d\n", buffer, GetLastError());
973     /* wait for child to terminate */
974     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
975     /* child process has changed result file, so let profile functions know about it */
976     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
977     CloseHandle(info.hThread);
978     CloseHandle(info.hProcess);
979     if (p) sprintf(buffer, "..%s/%s", p, exename);
980     else sprintf(buffer, "./%s", exename);
981     okChildString("Arguments", "argvA0", buffer);
982     release_memory();
983     DeleteFileA(resfile);
984 
985     /* Using AppName */
986     get_file_name(resfile);
987     GetFullPathNameA(selfname, MAX_PATH, fullpath, &lpFilePart);
988     assert ( lpFilePart != 0);
989     *(lpFilePart -1 ) = 0;
990     p = strrchr(fullpath, '\\');
991     /* Use exename to avoid buffer containing things like 'C:' */
992     if (p) sprintf(buffer, "..%s/%s", p, exename);
993     else sprintf(buffer, "./%s", exename);
994     sprintf(buffer2, "dummy tests/process.c dump \"%s\" \"a\\\"b\\\\\" c\\\" d", resfile);
995     SetLastError(0xdeadbeef);
996     ret = CreateProcessA(buffer, buffer2, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
997     ok(ret, "CreateProcess (%s) failed : %d\n", buffer, GetLastError());
998     /* wait for child to terminate */
999     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1000     /* child process has changed result file, so let profile functions know about it */
1001     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1002     CloseHandle(info.hThread);
1003     CloseHandle(info.hProcess);
1004     sprintf(buffer, "tests/process.c dump %s", resfile);
1005     okChildString("Arguments", "argvA0", "dummy");
1006     okChildString("Arguments", "CommandLineA", buffer2);
1007     okChildStringWA("Arguments", "CommandLineW", buffer2);
1008     release_memory();
1009     DeleteFileA(resfile);
1010 
1011     if (0) /* Test crashes on NT-based Windows. */
1012     {
1013         /* Test NULL application name and command line parameters. */
1014         SetLastError(0xdeadbeef);
1015         ret = CreateProcessA(NULL, NULL, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
1016         ok(!ret, "CreateProcessA unexpectedly succeeded\n");
1017         ok(GetLastError() == ERROR_INVALID_PARAMETER,
1018            "Expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
1019     }
1020 
1021     buffer[0] = '\0';
1022 
1023     /* Test empty application name parameter. */
1024     SetLastError(0xdeadbeef);
1025     ret = CreateProcessA(buffer, NULL, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
1026     ok(!ret, "CreateProcessA unexpectedly succeeded\n");
1027     ok(GetLastError() == ERROR_PATH_NOT_FOUND ||
1028        broken(GetLastError() == ERROR_FILE_NOT_FOUND) /* Win9x/WinME */ ||
1029        broken(GetLastError() == ERROR_ACCESS_DENIED) /* Win98 */,
1030        "Expected ERROR_PATH_NOT_FOUND, got %d\n", GetLastError());
1031 
1032     buffer2[0] = '\0';
1033 
1034     /* Test empty application name and command line parameters. */
1035     SetLastError(0xdeadbeef);
1036     ret = CreateProcessA(buffer, buffer2, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
1037     ok(!ret, "CreateProcessA unexpectedly succeeded\n");
1038     ok(GetLastError() == ERROR_PATH_NOT_FOUND ||
1039        broken(GetLastError() == ERROR_FILE_NOT_FOUND) /* Win9x/WinME */ ||
1040        broken(GetLastError() == ERROR_ACCESS_DENIED) /* Win98 */,
1041        "Expected ERROR_PATH_NOT_FOUND, got %d\n", GetLastError());
1042 
1043     /* Test empty command line parameter. */
1044     SetLastError(0xdeadbeef);
1045     ret = CreateProcessA(NULL, buffer2, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
1046     ok(!ret, "CreateProcessA unexpectedly succeeded\n");
1047     ok(GetLastError() == ERROR_FILE_NOT_FOUND ||
1048        GetLastError() == ERROR_PATH_NOT_FOUND /* NT4 */ ||
1049        GetLastError() == ERROR_BAD_PATHNAME /* Win98 */ ||
1050        GetLastError() == ERROR_INVALID_PARAMETER /* Win7 */,
1051        "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
1052 
1053     strcpy(buffer, "doesnotexist.exe");
1054     strcpy(buffer2, "does not exist.exe");
1055 
1056     /* Test nonexistent application name. */
1057     SetLastError(0xdeadbeef);
1058     ret = CreateProcessA(buffer, NULL, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
1059     ok(!ret, "CreateProcessA unexpectedly succeeded\n");
1060     ok(GetLastError() == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
1061 
1062     SetLastError(0xdeadbeef);
1063     ret = CreateProcessA(buffer2, NULL, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
1064     ok(!ret, "CreateProcessA unexpectedly succeeded\n");
1065     ok(GetLastError() == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
1066 
1067     /* Test nonexistent command line parameter. */
1068     SetLastError(0xdeadbeef);
1069     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
1070     ok(!ret, "CreateProcessA unexpectedly succeeded\n");
1071     ok(GetLastError() == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
1072 
1073     SetLastError(0xdeadbeef);
1074     ret = CreateProcessA(NULL, buffer2, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info);
1075     ok(!ret, "CreateProcessA unexpectedly succeeded\n");
1076     ok(GetLastError() == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
1077 }
1078 
1079 static void test_Directory(void)
1080 {
1081     char                buffer[MAX_PATH];
1082     PROCESS_INFORMATION	info;
1083     STARTUPINFOA	startup;
1084     char windir[MAX_PATH];
1085     static CHAR cmdline[] = "winver.exe";
1086 
1087     memset(&startup, 0, sizeof(startup));
1088     startup.cb = sizeof(startup);
1089     startup.dwFlags = STARTF_USESHOWWINDOW;
1090     startup.wShowWindow = SW_SHOWNORMAL;
1091 
1092     /* the basics */
1093     get_file_name(resfile);
1094     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
1095     GetWindowsDirectoryA( windir, sizeof(windir) );
1096     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, windir, &startup, &info), "CreateProcess\n");
1097     /* wait for child to terminate */
1098     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1099     /* child process has changed result file, so let profile functions know about it */
1100     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1101     CloseHandle(info.hThread);
1102     CloseHandle(info.hProcess);
1103 
1104     okChildIString("Misc", "CurrDirA", windir);
1105     release_memory();
1106     DeleteFileA(resfile);
1107 
1108     /* search PATH for the exe if directory is NULL */
1109     ok(CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
1110     ok(TerminateProcess(info.hProcess, 0), "Child process termination\n");
1111     CloseHandle(info.hThread);
1112     CloseHandle(info.hProcess);
1113 
1114     /* if any directory is provided, don't search PATH, error on bad directory */
1115     SetLastError(0xdeadbeef);
1116     memset(&info, 0, sizeof(info));
1117     ok(!CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, 0L,
1118                        NULL, "non\\existent\\directory", &startup, &info), "CreateProcess\n");
1119     ok(GetLastError() == ERROR_DIRECTORY, "Expected ERROR_DIRECTORY, got %d\n", GetLastError());
1120     ok(!TerminateProcess(info.hProcess, 0), "Child process should not exist\n");
1121 }
1122 
1123 static void test_Toolhelp(void)
1124 {
1125     char                buffer[MAX_PATH];
1126     STARTUPINFOA        startup;
1127     PROCESS_INFORMATION info;
1128     HANDLE              process, thread, snapshot;
1129     PROCESSENTRY32      pe;
1130     THREADENTRY32       te;
1131     DWORD               ret;
1132     int                 i;
1133 
1134     memset(&startup, 0, sizeof(startup));
1135     startup.cb = sizeof(startup);
1136     startup.dwFlags = STARTF_USESHOWWINDOW;
1137     startup.wShowWindow = SW_SHOWNORMAL;
1138 
1139     get_file_name(resfile);
1140     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
1141     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess failed\n");
1142     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1143     CloseHandle(info.hProcess);
1144     CloseHandle(info.hThread);
1145 
1146     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1147     okChildInt("Toolhelp", "cntUsage", 0);
1148     okChildInt("Toolhelp", "th32DefaultHeapID", 0);
1149     okChildInt("Toolhelp", "th32ModuleID", 0);
1150     okChildInt("Toolhelp", "th32ParentProcessID", GetCurrentProcessId());
1151     /* pcPriClassBase differs between Windows versions (either 6 or 8) */
1152     okChildInt("Toolhelp", "dwFlags", 0);
1153 
1154     release_memory();
1155     DeleteFileA(resfile);
1156 
1157     get_file_name(resfile);
1158     sprintf(buffer, "\"%s\" tests/process.c nested \"%s\"", selfname, resfile);
1159     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess failed\n");
1160     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1161 
1162     process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, info.dwProcessId);
1163     ok(process != NULL, "OpenProcess failed %u\n", GetLastError());
1164     CloseHandle(process);
1165 
1166     CloseHandle(info.hProcess);
1167     CloseHandle(info.hThread);
1168 
1169     for (i = 0; i < 20; i++)
1170     {
1171         SetLastError(0xdeadbeef);
1172         process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, info.dwProcessId);
1173         ok(process || GetLastError() == ERROR_INVALID_PARAMETER, "OpenProcess failed %u\n", GetLastError());
1174         if (!process) break;
1175         CloseHandle(process);
1176         Sleep(100);
1177     }
1178     /* The following test fails randomly on some Windows versions, but Gothic 2 depends on it */
1179     ok(i < 20 || broken(i == 20), "process object not released\n");
1180 
1181     snapshot = pCreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
1182     ok(snapshot != INVALID_HANDLE_VALUE, "CreateToolhelp32Snapshot failed %u\n", GetLastError());
1183     memset(&pe, 0, sizeof(pe));
1184     pe.dwSize = sizeof(pe);
1185     if (pProcess32First(snapshot, &pe))
1186     {
1187         while (pe.th32ParentProcessID != info.dwProcessId)
1188             if (!pProcess32Next(snapshot, &pe)) break;
1189     }
1190     CloseHandle(snapshot);
1191     ok(pe.th32ParentProcessID == info.dwProcessId, "failed to find nested child process\n");
1192 
1193     process = OpenProcess(PROCESS_ALL_ACCESS_NT4, FALSE, pe.th32ProcessID);
1194     ok(process != NULL, "OpenProcess failed %u\n", GetLastError());
1195 
1196     snapshot = pCreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
1197     ok(snapshot != INVALID_HANDLE_VALUE, "CreateToolhelp32Snapshot failed %u\n", GetLastError());
1198     memset(&te, 0, sizeof(te));
1199     te.dwSize = sizeof(te);
1200     if (pThread32First(snapshot, &te))
1201     {
1202         while (te.th32OwnerProcessID != pe.th32ProcessID)
1203             if (!pThread32Next(snapshot, &te)) break;
1204     }
1205     CloseHandle(snapshot);
1206     ok(te.th32OwnerProcessID == pe.th32ProcessID, "failed to find suspended thread\n");
1207 
1208     thread = OpenThread(THREAD_ALL_ACCESS_NT4, FALSE, te.th32ThreadID);
1209     ok(thread != NULL, "OpenThread failed %u\n", GetLastError());
1210     ret = ResumeThread(thread);
1211     ok(ret == 1, "expected 1, got %u\n", ret);
1212     CloseHandle(thread);
1213 
1214     ok(WaitForSingleObject(process, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1215     CloseHandle(process);
1216 
1217     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1218     okChildInt("Toolhelp", "cntUsage", 0);
1219     okChildInt("Toolhelp", "th32DefaultHeapID", 0);
1220     okChildInt("Toolhelp", "th32ModuleID", 0);
1221     okChildInt("Toolhelp", "th32ParentProcessID", info.dwProcessId);
1222     /* pcPriClassBase differs between Windows versions (either 6 or 8) */
1223     okChildInt("Toolhelp", "dwFlags", 0);
1224 
1225     release_memory();
1226     DeleteFileA(resfile);
1227 }
1228 
1229 static BOOL is_str_env_drive_dir(const char* str)
1230 {
1231     return str[0] == '=' && str[1] >= 'A' && str[1] <= 'Z' && str[2] == ':' &&
1232         str[3] == '=' && str[4] == str[1];
1233 }
1234 
1235 /* compared expected child's environment (in gesA) from actual
1236  * environment our child got
1237  */
1238 static void cmpEnvironment(const char* gesA)
1239 {
1240     int                 i, clen;
1241     const char*         ptrA;
1242     char*               res;
1243     char                key[32];
1244     BOOL                found;
1245 
1246     clen = GetPrivateProfileIntA("EnvironmentA", "len", 0, resfile);
1247 
1248     /* now look each parent env in child */
1249     if ((ptrA = gesA) != NULL)
1250     {
1251         while (*ptrA)
1252         {
1253             for (i = 0; i < clen; i++)
1254             {
1255                 sprintf(key, "env%d", i);
1256                 res = getChildString("EnvironmentA", key);
1257                 if (strncmp(ptrA, res, MAX_LISTED_ENV_VAR - 1) == 0)
1258                     break;
1259             }
1260             found = i < clen;
1261             ok(found, "Parent-env string %s isn't in child process\n", ptrA);
1262 
1263             ptrA += strlen(ptrA) + 1;
1264             release_memory();
1265         }
1266     }
1267     /* and each child env in parent */
1268     for (i = 0; i < clen; i++)
1269     {
1270         sprintf(key, "env%d", i);
1271         res = getChildString("EnvironmentA", key);
1272         if ((ptrA = gesA) != NULL)
1273         {
1274             while (*ptrA)
1275             {
1276                 if (strncmp(res, ptrA, MAX_LISTED_ENV_VAR - 1) == 0)
1277                     break;
1278                 ptrA += strlen(ptrA) + 1;
1279             }
1280             if (!*ptrA) ptrA = NULL;
1281         }
1282 
1283         if (!is_str_env_drive_dir(res))
1284         {
1285             found = ptrA != NULL;
1286             ok(found, "Child-env string %s isn't in parent process\n", res);
1287         }
1288         /* else => should also test we get the right per drive default directory here... */
1289     }
1290 }
1291 
1292 static void test_Environment(void)
1293 {
1294     char                buffer[MAX_PATH];
1295     PROCESS_INFORMATION	info;
1296     STARTUPINFOA	startup;
1297     char                *child_env;
1298     int                 child_env_len;
1299     char                *ptr;
1300     char                *ptr2;
1301     char                *env;
1302     int                 slen;
1303 
1304     memset(&startup, 0, sizeof(startup));
1305     startup.cb = sizeof(startup);
1306     startup.dwFlags = STARTF_USESHOWWINDOW;
1307     startup.wShowWindow = SW_SHOWNORMAL;
1308 
1309     /* the basics */
1310     get_file_name(resfile);
1311     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
1312     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, NULL, NULL, &startup, &info), "CreateProcess\n");
1313     /* wait for child to terminate */
1314     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1315     /* child process has changed result file, so let profile functions know about it */
1316     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1317 
1318     env = GetEnvironmentStringsA();
1319     cmpEnvironment(env);
1320     release_memory();
1321     DeleteFileA(resfile);
1322 
1323     memset(&startup, 0, sizeof(startup));
1324     startup.cb = sizeof(startup);
1325     startup.dwFlags = STARTF_USESHOWWINDOW;
1326     startup.wShowWindow = SW_SHOWNORMAL;
1327 
1328     /* the basics */
1329     get_file_name(resfile);
1330     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
1331 
1332     child_env_len = 0;
1333     ptr = env;
1334     while(*ptr)
1335     {
1336         slen = strlen(ptr)+1;
1337         child_env_len += slen;
1338         ptr += slen;
1339     }
1340     /* Add space for additional environment variables */
1341     child_env_len += 256;
1342     child_env = HeapAlloc(GetProcessHeap(), 0, child_env_len);
1343 
1344     ptr = child_env;
1345     sprintf(ptr, "=%c:=%s", 'C', "C:\\FOO\\BAR");
1346     ptr += strlen(ptr) + 1;
1347     strcpy(ptr, "PATH=C:\\WINDOWS;C:\\WINDOWS\\SYSTEM;C:\\MY\\OWN\\DIR");
1348     ptr += strlen(ptr) + 1;
1349     strcpy(ptr, "FOO=BAR");
1350     ptr += strlen(ptr) + 1;
1351     strcpy(ptr, "BAR=FOOBAR");
1352     ptr += strlen(ptr) + 1;
1353     /* copy all existing variables except:
1354      * - WINELOADER
1355      * - PATH (already set above)
1356      * - the directory definitions (=[A-Z]:=)
1357      */
1358     for (ptr2 = env; *ptr2; ptr2 += strlen(ptr2) + 1)
1359     {
1360         if (strncmp(ptr2, "PATH=", 5) != 0 &&
1361             strncmp(ptr2, "WINELOADER=", 11) != 0 &&
1362             !is_str_env_drive_dir(ptr2))
1363         {
1364             strcpy(ptr, ptr2);
1365             ptr += strlen(ptr) + 1;
1366         }
1367     }
1368     *ptr = '\0';
1369     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0L, child_env, NULL, &startup, &info), "CreateProcess\n");
1370     /* wait for child to terminate */
1371     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1372     /* child process has changed result file, so let profile functions know about it */
1373     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1374 
1375     cmpEnvironment(child_env);
1376 
1377     HeapFree(GetProcessHeap(), 0, child_env);
1378     FreeEnvironmentStringsA(env);
1379     release_memory();
1380     DeleteFileA(resfile);
1381 }
1382 
1383 static  void    test_SuspendFlag(void)
1384 {
1385     char                buffer[MAX_PATH];
1386     PROCESS_INFORMATION	info;
1387     STARTUPINFOA       startup, us;
1388     DWORD               exit_status;
1389     char *result;
1390 
1391     /* let's start simplistic */
1392     memset(&startup, 0, sizeof(startup));
1393     startup.cb = sizeof(startup);
1394     startup.dwFlags = STARTF_USESHOWWINDOW;
1395     startup.wShowWindow = SW_SHOWNORMAL;
1396 
1397     get_file_name(resfile);
1398     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
1399     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &startup, &info), "CreateProcess\n");
1400 
1401     ok(GetExitCodeThread(info.hThread, &exit_status) && exit_status == STILL_ACTIVE, "thread still running\n");
1402     Sleep(8000);
1403     ok(GetExitCodeThread(info.hThread, &exit_status) && exit_status == STILL_ACTIVE, "thread still running\n");
1404     ok(ResumeThread(info.hThread) == 1, "Resuming thread\n");
1405 
1406     /* wait for child to terminate */
1407     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1408     /* child process has changed result file, so let profile functions know about it */
1409     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1410 
1411     GetStartupInfoA(&us);
1412 
1413     okChildInt("StartupInfoA", "cb", startup.cb);
1414     okChildString("StartupInfoA", "lpDesktop", us.lpDesktop);
1415     result = getChildString( "StartupInfoA", "lpTitle" );
1416     ok( broken(!result) || (result && !strCmp( result, selfname, 0 )),
1417         "expected '%s' or null, got '%s'\n", selfname, result );
1418     okChildInt("StartupInfoA", "dwX", startup.dwX);
1419     okChildInt("StartupInfoA", "dwY", startup.dwY);
1420     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
1421     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
1422     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
1423     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
1424     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
1425     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
1426     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
1427     release_memory();
1428     DeleteFileA(resfile);
1429 }
1430 
1431 static  void    test_DebuggingFlag(void)
1432 {
1433     char                buffer[MAX_PATH];
1434     void               *processbase = NULL;
1435     PROCESS_INFORMATION	info;
1436     STARTUPINFOA       startup, us;
1437     DEBUG_EVENT         de;
1438     unsigned            dbg = 0;
1439     char *result;
1440 
1441     /* let's start simplistic */
1442     memset(&startup, 0, sizeof(startup));
1443     startup.cb = sizeof(startup);
1444     startup.dwFlags = STARTF_USESHOWWINDOW;
1445     startup.wShowWindow = SW_SHOWNORMAL;
1446 
1447     get_file_name(resfile);
1448     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
1449     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &startup, &info), "CreateProcess\n");
1450 
1451     /* get all startup events up to the entry point break exception */
1452     do
1453     {
1454         ok(WaitForDebugEvent(&de, INFINITE), "reading debug event\n");
1455         ContinueDebugEvent(de.dwProcessId, de.dwThreadId, DBG_CONTINUE);
1456         if (!dbg)
1457         {
1458             ok(de.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT,
1459                "first event: %d\n", de.dwDebugEventCode);
1460             processbase = de.u.CreateProcessInfo.lpBaseOfImage;
1461         }
1462         if (de.dwDebugEventCode != EXCEPTION_DEBUG_EVENT) dbg++;
1463         ok(de.dwDebugEventCode != LOAD_DLL_DEBUG_EVENT ||
1464            de.u.LoadDll.lpBaseOfDll != processbase, "got LOAD_DLL for main module\n");
1465     } while (de.dwDebugEventCode != EXIT_PROCESS_DEBUG_EVENT);
1466 
1467     ok(dbg, "I have seen a debug event\n");
1468     /* wait for child to terminate */
1469     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1470     /* child process has changed result file, so let profile functions know about it */
1471     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1472 
1473     GetStartupInfoA(&us);
1474 
1475     okChildInt("StartupInfoA", "cb", startup.cb);
1476     okChildString("StartupInfoA", "lpDesktop", us.lpDesktop);
1477     result = getChildString( "StartupInfoA", "lpTitle" );
1478     ok( broken(!result) || (result && !strCmp( result, selfname, 0 )),
1479         "expected '%s' or null, got '%s'\n", selfname, result );
1480     okChildInt("StartupInfoA", "dwX", startup.dwX);
1481     okChildInt("StartupInfoA", "dwY", startup.dwY);
1482     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
1483     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
1484     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
1485     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
1486     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
1487     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
1488     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
1489     release_memory();
1490     DeleteFileA(resfile);
1491 }
1492 
1493 static BOOL is_console(HANDLE h)
1494 {
1495     return h != INVALID_HANDLE_VALUE && ((ULONG_PTR)h & 3) == 3;
1496 }
1497 
1498 static void test_Console(void)
1499 {
1500     char                buffer[MAX_PATH];
1501     PROCESS_INFORMATION	info;
1502     STARTUPINFOA       startup, us;
1503     SECURITY_ATTRIBUTES sa;
1504     CONSOLE_SCREEN_BUFFER_INFO	sbi, sbiC;
1505     DWORD               modeIn, modeOut, modeInC, modeOutC;
1506     DWORD               cpIn, cpOut, cpInC, cpOutC;
1507     DWORD               w;
1508     HANDLE              hChildIn, hChildInInh, hChildOut, hChildOutInh, hParentIn, hParentOut;
1509     const char*         msg = "This is a std-handle inheritance test.";
1510     unsigned            msg_len;
1511     BOOL                run_tests = TRUE;
1512     char *result;
1513 
1514     memset(&startup, 0, sizeof(startup));
1515     startup.cb = sizeof(startup);
1516     startup.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
1517     startup.wShowWindow = SW_SHOWNORMAL;
1518 
1519     sa.nLength = sizeof(sa);
1520     sa.lpSecurityDescriptor = NULL;
1521     sa.bInheritHandle = TRUE;
1522 
1523     startup.hStdInput = CreateFileA("CONIN$", GENERIC_READ|GENERIC_WRITE, 0, &sa, OPEN_EXISTING, 0, 0);
1524     startup.hStdOutput = CreateFileA("CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, &sa, OPEN_EXISTING, 0, 0);
1525 
1526     /* first, we need to be sure we're attached to a console */
1527     if (!is_console(startup.hStdInput) || !is_console(startup.hStdOutput))
1528     {
1529         /* we're not attached to a console, let's do it */
1530         AllocConsole();
1531         startup.hStdInput = CreateFileA("CONIN$", GENERIC_READ|GENERIC_WRITE, 0, &sa, OPEN_EXISTING, 0, 0);
1532         startup.hStdOutput = CreateFileA("CONOUT$", GENERIC_READ|GENERIC_WRITE, 0, &sa, OPEN_EXISTING, 0, 0);
1533     }
1534     /* now verify everything's ok */
1535     ok(startup.hStdInput != INVALID_HANDLE_VALUE, "Opening ConIn\n");
1536     ok(startup.hStdOutput != INVALID_HANDLE_VALUE, "Opening ConOut\n");
1537     startup.hStdError = startup.hStdOutput;
1538 
1539     ok(GetConsoleScreenBufferInfo(startup.hStdOutput, &sbi), "Getting sb info\n");
1540     ok(GetConsoleMode(startup.hStdInput, &modeIn), "Getting console in mode\n");
1541     ok(GetConsoleMode(startup.hStdOutput, &modeOut), "Getting console out mode\n");
1542     cpIn = GetConsoleCP();
1543     cpOut = GetConsoleOutputCP();
1544 
1545     get_file_name(resfile);
1546     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\" console", selfname, resfile);
1547     ok(CreateProcessA(NULL, buffer, NULL, NULL, TRUE, 0, NULL, NULL, &startup, &info), "CreateProcess\n");
1548 
1549     /* wait for child to terminate */
1550     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1551     /* child process has changed result file, so let profile functions know about it */
1552     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1553 
1554     /* now get the modification the child has made, and resets parents expected values */
1555     ok(GetConsoleScreenBufferInfo(startup.hStdOutput, &sbiC), "Getting sb info\n");
1556     ok(GetConsoleMode(startup.hStdInput, &modeInC), "Getting console in mode\n");
1557     ok(GetConsoleMode(startup.hStdOutput, &modeOutC), "Getting console out mode\n");
1558 
1559     SetConsoleMode(startup.hStdInput, modeIn);
1560     SetConsoleMode(startup.hStdOutput, modeOut);
1561 
1562     cpInC = GetConsoleCP();
1563     cpOutC = GetConsoleOutputCP();
1564 
1565     /* Try to set invalid CP */
1566     SetLastError(0xdeadbeef);
1567     ok(!SetConsoleCP(0), "Shouldn't succeed\n");
1568     ok(GetLastError()==ERROR_INVALID_PARAMETER ||
1569        broken(GetLastError() == ERROR_CALL_NOT_IMPLEMENTED), /* win9x */
1570        "GetLastError: expecting %u got %u\n",
1571        ERROR_INVALID_PARAMETER, GetLastError());
1572     if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1573         run_tests = FALSE;
1574 
1575 
1576     SetLastError(0xdeadbeef);
1577     ok(!SetConsoleOutputCP(0), "Shouldn't succeed\n");
1578     ok(GetLastError()==ERROR_INVALID_PARAMETER ||
1579        broken(GetLastError() == ERROR_CALL_NOT_IMPLEMENTED), /* win9x */
1580        "GetLastError: expecting %u got %u\n",
1581        ERROR_INVALID_PARAMETER, GetLastError());
1582 
1583     SetConsoleCP(cpIn);
1584     SetConsoleOutputCP(cpOut);
1585 
1586     GetStartupInfoA(&us);
1587 
1588     okChildInt("StartupInfoA", "cb", startup.cb);
1589     okChildString("StartupInfoA", "lpDesktop", us.lpDesktop);
1590     result = getChildString( "StartupInfoA", "lpTitle" );
1591     ok( broken(!result) || (result && !strCmp( result, selfname, 0 )),
1592         "expected '%s' or null, got '%s'\n", selfname, result );
1593     okChildInt("StartupInfoA", "dwX", startup.dwX);
1594     okChildInt("StartupInfoA", "dwY", startup.dwY);
1595     okChildInt("StartupInfoA", "dwXSize", startup.dwXSize);
1596     okChildInt("StartupInfoA", "dwYSize", startup.dwYSize);
1597     okChildInt("StartupInfoA", "dwXCountChars", startup.dwXCountChars);
1598     okChildInt("StartupInfoA", "dwYCountChars", startup.dwYCountChars);
1599     okChildInt("StartupInfoA", "dwFillAttribute", startup.dwFillAttribute);
1600     okChildInt("StartupInfoA", "dwFlags", startup.dwFlags);
1601     okChildInt("StartupInfoA", "wShowWindow", startup.wShowWindow);
1602 
1603     /* check child correctly inherited the console */
1604     okChildInt("StartupInfoA", "hStdInput", (DWORD_PTR)startup.hStdInput);
1605     okChildInt("StartupInfoA", "hStdOutput", (DWORD_PTR)startup.hStdOutput);
1606     okChildInt("StartupInfoA", "hStdError", (DWORD_PTR)startup.hStdError);
1607     okChildInt("Console", "SizeX", (DWORD)sbi.dwSize.X);
1608     okChildInt("Console", "SizeY", (DWORD)sbi.dwSize.Y);
1609     okChildInt("Console", "CursorX", (DWORD)sbi.dwCursorPosition.X);
1610     okChildInt("Console", "CursorY", (DWORD)sbi.dwCursorPosition.Y);
1611     okChildInt("Console", "Attributes", sbi.wAttributes);
1612     okChildInt("Console", "winLeft", (DWORD)sbi.srWindow.Left);
1613     okChildInt("Console", "winTop", (DWORD)sbi.srWindow.Top);
1614     okChildInt("Console", "winRight", (DWORD)sbi.srWindow.Right);
1615     okChildInt("Console", "winBottom", (DWORD)sbi.srWindow.Bottom);
1616     okChildInt("Console", "maxWinWidth", (DWORD)sbi.dwMaximumWindowSize.X);
1617     okChildInt("Console", "maxWinHeight", (DWORD)sbi.dwMaximumWindowSize.Y);
1618     okChildInt("Console", "InputCP", cpIn);
1619     okChildInt("Console", "OutputCP", cpOut);
1620     okChildInt("Console", "InputMode", modeIn);
1621     okChildInt("Console", "OutputMode", modeOut);
1622 
1623     if (run_tests)
1624     {
1625         ok(cpInC == 1252, "Wrong console CP (expected 1252 got %d/%d)\n", cpInC, cpIn);
1626         ok(cpOutC == 1252, "Wrong console-SB CP (expected 1252 got %d/%d)\n", cpOutC, cpOut);
1627     }
1628     else
1629         win_skip("Setting the codepage is not implemented\n");
1630 
1631     ok(modeInC == (modeIn ^ 1), "Wrong console mode\n");
1632     ok(modeOutC == (modeOut ^ 1), "Wrong console-SB mode\n");
1633     trace("cursor position(X): %d/%d\n",sbi.dwCursorPosition.X, sbiC.dwCursorPosition.X);
1634     ok(sbiC.dwCursorPosition.Y == (sbi.dwCursorPosition.Y ^ 1), "Wrong cursor position\n");
1635 
1636     release_memory();
1637     DeleteFileA(resfile);
1638 
1639     ok(CreatePipe(&hParentIn, &hChildOut, NULL, 0), "Creating parent-input pipe\n");
1640     ok(DuplicateHandle(GetCurrentProcess(), hChildOut, GetCurrentProcess(),
1641                        &hChildOutInh, 0, TRUE, DUPLICATE_SAME_ACCESS),
1642        "Duplicating as inheritable child-output pipe\n");
1643     CloseHandle(hChildOut);
1644 
1645     ok(CreatePipe(&hChildIn, &hParentOut, NULL, 0), "Creating parent-output pipe\n");
1646     ok(DuplicateHandle(GetCurrentProcess(), hChildIn, GetCurrentProcess(),
1647                        &hChildInInh, 0, TRUE, DUPLICATE_SAME_ACCESS),
1648        "Duplicating as inheritable child-input pipe\n");
1649     CloseHandle(hChildIn);
1650 
1651     memset(&startup, 0, sizeof(startup));
1652     startup.cb = sizeof(startup);
1653     startup.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
1654     startup.wShowWindow = SW_SHOWNORMAL;
1655     startup.hStdInput = hChildInInh;
1656     startup.hStdOutput = hChildOutInh;
1657     startup.hStdError = hChildOutInh;
1658 
1659     get_file_name(resfile);
1660     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\" stdhandle", selfname, resfile);
1661     ok(CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &startup, &info), "CreateProcess\n");
1662     ok(CloseHandle(hChildInInh), "Closing handle\n");
1663     ok(CloseHandle(hChildOutInh), "Closing handle\n");
1664 
1665     msg_len = strlen(msg) + 1;
1666     ok(WriteFile(hParentOut, msg, msg_len, &w, NULL), "Writing to child\n");
1667     ok(w == msg_len, "Should have written %u bytes, actually wrote %u\n", msg_len, w);
1668     memset(buffer, 0, sizeof(buffer));
1669     ok(ReadFile(hParentIn, buffer, sizeof(buffer), &w, NULL), "Reading from child\n");
1670     ok(strcmp(buffer, msg) == 0, "Should have received '%s'\n", msg);
1671 
1672     /* wait for child to terminate */
1673     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1674     /* child process has changed result file, so let profile functions know about it */
1675     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1676 
1677     okChildString("StdHandle", "msg", msg);
1678 
1679     release_memory();
1680     DeleteFileA(resfile);
1681 }
1682 
1683 static  void    test_ExitCode(void)
1684 {
1685     char                buffer[MAX_PATH];
1686     PROCESS_INFORMATION	info;
1687     STARTUPINFOA	startup;
1688     DWORD               code;
1689 
1690     /* let's start simplistic */
1691     memset(&startup, 0, sizeof(startup));
1692     startup.cb = sizeof(startup);
1693     startup.dwFlags = STARTF_USESHOWWINDOW;
1694     startup.wShowWindow = SW_SHOWNORMAL;
1695 
1696     get_file_name(resfile);
1697     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\" exit_code", selfname, resfile);
1698     ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &info), "CreateProcess\n");
1699 
1700     /* wait for child to terminate */
1701     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
1702     /* child process has changed result file, so let profile functions know about it */
1703     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
1704 
1705     ok(GetExitCodeProcess(info.hProcess, &code), "Getting exit code\n");
1706     okChildInt("ExitCode", "value", code);
1707 
1708     release_memory();
1709     DeleteFileA(resfile);
1710 }
1711 
1712 static void test_OpenProcess(void)
1713 {
1714     HANDLE hproc;
1715     void *addr1;
1716     MEMORY_BASIC_INFORMATION info;
1717     SIZE_T dummy, read_bytes;
1718     BOOL ret;
1719 
1720     /* not exported in all windows versions */
1721     if ((!pVirtualAllocEx) || (!pVirtualFreeEx)) {
1722         win_skip("VirtualAllocEx not found\n");
1723         return;
1724     }
1725 
1726     /* without PROCESS_VM_OPERATION */
1727     hproc = OpenProcess(PROCESS_ALL_ACCESS_NT4 & ~PROCESS_VM_OPERATION, FALSE, GetCurrentProcessId());
1728     ok(hproc != NULL, "OpenProcess error %d\n", GetLastError());
1729 
1730     SetLastError(0xdeadbeef);
1731     addr1 = pVirtualAllocEx(hproc, 0, 0xFFFC, MEM_RESERVE, PAGE_NOACCESS);
1732     ok(!addr1, "VirtualAllocEx should fail\n");
1733     if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
1734     {   /* Win9x */
1735         CloseHandle(hproc);
1736         win_skip("VirtualAllocEx not implemented\n");
1737         return;
1738     }
1739     ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %d\n", GetLastError());
1740 
1741     read_bytes = 0xdeadbeef;
1742     SetLastError(0xdeadbeef);
1743     ret = ReadProcessMemory(hproc, test_OpenProcess, &dummy, sizeof(dummy), &read_bytes);
1744     ok(ret, "ReadProcessMemory error %d\n", GetLastError());
1745     ok(read_bytes == sizeof(dummy), "wrong read bytes %ld\n", read_bytes);
1746 
1747     CloseHandle(hproc);
1748 
1749     hproc = OpenProcess(PROCESS_VM_OPERATION, FALSE, GetCurrentProcessId());
1750     ok(hproc != NULL, "OpenProcess error %d\n", GetLastError());
1751 
1752     addr1 = pVirtualAllocEx(hproc, 0, 0xFFFC, MEM_RESERVE, PAGE_NOACCESS);
1753     ok(addr1 != NULL, "VirtualAllocEx error %d\n", GetLastError());
1754 
1755     /* without PROCESS_QUERY_INFORMATION */
1756     SetLastError(0xdeadbeef);
1757     ok(!VirtualQueryEx(hproc, addr1, &info, sizeof(info)),
1758        "VirtualQueryEx without PROCESS_QUERY_INFORMATION rights should fail\n");
1759     ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %d\n", GetLastError());
1760 
1761     /* without PROCESS_VM_READ */
1762     read_bytes = 0xdeadbeef;
1763     SetLastError(0xdeadbeef);
1764     ok(!ReadProcessMemory(hproc, addr1, &dummy, sizeof(dummy), &read_bytes),
1765        "ReadProcessMemory without PROCESS_VM_READ rights should fail\n");
1766     ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %d\n", GetLastError());
1767     ok(read_bytes == 0, "wrong read bytes %ld\n", read_bytes);
1768 
1769     CloseHandle(hproc);
1770 
1771     hproc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
1772 
1773     memset(&info, 0xcc, sizeof(info));
1774     read_bytes = VirtualQueryEx(hproc, addr1, &info, sizeof(info));
1775     ok(read_bytes == sizeof(info), "VirtualQueryEx error %d\n", GetLastError());
1776 
1777     ok(info.BaseAddress == addr1, "%p != %p\n", info.BaseAddress, addr1);
1778     ok(info.AllocationBase == addr1, "%p != %p\n", info.AllocationBase, addr1);
1779     ok(info.AllocationProtect == PAGE_NOACCESS, "%x != PAGE_NOACCESS\n", info.AllocationProtect);
1780     ok(info.RegionSize == 0x10000, "%lx != 0x10000\n", info.RegionSize);
1781     ok(info.State == MEM_RESERVE, "%x != MEM_RESERVE\n", info.State);
1782     /* NT reports Protect == 0 for a not committed memory block */
1783     ok(info.Protect == 0 /* NT */ ||
1784        info.Protect == PAGE_NOACCESS, /* Win9x */
1785         "%x != PAGE_NOACCESS\n", info.Protect);
1786     ok(info.Type == MEM_PRIVATE, "%x != MEM_PRIVATE\n", info.Type);
1787 
1788     SetLastError(0xdeadbeef);
1789     ok(!pVirtualFreeEx(hproc, addr1, 0, MEM_RELEASE),
1790        "VirtualFreeEx without PROCESS_VM_OPERATION rights should fail\n");
1791     ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %d\n", GetLastError());
1792 
1793     CloseHandle(hproc);
1794 
1795     hproc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, GetCurrentProcessId());
1796     if (hproc)
1797     {
1798         SetLastError(0xdeadbeef);
1799         memset(&info, 0xcc, sizeof(info));
1800         read_bytes = VirtualQueryEx(hproc, addr1, &info, sizeof(info));
1801         if (read_bytes) /* win8 */
1802         {
1803             ok(read_bytes == sizeof(info), "VirtualQueryEx error %d\n", GetLastError());
1804             ok(info.BaseAddress == addr1, "%p != %p\n", info.BaseAddress, addr1);
1805             ok(info.AllocationBase == addr1, "%p != %p\n", info.AllocationBase, addr1);
1806             ok(info.AllocationProtect == PAGE_NOACCESS, "%x != PAGE_NOACCESS\n", info.AllocationProtect);
1807             ok(info.RegionSize == 0x10000, "%lx != 0x10000\n", info.RegionSize);
1808             ok(info.State == MEM_RESERVE, "%x != MEM_RESERVE\n", info.State);
1809             ok(info.Protect == 0, "%x != PAGE_NOACCESS\n", info.Protect);
1810             ok(info.Type == MEM_PRIVATE, "%x != MEM_PRIVATE\n", info.Type);
1811         }
1812         else /* before win8 */
1813             ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %d\n", GetLastError());
1814 
1815         SetLastError(0xdeadbeef);
1816         ok(!pVirtualFreeEx(hproc, addr1, 0, MEM_RELEASE),
1817            "VirtualFreeEx without PROCESS_VM_OPERATION rights should fail\n");
1818         ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %d\n", GetLastError());
1819 
1820         CloseHandle(hproc);
1821     }
1822 
1823     ok(VirtualFree(addr1, 0, MEM_RELEASE), "VirtualFree failed\n");
1824 }
1825 
1826 static void test_GetProcessVersion(void)
1827 {
1828     static char cmdline[] = "winver.exe";
1829     PROCESS_INFORMATION pi;
1830     STARTUPINFOA si;
1831     DWORD ret;
1832 
1833     SetLastError(0xdeadbeef);
1834     ret = GetProcessVersion(0);
1835     ok(ret, "GetProcessVersion error %u\n", GetLastError());
1836 
1837     SetLastError(0xdeadbeef);
1838     ret = GetProcessVersion(GetCurrentProcessId());
1839     ok(ret, "GetProcessVersion error %u\n", GetLastError());
1840 
1841     memset(&si, 0, sizeof(si));
1842     si.cb = sizeof(si);
1843     si.dwFlags = STARTF_USESHOWWINDOW;
1844     si.wShowWindow = SW_HIDE;
1845     SetLastError(0xdeadbeef);
1846     ret = CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
1847     ok(ret, "CreateProcess error %u\n", GetLastError());
1848 
1849     SetLastError(0xdeadbeef);
1850     ret = GetProcessVersion(pi.dwProcessId);
1851     ok(ret, "GetProcessVersion error %u\n", GetLastError());
1852 
1853     SetLastError(0xdeadbeef);
1854     ret = TerminateProcess(pi.hProcess, 0);
1855     ok(ret, "TerminateProcess error %u\n", GetLastError());
1856 
1857     CloseHandle(pi.hProcess);
1858     CloseHandle(pi.hThread);
1859 }
1860 
1861 static void test_GetProcessImageFileNameA(void)
1862 {
1863     DWORD rc;
1864     CHAR process[MAX_PATH];
1865     static const char harddisk[] = "\\Device\\HarddiskVolume";
1866 
1867     if (!pK32GetProcessImageFileNameA)
1868     {
1869         win_skip("K32GetProcessImageFileNameA is unavailable\n");
1870         return;
1871     }
1872 
1873     /* callers must guess the buffer size */
1874     SetLastError(0xdeadbeef);
1875     rc = pK32GetProcessImageFileNameA(GetCurrentProcess(), NULL, 0);
1876     ok(!rc && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
1877        "K32GetProcessImageFileNameA(no buffer): returned %u, le=%u\n", rc, GetLastError());
1878 
1879     *process = '\0';
1880     rc = pK32GetProcessImageFileNameA(GetCurrentProcess(), process, sizeof(process));
1881     expect_eq_d(rc, lstrlenA(process));
1882     if (strncmp(process, harddisk, lstrlenA(harddisk)))
1883     {
1884         todo_wine win_skip("%s is probably on a network share, skipping tests\n", process);
1885         return;
1886     }
1887 
1888     if (!pQueryFullProcessImageNameA)
1889         win_skip("QueryFullProcessImageNameA unavailable (added in Windows Vista)\n");
1890     else
1891     {
1892         CHAR image[MAX_PATH];
1893         DWORD length;
1894 
1895         length = sizeof(image);
1896         expect_eq_d(TRUE, pQueryFullProcessImageNameA(GetCurrentProcess(), PROCESS_NAME_NATIVE, image, &length));
1897         expect_eq_d(length, lstrlenA(image));
1898         ok(lstrcmpiA(process, image) == 0, "expected '%s' to be equal to '%s'\n", process, image);
1899     }
1900 }
1901 
1902 static void test_QueryFullProcessImageNameA(void)
1903 {
1904 #define INIT_STR "Just some words"
1905     DWORD length, size;
1906     CHAR buf[MAX_PATH], module[MAX_PATH];
1907 
1908     if (!pQueryFullProcessImageNameA)
1909     {
1910         win_skip("QueryFullProcessImageNameA unavailable (added in Windows Vista)\n");
1911         return;
1912     }
1913 
1914     *module = '\0';
1915     SetLastError(0); /* old Windows don't reset it on success */
1916     size = GetModuleFileNameA(NULL, module, sizeof(module));
1917     ok(size && GetLastError() != ERROR_INSUFFICIENT_BUFFER, "GetModuleFileName failed: %u le=%u\n", size, GetLastError());
1918 
1919     /* get the buffer length without \0 terminator */
1920     length = sizeof(buf);
1921     expect_eq_d(TRUE, pQueryFullProcessImageNameA(GetCurrentProcess(), 0, buf, &length));
1922     expect_eq_d(length, lstrlenA(buf));
1923     ok((buf[0] == '\\' && buf[1] == '\\') ||
1924        lstrcmpiA(buf, module) == 0, "expected %s to match %s\n", buf, module);
1925 
1926     /*  when the buffer is too small
1927      *  - function fail with error ERROR_INSUFFICIENT_BUFFER
1928      *  - the size variable is not modified
1929      * tested with the biggest too small size
1930      */
1931     size = length;
1932     sprintf(buf,INIT_STR);
1933     expect_eq_d(FALSE, pQueryFullProcessImageNameA(GetCurrentProcess(), 0, buf, &size));
1934     expect_eq_d(ERROR_INSUFFICIENT_BUFFER, GetLastError());
1935     expect_eq_d(length, size);
1936     expect_eq_s(INIT_STR, buf);
1937 
1938     /* retest with smaller buffer size
1939      */
1940     size = 4;
1941     sprintf(buf,INIT_STR);
1942     expect_eq_d(FALSE, pQueryFullProcessImageNameA(GetCurrentProcess(), 0, buf, &size));
1943     expect_eq_d(ERROR_INSUFFICIENT_BUFFER, GetLastError());
1944     expect_eq_d(4, size);
1945     expect_eq_s(INIT_STR, buf);
1946 
1947     /* this is a difference between the ascii and the unicode version
1948      * the unicode version crashes when the size is big enough to hold
1949      * the result while the ascii version throws an error
1950      */
1951     size = 1024;
1952     expect_eq_d(FALSE, pQueryFullProcessImageNameA(GetCurrentProcess(), 0, NULL, &size));
1953     expect_eq_d(1024, size);
1954     expect_eq_d(ERROR_INVALID_PARAMETER, GetLastError());
1955 }
1956 
1957 static void test_QueryFullProcessImageNameW(void)
1958 {
1959     HANDLE hSelf;
1960     WCHAR module_name[1024], device[1024];
1961     WCHAR deviceW[] = {'\\','D', 'e','v','i','c','e',0};
1962     WCHAR buf[1024];
1963     DWORD size, len;
1964 
1965     if (!pQueryFullProcessImageNameW)
1966     {
1967         win_skip("QueryFullProcessImageNameW unavailable (added in Windows Vista)\n");
1968         return;
1969     }
1970 
1971     ok(GetModuleFileNameW(NULL, module_name, 1024), "GetModuleFileNameW(NULL, ...) failed\n");
1972 
1973     /* GetCurrentProcess pseudo-handle */
1974     size = sizeof(buf) / sizeof(buf[0]);
1975     expect_eq_d(TRUE, pQueryFullProcessImageNameW(GetCurrentProcess(), 0, buf, &size));
1976     expect_eq_d(lstrlenW(buf), size);
1977     expect_eq_ws_i(buf, module_name);
1978 
1979     hSelf = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, GetCurrentProcessId());
1980     /* Real handle */
1981     size = sizeof(buf) / sizeof(buf[0]);
1982     expect_eq_d(TRUE, pQueryFullProcessImageNameW(hSelf, 0, buf, &size));
1983     expect_eq_d(lstrlenW(buf), size);
1984     expect_eq_ws_i(buf, module_name);
1985 
1986     /* Buffer too small */
1987     size = lstrlenW(module_name)/2;
1988     lstrcpyW(buf, deviceW);
1989     SetLastError(0xdeadbeef);
1990     expect_eq_d(FALSE, pQueryFullProcessImageNameW(hSelf, 0, buf, &size));
1991     expect_eq_d(lstrlenW(module_name)/2, size);  /* size not changed(!) */
1992     expect_eq_d(ERROR_INSUFFICIENT_BUFFER, GetLastError());
1993     expect_eq_ws_i(deviceW, buf);  /* buffer not changed */
1994 
1995     /* Too small - not space for NUL terminator */
1996     size = lstrlenW(module_name);
1997     SetLastError(0xdeadbeef);
1998     expect_eq_d(FALSE, pQueryFullProcessImageNameW(hSelf, 0, buf, &size));
1999     expect_eq_d(lstrlenW(module_name), size);  /* size not changed(!) */
2000     expect_eq_d(ERROR_INSUFFICIENT_BUFFER, GetLastError());
2001 
2002     /* NULL buffer */
2003     size = 0;
2004     expect_eq_d(FALSE, pQueryFullProcessImageNameW(hSelf, 0, NULL, &size));
2005     expect_eq_d(0, size);
2006     expect_eq_d(ERROR_INSUFFICIENT_BUFFER, GetLastError());
2007 
2008     /* Buffer too small */
2009     size = lstrlenW(module_name)/2;
2010     SetLastError(0xdeadbeef);
2011     lstrcpyW(buf, module_name);
2012     expect_eq_d(FALSE, pQueryFullProcessImageNameW(hSelf, 0, buf, &size));
2013     expect_eq_d(lstrlenW(module_name)/2, size);  /* size not changed(!) */
2014     expect_eq_d(ERROR_INSUFFICIENT_BUFFER, GetLastError());
2015     expect_eq_ws_i(module_name, buf);  /* buffer not changed */
2016 
2017 
2018     /* native path */
2019     size = sizeof(buf) / sizeof(buf[0]);
2020     expect_eq_d(TRUE, pQueryFullProcessImageNameW(hSelf, PROCESS_NAME_NATIVE, buf, &size));
2021     expect_eq_d(lstrlenW(buf), size);
2022     ok(buf[0] == '\\', "NT path should begin with '\\'\n");
2023     ok(memcmp(buf, deviceW, sizeof(WCHAR)*lstrlenW(deviceW)) == 0, "NT path should begin with \\Device\n");
2024 
2025     module_name[2] = '\0';
2026     *device = '\0';
2027     size = QueryDosDeviceW(module_name, device, sizeof(device)/sizeof(device[0]));
2028     ok(size, "QueryDosDeviceW failed: le=%u\n", GetLastError());
2029     len = lstrlenW(device);
2030     ok(size >= len+2, "expected %d to be greater than %d+2 = strlen(%s)\n", size, len, wine_dbgstr_w(device));
2031 
2032     if (size >= lstrlenW(buf))
2033     {
2034         ok(0, "expected %s\\ to match the start of %s\n", wine_dbgstr_w(device), wine_dbgstr_w(buf));
2035     }
2036     else
2037     {
2038         ok(buf[len] == '\\', "expected '%c' to be a '\\' in %s\n", buf[len], wine_dbgstr_w(module_name));
2039         buf[len] = '\0';
2040         ok(lstrcmpiW(device, buf) == 0, "expected %s to match %s\n", wine_dbgstr_w(device), wine_dbgstr_w(buf));
2041         ok(lstrcmpiW(module_name+3, buf+len+1) == 0, "expected '%s' to match '%s'\n", wine_dbgstr_w(module_name+3), wine_dbgstr_w(buf+len+1));
2042     }
2043 
2044     CloseHandle(hSelf);
2045 }
2046 
2047 static void test_Handles(void)
2048 {
2049     HANDLE handle = GetCurrentProcess();
2050     HANDLE h2, h3;
2051     BOOL ret;
2052     DWORD code;
2053 
2054     ok( handle == (HANDLE)~(ULONG_PTR)0 ||
2055         handle == (HANDLE)(ULONG_PTR)0x7fffffff /* win9x */,
2056         "invalid current process handle %p\n", handle );
2057     ret = GetExitCodeProcess( handle, &code );
2058     ok( ret, "GetExitCodeProcess failed err %u\n", GetLastError() );
2059 #ifdef _WIN64
2060     /* truncated handle */
2061     SetLastError( 0xdeadbeef );
2062     handle = (HANDLE)((ULONG_PTR)handle & ~0u);
2063     ret = GetExitCodeProcess( handle, &code );
2064     ok( !ret, "GetExitCodeProcess succeeded for %p\n", handle );
2065     ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
2066     /* sign-extended handle */
2067     SetLastError( 0xdeadbeef );
2068     handle = (HANDLE)((LONG_PTR)(int)(ULONG_PTR)handle);
2069     ret = GetExitCodeProcess( handle, &code );
2070     ok( ret, "GetExitCodeProcess failed err %u\n", GetLastError() );
2071     /* invalid high-word */
2072     SetLastError( 0xdeadbeef );
2073     handle = (HANDLE)(((ULONG_PTR)handle & ~0u) + ((ULONG_PTR)1 << 32));
2074     ret = GetExitCodeProcess( handle, &code );
2075     ok( !ret, "GetExitCodeProcess succeeded for %p\n", handle );
2076     ok( GetLastError() == ERROR_INVALID_HANDLE, "wrong error %u\n", GetLastError() );
2077 #endif
2078 
2079     handle = GetStdHandle( STD_ERROR_HANDLE );
2080     ok( handle != 0, "handle %p\n", handle );
2081     DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(), &h3,
2082                      0, TRUE, DUPLICATE_SAME_ACCESS );
2083     SetStdHandle( STD_ERROR_HANDLE, h3 );
2084     CloseHandle( (HANDLE)STD_ERROR_HANDLE );
2085     h2 = GetStdHandle( STD_ERROR_HANDLE );
2086     ok( h2 == 0 ||
2087         broken( h2 == h3) || /* nt4, w2k */
2088         broken( h2 == INVALID_HANDLE_VALUE),  /* win9x */
2089         "wrong handle %p/%p\n", h2, h3 );
2090     SetStdHandle( STD_ERROR_HANDLE, handle );
2091 }
2092 
2093 static void test_IsWow64Process(void)
2094 {
2095     PROCESS_INFORMATION pi;
2096     STARTUPINFOA si;
2097     DWORD ret;
2098     BOOL is_wow64;
2099     static char cmdline[] = "C:\\Program Files\\Internet Explorer\\iexplore.exe";
2100     static char cmdline_wow64[] = "C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";
2101 
2102     if (!pIsWow64Process)
2103     {
2104         skip("IsWow64Process is not available\n");
2105         return;
2106     }
2107 
2108     memset(&si, 0, sizeof(si));
2109     si.cb = sizeof(si);
2110     si.dwFlags = STARTF_USESHOWWINDOW;
2111     si.wShowWindow = SW_HIDE;
2112     ret = CreateProcessA(NULL, cmdline_wow64, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2113     if (ret)
2114     {
2115         trace("Created process %s\n", cmdline_wow64);
2116         is_wow64 = FALSE;
2117         ret = pIsWow64Process(pi.hProcess, &is_wow64);
2118         ok(ret, "IsWow64Process failed.\n");
2119         ok(is_wow64, "is_wow64 returned FALSE.\n");
2120 
2121         ret = TerminateProcess(pi.hProcess, 0);
2122         ok(ret, "TerminateProcess error\n");
2123 
2124         CloseHandle(pi.hProcess);
2125         CloseHandle(pi.hThread);
2126     }
2127 
2128     memset(&si, 0, sizeof(si));
2129     si.cb = sizeof(si);
2130     si.dwFlags = STARTF_USESHOWWINDOW;
2131     si.wShowWindow = SW_HIDE;
2132     ret = CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2133     if (ret)
2134     {
2135         trace("Created process %s\n", cmdline);
2136         is_wow64 = TRUE;
2137         ret = pIsWow64Process(pi.hProcess, &is_wow64);
2138         ok(ret, "IsWow64Process failed.\n");
2139         ok(!is_wow64, "is_wow64 returned TRUE.\n");
2140 
2141         ret = TerminateProcess(pi.hProcess, 0);
2142         ok(ret, "TerminateProcess error\n");
2143 
2144         CloseHandle(pi.hProcess);
2145         CloseHandle(pi.hThread);
2146     }
2147 }
2148 
2149 static void test_SystemInfo(void)
2150 {
2151     SYSTEM_INFO si, nsi;
2152     BOOL is_wow64;
2153 
2154     if (!pGetNativeSystemInfo)
2155     {
2156         win_skip("GetNativeSystemInfo is not available\n");
2157         return;
2158     }
2159 
2160     if (!pIsWow64Process || !pIsWow64Process( GetCurrentProcess(), &is_wow64 )) is_wow64 = FALSE;
2161 
2162     GetSystemInfo(&si);
2163     pGetNativeSystemInfo(&nsi);
2164     if (is_wow64)
2165     {
2166         if (S(U(si)).wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
2167         {
2168             ok(S(U(nsi)).wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64,
2169                "Expected PROCESSOR_ARCHITECTURE_AMD64, got %d\n",
2170                S(U(nsi)).wProcessorArchitecture);
2171             ok(nsi.dwProcessorType == PROCESSOR_AMD_X8664,
2172                "Expected PROCESSOR_AMD_X8664, got %d\n",
2173                nsi.dwProcessorType);
2174         }
2175     }
2176     else
2177     {
2178         ok(S(U(si)).wProcessorArchitecture == S(U(nsi)).wProcessorArchitecture,
2179            "Expected no difference for wProcessorArchitecture, got %d and %d\n",
2180            S(U(si)).wProcessorArchitecture, S(U(nsi)).wProcessorArchitecture);
2181         ok(si.dwProcessorType == nsi.dwProcessorType,
2182            "Expected no difference for dwProcessorType, got %d and %d\n",
2183            si.dwProcessorType, nsi.dwProcessorType);
2184     }
2185 }
2186 
2187 static void test_RegistryQuota(void)
2188 {
2189     BOOL ret;
2190     DWORD max_quota, used_quota;
2191 
2192     if (!pGetSystemRegistryQuota)
2193     {
2194         win_skip("GetSystemRegistryQuota is not available\n");
2195         return;
2196     }
2197 
2198     ret = pGetSystemRegistryQuota(NULL, NULL);
2199     ok(ret == TRUE,
2200        "Expected GetSystemRegistryQuota to return TRUE, got %d\n", ret);
2201 
2202     ret = pGetSystemRegistryQuota(&max_quota, NULL);
2203     ok(ret == TRUE,
2204        "Expected GetSystemRegistryQuota to return TRUE, got %d\n", ret);
2205 
2206     ret = pGetSystemRegistryQuota(NULL, &used_quota);
2207     ok(ret == TRUE,
2208        "Expected GetSystemRegistryQuota to return TRUE, got %d\n", ret);
2209 
2210     ret = pGetSystemRegistryQuota(&max_quota, &used_quota);
2211     ok(ret == TRUE,
2212        "Expected GetSystemRegistryQuota to return TRUE, got %d\n", ret);
2213 }
2214 
2215 static void test_TerminateProcess(void)
2216 {
2217     static char cmdline[] = "winver.exe";
2218     PROCESS_INFORMATION pi;
2219     STARTUPINFOA si;
2220     DWORD ret;
2221     HANDLE dummy, thread;
2222 
2223     memset(&si, 0, sizeof(si));
2224     si.cb = sizeof(si);
2225     SetLastError(0xdeadbeef);
2226     ret = CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi);
2227     ok(ret, "CreateProcess error %u\n", GetLastError());
2228 
2229     SetLastError(0xdeadbeef);
2230     thread = CreateRemoteThread(pi.hProcess, NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
2231     ok(thread != 0, "CreateRemoteThread error %d\n", GetLastError());
2232 
2233     /* create a not closed thread handle duplicate in the target process */
2234     SetLastError(0xdeadbeef);
2235     ret = DuplicateHandle(GetCurrentProcess(), thread, pi.hProcess, &dummy,
2236                           0, FALSE, DUPLICATE_SAME_ACCESS);
2237     ok(ret, "DuplicateHandle error %u\n", GetLastError());
2238 
2239     SetLastError(0xdeadbeef);
2240     ret = TerminateThread(thread, 0);
2241     ok(ret, "TerminateThread error %u\n", GetLastError());
2242     CloseHandle(thread);
2243 
2244     SetLastError(0xdeadbeef);
2245     ret = TerminateProcess(pi.hProcess, 0);
2246     ok(ret, "TerminateProcess error %u\n", GetLastError());
2247 
2248     CloseHandle(pi.hProcess);
2249     CloseHandle(pi.hThread);
2250 }
2251 
2252 static void test_DuplicateHandle(void)
2253 {
2254     char path[MAX_PATH], file_name[MAX_PATH];
2255     HANDLE f, fmin, out;
2256     DWORD info;
2257     BOOL r;
2258 
2259     r = DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(),
2260             GetCurrentProcess(), &out, 0, FALSE,
2261             DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
2262     ok(r, "DuplicateHandle error %u\n", GetLastError());
2263     r = GetHandleInformation(out, &info);
2264     ok(r, "GetHandleInformation error %u\n", GetLastError());
2265     ok(info == 0, "info = %x\n", info);
2266     ok(out != GetCurrentProcess(), "out = GetCurrentProcess()\n");
2267     CloseHandle(out);
2268 
2269     r = DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(),
2270             GetCurrentProcess(), &out, 0, TRUE,
2271             DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
2272     ok(r, "DuplicateHandle error %u\n", GetLastError());
2273     r = GetHandleInformation(out, &info);
2274     ok(r, "GetHandleInformation error %u\n", GetLastError());
2275     ok(info == HANDLE_FLAG_INHERIT, "info = %x\n", info);
2276     ok(out != GetCurrentProcess(), "out = GetCurrentProcess()\n");
2277     CloseHandle(out);
2278 
2279     GetTempPathA(MAX_PATH, path);
2280     GetTempFileNameA(path, "wt", 0, file_name);
2281     f = CreateFileA(file_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
2282     if (f == INVALID_HANDLE_VALUE)
2283     {
2284         ok(0, "could not create %s\n", file_name);
2285         return;
2286     }
2287 
2288     r = DuplicateHandle(GetCurrentProcess(), f, GetCurrentProcess(), &out,
2289             0, FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
2290     ok(r, "DuplicateHandle error %u\n", GetLastError());
2291     ok(f == out, "f != out\n");
2292     r = GetHandleInformation(out, &info);
2293     ok(r, "GetHandleInformation error %u\n", GetLastError());
2294     ok(info == 0, "info = %x\n", info);
2295 
2296     r = DuplicateHandle(GetCurrentProcess(), f, GetCurrentProcess(), &out,
2297             0, TRUE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
2298     ok(r, "DuplicateHandle error %u\n", GetLastError());
2299     ok(f == out, "f != out\n");
2300     r = GetHandleInformation(out, &info);
2301     ok(r, "GetHandleInformation error %u\n", GetLastError());
2302     ok(info == HANDLE_FLAG_INHERIT, "info = %x\n", info);
2303 
2304     r = SetHandleInformation(f, HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAG_PROTECT_FROM_CLOSE);
2305     ok(r, "SetHandleInformation error %u\n", GetLastError());
2306     r = DuplicateHandle(GetCurrentProcess(), f, GetCurrentProcess(), &out,
2307                 0, TRUE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
2308     ok(r, "DuplicateHandle error %u\n", GetLastError());
2309     ok(f != out, "f == out\n");
2310     r = GetHandleInformation(out, &info);
2311     ok(r, "GetHandleInformation error %u\n", GetLastError());
2312     ok(info == HANDLE_FLAG_INHERIT, "info = %x\n", info);
2313     r = SetHandleInformation(f, HANDLE_FLAG_PROTECT_FROM_CLOSE, 0);
2314     ok(r, "SetHandleInformation error %u\n", GetLastError());
2315 
2316     /* Test if DuplicateHandle allocates first free handle */
2317     if (f > out)
2318     {
2319         fmin = out;
2320     }
2321     else
2322     {
2323         fmin = f;
2324         f = out;
2325     }
2326     CloseHandle(fmin);
2327     r = DuplicateHandle(GetCurrentProcess(), f, GetCurrentProcess(), &out,
2328             0, TRUE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
2329     ok(r, "DuplicateHandle error %u\n", GetLastError());
2330     ok(f == out, "f != out\n");
2331     CloseHandle(out);
2332     DeleteFileA(file_name);
2333 
2334     f = CreateFileA("CONIN$", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
2335     if (!is_console(f))
2336     {
2337         skip("DuplicateHandle on console handle\n");
2338         CloseHandle(f);
2339         return;
2340     }
2341 
2342     r = DuplicateHandle(GetCurrentProcess(), f, GetCurrentProcess(), &out,
2343             0, FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
2344     ok(r, "DuplicateHandle error %u\n", GetLastError());
2345     todo_wine ok(f != out, "f == out\n");
2346     CloseHandle(out);
2347 }
2348 
2349 #define test_completion(a, b, c, d, e) _test_completion(__LINE__, a, b, c, d, e)
2350 static void _test_completion(int line, HANDLE port, DWORD ekey, ULONG_PTR evalue, ULONG_PTR eoverlapped, DWORD wait)
2351 {
2352     LPOVERLAPPED overlapped;
2353     ULONG_PTR value;
2354     DWORD key;
2355     BOOL ret;
2356 
2357     ret = GetQueuedCompletionStatus(port, &key, &value, &overlapped, wait);
2358 
2359     ok_(__FILE__, line)(ret, "GetQueuedCompletionStatus: %x\n", GetLastError());
2360     if (ret)
2361     {
2362         ok_(__FILE__, line)(key == ekey, "unexpected key %x\n", key);
2363         ok_(__FILE__, line)(value == evalue, "unexpected value %p\n", (void *)value);
2364         ok_(__FILE__, line)(overlapped == (LPOVERLAPPED)eoverlapped, "unexpected overlapped %p\n", overlapped);
2365     }
2366 }
2367 
2368 #define create_process(cmd, pi) _create_process(__LINE__, cmd, pi)
2369 static void _create_process(int line, const char *command, LPPROCESS_INFORMATION pi)
2370 {
2371     BOOL ret;
2372     char buffer[MAX_PATH];
2373     STARTUPINFOA si = {0};
2374 
2375     sprintf(buffer, "\"%s\" tests/process.c %s", selfname, command);
2376 
2377     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, pi);
2378     ok_(__FILE__, line)(ret, "CreateProcess error %u\n", GetLastError());
2379 }
2380 
2381 
2382 static void test_IsProcessInJob(void)
2383 {
2384     HANDLE job, job2;
2385     PROCESS_INFORMATION pi;
2386     BOOL ret, out;
2387     DWORD dwret;
2388 
2389     if (!pIsProcessInJob)
2390     {
2391         win_skip("IsProcessInJob not available.\n");
2392         return;
2393     }
2394 
2395     job = pCreateJobObjectW(NULL, NULL);
2396     ok(job != NULL, "CreateJobObject error %u\n", GetLastError());
2397 
2398     job2 = pCreateJobObjectW(NULL, NULL);
2399     ok(job2 != NULL, "CreateJobObject error %u\n", GetLastError());
2400 
2401     create_process("wait", &pi);
2402 
2403     out = TRUE;
2404     ret = pIsProcessInJob(pi.hProcess, job, &out);
2405     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2406     ok(!out, "IsProcessInJob returned out=%u\n", out);
2407 
2408     out = TRUE;
2409     ret = pIsProcessInJob(pi.hProcess, job2, &out);
2410     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2411     ok(!out, "IsProcessInJob returned out=%u\n", out);
2412 
2413     out = TRUE;
2414     ret = pIsProcessInJob(pi.hProcess, NULL, &out);
2415     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2416     ok(!out, "IsProcessInJob returned out=%u\n", out);
2417 
2418     ret = pAssignProcessToJobObject(job, pi.hProcess);
2419     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2420 
2421     out = FALSE;
2422     ret = pIsProcessInJob(pi.hProcess, job, &out);
2423     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2424     ok(out, "IsProcessInJob returned out=%u\n", out);
2425 
2426     out = TRUE;
2427     ret = pIsProcessInJob(pi.hProcess, job2, &out);
2428     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2429     ok(!out, "IsProcessInJob returned out=%u\n", out);
2430 
2431     out = FALSE;
2432     ret = pIsProcessInJob(pi.hProcess, NULL, &out);
2433     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2434     ok(out, "IsProcessInJob returned out=%u\n", out);
2435 
2436     TerminateProcess(pi.hProcess, 0);
2437 
2438     dwret = WaitForSingleObject(pi.hProcess, 1000);
2439     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2440 
2441     out = FALSE;
2442     ret = pIsProcessInJob(pi.hProcess, job, &out);
2443     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2444     ok(out, "IsProcessInJob returned out=%u\n", out);
2445 
2446     CloseHandle(pi.hProcess);
2447     CloseHandle(pi.hThread);
2448     CloseHandle(job);
2449     CloseHandle(job2);
2450 }
2451 
2452 static void test_TerminateJobObject(void)
2453 {
2454     HANDLE job;
2455     PROCESS_INFORMATION pi;
2456     BOOL ret;
2457     DWORD dwret;
2458 
2459     job = pCreateJobObjectW(NULL, NULL);
2460     ok(job != NULL, "CreateJobObject error %u\n", GetLastError());
2461 
2462     create_process("wait", &pi);
2463 
2464     ret = pAssignProcessToJobObject(job, pi.hProcess);
2465     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2466 
2467     ret = pTerminateJobObject(job, 123);
2468     ok(ret, "TerminateJobObject error %u\n", GetLastError());
2469 
2470     dwret = WaitForSingleObject(pi.hProcess, 1000);
2471     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2472     if (dwret == WAIT_TIMEOUT) TerminateProcess(pi.hProcess, 0);
2473 
2474     ret = GetExitCodeProcess(pi.hProcess, &dwret);
2475     ok(ret, "GetExitCodeProcess error %u\n", GetLastError());
2476     ok(dwret == 123 || broken(dwret == 0) /* randomly fails on Win 2000 / XP */,
2477        "wrong exitcode %u\n", dwret);
2478 
2479     CloseHandle(pi.hProcess);
2480     CloseHandle(pi.hThread);
2481 
2482     /* Test adding an already terminated process to a job object */
2483     create_process("exit", &pi);
2484 
2485     dwret = WaitForSingleObject(pi.hProcess, 1000);
2486     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2487 
2488     SetLastError(0xdeadbeef);
2489     ret = pAssignProcessToJobObject(job, pi.hProcess);
2490     ok(!ret, "AssignProcessToJobObject unexpectedly succeeded\n");
2491     expect_eq_d(ERROR_ACCESS_DENIED, GetLastError());
2492 
2493     CloseHandle(pi.hProcess);
2494     CloseHandle(pi.hThread);
2495 
2496     CloseHandle(job);
2497 }
2498 
2499 static void test_QueryInformationJobObject(void)
2500 {
2501     char buf[sizeof(JOBOBJECT_BASIC_PROCESS_ID_LIST) + sizeof(ULONG_PTR) * 4];
2502     PJOBOBJECT_BASIC_PROCESS_ID_LIST pid_list = (JOBOBJECT_BASIC_PROCESS_ID_LIST *)buf;
2503     JOBOBJECT_EXTENDED_LIMIT_INFORMATION ext_limit_info;
2504     JOBOBJECT_BASIC_LIMIT_INFORMATION *basic_limit_info = &ext_limit_info.BasicLimitInformation;
2505     DWORD dwret, ret_len;
2506     PROCESS_INFORMATION pi[2];
2507     HANDLE job;
2508     BOOL ret;
2509 
2510     job = pCreateJobObjectW(NULL, NULL);
2511     ok(job != NULL, "CreateJobObject error %u\n", GetLastError());
2512 
2513     /* Only active processes are returned */
2514     create_process("exit", &pi[0]);
2515     ret = pAssignProcessToJobObject(job, pi[0].hProcess);
2516     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2517     dwret = WaitForSingleObject(pi[0].hProcess, 1000);
2518     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2519 
2520     CloseHandle(pi[0].hProcess);
2521     CloseHandle(pi[0].hThread);
2522 
2523     create_process("wait", &pi[0]);
2524     ret = pAssignProcessToJobObject(job, pi[0].hProcess);
2525     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2526 
2527     create_process("wait", &pi[1]);
2528     ret = pAssignProcessToJobObject(job, pi[1].hProcess);
2529     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2530 
2531     SetLastError(0xdeadbeef);
2532     ret = QueryInformationJobObject(job, JobObjectBasicProcessIdList, pid_list,
2533                                     FIELD_OFFSET(JOBOBJECT_BASIC_PROCESS_ID_LIST, ProcessIdList), &ret_len);
2534     ok(!ret, "QueryInformationJobObject expected failure\n");
2535     expect_eq_d(ERROR_BAD_LENGTH, GetLastError());
2536 
2537     SetLastError(0xdeadbeef);
2538     memset(buf, 0, sizeof(buf));
2539     pid_list->NumberOfAssignedProcesses = 42;
2540     pid_list->NumberOfProcessIdsInList  = 42;
2541     ret = QueryInformationJobObject(job, JobObjectBasicProcessIdList, pid_list,
2542                                     FIELD_OFFSET(JOBOBJECT_BASIC_PROCESS_ID_LIST, ProcessIdList[1]), &ret_len);
2543     todo_wine
2544     ok(!ret, "QueryInformationJobObject expected failure\n");
2545     todo_wine
2546     expect_eq_d(ERROR_MORE_DATA, GetLastError());
2547     if (ret)
2548     {
2549         todo_wine
2550         expect_eq_d(42, pid_list->NumberOfAssignedProcesses);
2551         todo_wine
2552         expect_eq_d(42, pid_list->NumberOfProcessIdsInList);
2553     }
2554 
2555     memset(buf, 0, sizeof(buf));
2556     ret = pQueryInformationJobObject(job, JobObjectBasicProcessIdList, pid_list, sizeof(buf), &ret_len);
2557     ok(ret, "QueryInformationJobObject error %u\n", GetLastError());
2558     if(ret)
2559     {
2560         if (pid_list->NumberOfAssignedProcesses == 3) /* Win 8 */
2561             win_skip("Number of assigned processes broken on Win 8\n");
2562         else
2563         {
2564             ULONG_PTR *list = pid_list->ProcessIdList;
2565 
2566             todo_wine
2567             ok(ret_len == FIELD_OFFSET(JOBOBJECT_BASIC_PROCESS_ID_LIST, ProcessIdList[2]),
2568                "QueryInformationJobObject returned ret_len=%u\n", ret_len);
2569 
2570             todo_wine
2571             expect_eq_d(2, pid_list->NumberOfAssignedProcesses);
2572             todo_wine
2573             expect_eq_d(2, pid_list->NumberOfProcessIdsInList);
2574             todo_wine
2575             expect_eq_d(pi[0].dwProcessId, list[0]);
2576             todo_wine
2577             expect_eq_d(pi[1].dwProcessId, list[1]);
2578         }
2579     }
2580 
2581     /* test JobObjectBasicLimitInformation */
2582     ret = pQueryInformationJobObject(job, JobObjectBasicLimitInformation, basic_limit_info,
2583                                      sizeof(*basic_limit_info) - 1, &ret_len);
2584     ok(!ret, "QueryInformationJobObject expected failure\n");
2585     expect_eq_d(ERROR_BAD_LENGTH, GetLastError());
2586 
2587     ret_len = 0xdeadbeef;
2588     memset(basic_limit_info, 0x11, sizeof(*basic_limit_info));
2589     ret = pQueryInformationJobObject(job, JobObjectBasicLimitInformation, basic_limit_info,
2590                                      sizeof(*basic_limit_info), &ret_len);
2591     ok(ret, "QueryInformationJobObject error %u\n", GetLastError());
2592     ok(ret_len == sizeof(*basic_limit_info), "QueryInformationJobObject returned ret_len=%u\n", ret_len);
2593     expect_eq_d(0, basic_limit_info->LimitFlags);
2594 
2595     /* test JobObjectExtendedLimitInformation */
2596     ret = pQueryInformationJobObject(job, JobObjectExtendedLimitInformation, &ext_limit_info,
2597                                      sizeof(ext_limit_info) - 1, &ret_len);
2598     ok(!ret, "QueryInformationJobObject expected failure\n");
2599     expect_eq_d(ERROR_BAD_LENGTH, GetLastError());
2600 
2601     ret_len = 0xdeadbeef;
2602     memset(&ext_limit_info, 0x11, sizeof(ext_limit_info));
2603     ret = pQueryInformationJobObject(job, JobObjectExtendedLimitInformation, &ext_limit_info,
2604                                      sizeof(ext_limit_info), &ret_len);
2605     ok(ret, "QueryInformationJobObject error %u\n", GetLastError());
2606     ok(ret_len == sizeof(ext_limit_info), "QueryInformationJobObject returned ret_len=%u\n", ret_len);
2607     expect_eq_d(0, basic_limit_info->LimitFlags);
2608 
2609     TerminateProcess(pi[0].hProcess, 0);
2610     CloseHandle(pi[0].hProcess);
2611     CloseHandle(pi[0].hThread);
2612 
2613     TerminateProcess(pi[1].hProcess, 0);
2614     CloseHandle(pi[1].hProcess);
2615     CloseHandle(pi[1].hThread);
2616 
2617     CloseHandle(job);
2618 }
2619 
2620 static void test_CompletionPort(void)
2621 {
2622     JOBOBJECT_ASSOCIATE_COMPLETION_PORT port_info;
2623     PROCESS_INFORMATION pi;
2624     HANDLE job, port;
2625     DWORD dwret;
2626     BOOL ret;
2627 
2628     job = pCreateJobObjectW(NULL, NULL);
2629     ok(job != NULL, "CreateJobObject error %u\n", GetLastError());
2630 
2631     port = pCreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
2632     ok(port != NULL, "CreateIoCompletionPort error %u\n", GetLastError());
2633 
2634     port_info.CompletionKey = job;
2635     port_info.CompletionPort = port;
2636     ret = pSetInformationJobObject(job, JobObjectAssociateCompletionPortInformation, &port_info, sizeof(port_info));
2637     ok(ret, "SetInformationJobObject error %u\n", GetLastError());
2638 
2639     create_process("wait", &pi);
2640 
2641     ret = pAssignProcessToJobObject(job, pi.hProcess);
2642     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2643 
2644     test_completion(port, JOB_OBJECT_MSG_NEW_PROCESS, (DWORD_PTR)job, pi.dwProcessId, 0);
2645 
2646     TerminateProcess(pi.hProcess, 0);
2647     dwret = WaitForSingleObject(pi.hProcess, 1000);
2648     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2649 
2650     test_completion(port, JOB_OBJECT_MSG_EXIT_PROCESS, (DWORD_PTR)job, pi.dwProcessId, 0);
2651     test_completion(port, JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO, (DWORD_PTR)job, 0, 100);
2652 
2653     CloseHandle(pi.hProcess);
2654     CloseHandle(pi.hThread);
2655     CloseHandle(job);
2656     CloseHandle(port);
2657 }
2658 
2659 static void test_KillOnJobClose(void)
2660 {
2661     JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info;
2662     PROCESS_INFORMATION pi;
2663     DWORD dwret;
2664     HANDLE job;
2665     BOOL ret;
2666 
2667     job = pCreateJobObjectW(NULL, NULL);
2668     ok(job != NULL, "CreateJobObject error %u\n", GetLastError());
2669 
2670     limit_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
2671     ret = pSetInformationJobObject(job, JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info));
2672     if (!ret && GetLastError() == ERROR_INVALID_PARAMETER)
2673     {
2674         win_skip("Kill on job close limit not available\n");
2675         return;
2676     }
2677     ok(ret, "SetInformationJobObject error %u\n", GetLastError());
2678 
2679     create_process("wait", &pi);
2680 
2681     ret = pAssignProcessToJobObject(job, pi.hProcess);
2682     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2683 
2684     CloseHandle(job);
2685 
2686     dwret = WaitForSingleObject(pi.hProcess, 1000);
2687     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2688     if (dwret == WAIT_TIMEOUT) TerminateProcess(pi.hProcess, 0);
2689 
2690     CloseHandle(pi.hProcess);
2691     CloseHandle(pi.hThread);
2692 }
2693 
2694 static void test_WaitForJobObject(void)
2695 {
2696     HANDLE job;
2697     PROCESS_INFORMATION pi;
2698     BOOL ret;
2699     DWORD dwret;
2700 
2701     /* test waiting for a job object when the process is killed */
2702     job = pCreateJobObjectW(NULL, NULL);
2703     ok(job != NULL, "CreateJobObject error %u\n", GetLastError());
2704 
2705     dwret = WaitForSingleObject(job, 100);
2706     ok(dwret == WAIT_TIMEOUT, "WaitForSingleObject returned %u\n", dwret);
2707 
2708     create_process("wait", &pi);
2709 
2710     ret = pAssignProcessToJobObject(job, pi.hProcess);
2711     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2712 
2713     dwret = WaitForSingleObject(job, 100);
2714     ok(dwret == WAIT_TIMEOUT, "WaitForSingleObject returned %u\n", dwret);
2715 
2716     ret = pTerminateJobObject(job, 123);
2717     ok(ret, "TerminateJobObject error %u\n", GetLastError());
2718 
2719     dwret = WaitForSingleObject(job, 500);
2720     ok(dwret == WAIT_OBJECT_0 || broken(dwret == WAIT_TIMEOUT),
2721        "WaitForSingleObject returned %u\n", dwret);
2722 
2723     if (dwret == WAIT_TIMEOUT) /* Win 2000/XP */
2724     {
2725 #ifdef __REACTOS__
2726         if (!ret)
2727         {
2728             ok(0, "HACK: Killing process to speed up the test\n");
2729             TerminateProcess(pi.hProcess, 0);
2730         }
2731 #endif
2732         CloseHandle(pi.hProcess);
2733         CloseHandle(pi.hThread);
2734         CloseHandle(job);
2735         win_skip("TerminateJobObject doesn't signal job, skipping tests\n");
2736         return;
2737     }
2738 
2739     /* the object is not reset immediately */
2740     dwret = WaitForSingleObject(job, 100);
2741     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2742 
2743     CloseHandle(pi.hProcess);
2744     CloseHandle(pi.hThread);
2745 
2746     /* creating a new process doesn't reset the signalled state */
2747     create_process("wait", &pi);
2748 
2749     ret = pAssignProcessToJobObject(job, pi.hProcess);
2750     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2751 
2752     dwret = WaitForSingleObject(job, 100);
2753     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2754 
2755     ret = pTerminateJobObject(job, 123);
2756     ok(ret, "TerminateJobObject error %u\n", GetLastError());
2757 
2758     CloseHandle(pi.hProcess);
2759     CloseHandle(pi.hThread);
2760 
2761     CloseHandle(job);
2762 
2763     /* repeat the test, but this time the process terminates properly */
2764     job = pCreateJobObjectW(NULL, NULL);
2765     ok(job != NULL, "CreateJobObject error %u\n", GetLastError());
2766 
2767     dwret = WaitForSingleObject(job, 100);
2768     ok(dwret == WAIT_TIMEOUT, "WaitForSingleObject returned %u\n", dwret);
2769 
2770     create_process("exit", &pi);
2771 
2772     ret = pAssignProcessToJobObject(job, pi.hProcess);
2773     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2774 
2775     dwret = WaitForSingleObject(job, 100);
2776     ok(dwret == WAIT_TIMEOUT, "WaitForSingleObject returned %u\n", dwret);
2777 
2778     CloseHandle(pi.hProcess);
2779     CloseHandle(pi.hThread);
2780     CloseHandle(job);
2781 }
2782 
2783 static HANDLE test_AddSelfToJob(void)
2784 {
2785     HANDLE job;
2786     BOOL ret;
2787 
2788     job = pCreateJobObjectW(NULL, NULL);
2789     ok(job != NULL, "CreateJobObject error %u\n", GetLastError());
2790 
2791     ret = pAssignProcessToJobObject(job, GetCurrentProcess());
2792     ok(ret, "AssignProcessToJobObject error %u\n", GetLastError());
2793 
2794     return job;
2795 }
2796 
2797 static void test_jobInheritance(HANDLE job)
2798 {
2799     char buffer[MAX_PATH];
2800     PROCESS_INFORMATION pi;
2801     STARTUPINFOA si = {0};
2802     DWORD dwret;
2803     BOOL ret, out;
2804 
2805     if (!pIsProcessInJob)
2806     {
2807         win_skip("IsProcessInJob not available.\n");
2808         return;
2809     }
2810 
2811     sprintf(buffer, "\"%s\" tests/process.c %s", selfname, "exit");
2812 
2813     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2814     ok(ret, "CreateProcessA error %u\n", GetLastError());
2815 
2816     out = FALSE;
2817     ret = pIsProcessInJob(pi.hProcess, job, &out);
2818     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2819     ok(out, "IsProcessInJob returned out=%u\n", out);
2820 
2821     dwret = WaitForSingleObject(pi.hProcess, 1000);
2822     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2823 
2824     CloseHandle(pi.hProcess);
2825     CloseHandle(pi.hThread);
2826 }
2827 
2828 static void test_BreakawayOk(HANDLE job)
2829 {
2830     JOBOBJECT_EXTENDED_LIMIT_INFORMATION limit_info;
2831     PROCESS_INFORMATION pi;
2832     STARTUPINFOA si = {0};
2833     char buffer[MAX_PATH];
2834     BOOL ret, out;
2835     DWORD dwret;
2836 
2837     if (!pIsProcessInJob)
2838     {
2839         win_skip("IsProcessInJob not available.\n");
2840         return;
2841     }
2842 
2843     sprintf(buffer, "\"%s\" tests/process.c %s", selfname, "exit");
2844 
2845     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, CREATE_BREAKAWAY_FROM_JOB, NULL, NULL, &si, &pi);
2846     ok(!ret, "CreateProcessA expected failure\n");
2847     expect_eq_d(ERROR_ACCESS_DENIED, GetLastError());
2848 
2849     if (ret)
2850     {
2851         TerminateProcess(pi.hProcess, 0);
2852 
2853         dwret = WaitForSingleObject(pi.hProcess, 1000);
2854         ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2855 
2856         CloseHandle(pi.hProcess);
2857         CloseHandle(pi.hThread);
2858     }
2859 
2860     limit_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_BREAKAWAY_OK;
2861     ret = pSetInformationJobObject(job, JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info));
2862     ok(ret, "SetInformationJobObject error %u\n", GetLastError());
2863 
2864     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, CREATE_BREAKAWAY_FROM_JOB, NULL, NULL, &si, &pi);
2865     ok(ret, "CreateProcessA error %u\n", GetLastError());
2866 
2867     ret = pIsProcessInJob(pi.hProcess, job, &out);
2868     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2869     ok(!out, "IsProcessInJob returned out=%u\n", out);
2870 
2871     dwret = WaitForSingleObject(pi.hProcess, 1000);
2872     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2873 
2874     CloseHandle(pi.hProcess);
2875     CloseHandle(pi.hThread);
2876 
2877     limit_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK;
2878     ret = pSetInformationJobObject(job, JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info));
2879     ok(ret, "SetInformationJobObject error %u\n", GetLastError());
2880 
2881     ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
2882     ok(ret, "CreateProcess error %u\n", GetLastError());
2883 
2884     ret = pIsProcessInJob(pi.hProcess, job, &out);
2885     ok(ret, "IsProcessInJob error %u\n", GetLastError());
2886     ok(!out, "IsProcessInJob returned out=%u\n", out);
2887 
2888     dwret = WaitForSingleObject(pi.hProcess, 1000);
2889     ok(dwret == WAIT_OBJECT_0, "WaitForSingleObject returned %u\n", dwret);
2890 
2891     CloseHandle(pi.hProcess);
2892     CloseHandle(pi.hThread);
2893 
2894     /* unset breakaway ok */
2895     limit_info.BasicLimitInformation.LimitFlags = 0;
2896     ret = pSetInformationJobObject(job, JobObjectExtendedLimitInformation, &limit_info, sizeof(limit_info));
2897     ok(ret, "SetInformationJobObject error %u\n", GetLastError());
2898 }
2899 
2900 static void test_StartupNoConsole(void)
2901 {
2902 #ifndef _WIN64
2903     char                buffer[MAX_PATH];
2904     STARTUPINFOA        startup;
2905     PROCESS_INFORMATION info;
2906 
2907     memset(&startup, 0, sizeof(startup));
2908     startup.cb = sizeof(startup);
2909     startup.dwFlags = STARTF_USESHOWWINDOW;
2910     startup.wShowWindow = SW_SHOWNORMAL;
2911     get_file_name(resfile);
2912     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
2913     ok(CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &startup,
2914                       &info), "CreateProcess\n");
2915     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
2916     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
2917     okChildInt("StartupInfoA", "hStdInput", (UINT)INVALID_HANDLE_VALUE);
2918     okChildInt("StartupInfoA", "hStdOutput", (UINT)INVALID_HANDLE_VALUE);
2919     okChildInt("StartupInfoA", "hStdError", (UINT)INVALID_HANDLE_VALUE);
2920     okChildInt("TEB", "hStdInput", 0);
2921     okChildInt("TEB", "hStdOutput", 0);
2922     okChildInt("TEB", "hStdError", 0);
2923     release_memory();
2924     DeleteFileA(resfile);
2925 #endif
2926 }
2927 
2928 static void test_DetachConsoleHandles(void)
2929 {
2930 #ifndef _WIN64
2931     char                buffer[MAX_PATH];
2932     STARTUPINFOA        startup;
2933     PROCESS_INFORMATION info;
2934     UINT                result;
2935 
2936     memset(&startup, 0, sizeof(startup));
2937     startup.cb = sizeof(startup);
2938     startup.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
2939     startup.wShowWindow = SW_SHOWNORMAL;
2940     startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
2941     startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
2942     startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
2943     get_file_name(resfile);
2944     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
2945     ok(CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &startup,
2946                       &info), "CreateProcess\n");
2947     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
2948     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
2949 
2950     result = GetPrivateProfileIntA("StartupInfoA", "hStdInput", 0, resfile);
2951     ok(result != 0 && result != (UINT)INVALID_HANDLE_VALUE, "bad handle %x\n", result);
2952     result = GetPrivateProfileIntA("StartupInfoA", "hStdOutput", 0, resfile);
2953     ok(result != 0 && result != (UINT)INVALID_HANDLE_VALUE, "bad handle %x\n", result);
2954     result = GetPrivateProfileIntA("StartupInfoA", "hStdError", 0, resfile);
2955     ok(result != 0 && result != (UINT)INVALID_HANDLE_VALUE, "bad handle %x\n", result);
2956     result = GetPrivateProfileIntA("TEB", "hStdInput", 0, resfile);
2957     ok(result != 0 && result != (UINT)INVALID_HANDLE_VALUE, "bad handle %x\n", result);
2958     result = GetPrivateProfileIntA("TEB", "hStdOutput", 0, resfile);
2959     ok(result != 0 && result != (UINT)INVALID_HANDLE_VALUE, "bad handle %x\n", result);
2960     result = GetPrivateProfileIntA("TEB", "hStdError", 0, resfile);
2961     ok(result != 0 && result != (UINT)INVALID_HANDLE_VALUE, "bad handle %x\n", result);
2962 
2963     release_memory();
2964     DeleteFileA(resfile);
2965 #endif
2966 }
2967 
2968 static void test_DetachStdHandles(void)
2969 {
2970 #ifndef _WIN64
2971     char                buffer[MAX_PATH], tempfile[MAX_PATH];
2972     STARTUPINFOA        startup;
2973     PROCESS_INFORMATION info;
2974     HANDLE              hstdin, hstdout, hstderr, htemp;
2975     BOOL                res;
2976 
2977     hstdin = GetStdHandle(STD_INPUT_HANDLE);
2978     hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
2979     hstderr = GetStdHandle(STD_ERROR_HANDLE);
2980 
2981     get_file_name(tempfile);
2982     htemp = CreateFileA(tempfile, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
2983     ok(htemp != INVALID_HANDLE_VALUE, "failed opening temporary file\n");
2984 
2985     memset(&startup, 0, sizeof(startup));
2986     startup.cb = sizeof(startup);
2987     startup.dwFlags = STARTF_USESHOWWINDOW;
2988     startup.wShowWindow = SW_SHOWNORMAL;
2989     get_file_name(resfile);
2990     sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, resfile);
2991 
2992     SetStdHandle(STD_INPUT_HANDLE, htemp);
2993     SetStdHandle(STD_OUTPUT_HANDLE, htemp);
2994     SetStdHandle(STD_ERROR_HANDLE, htemp);
2995 
2996     res = CreateProcessA(NULL, buffer, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &startup,
2997                       &info);
2998 
2999     SetStdHandle(STD_INPUT_HANDLE, hstdin);
3000     SetStdHandle(STD_OUTPUT_HANDLE, hstdout);
3001     SetStdHandle(STD_ERROR_HANDLE, hstderr);
3002 
3003     ok(res, "CreateProcess failed\n");
3004     ok(WaitForSingleObject(info.hProcess, 30000) == WAIT_OBJECT_0, "Child process termination\n");
3005     WritePrivateProfileStringA(NULL, NULL, NULL, resfile);
3006     okChildInt("StartupInfoA", "hStdInput", (UINT)INVALID_HANDLE_VALUE);
3007     okChildInt("StartupInfoA", "hStdOutput", (UINT)INVALID_HANDLE_VALUE);
3008     okChildInt("StartupInfoA", "hStdError", (UINT)INVALID_HANDLE_VALUE);
3009     okChildInt("TEB", "hStdInput", 0);
3010     okChildInt("TEB", "hStdOutput", 0);
3011     okChildInt("TEB", "hStdError", 0);
3012     release_memory();
3013     DeleteFileA(resfile);
3014 
3015     CloseHandle(htemp);
3016     DeleteFileA(tempfile);
3017 #endif
3018 }
3019 
3020 static void test_GetNumaProcessorNode(void)
3021 {
3022     SYSTEM_INFO si;
3023     UCHAR node;
3024     BOOL ret;
3025     int i;
3026 
3027     if (!pGetNumaProcessorNode)
3028     {
3029         win_skip("GetNumaProcessorNode is missing\n");
3030         return;
3031     }
3032 
3033     GetSystemInfo(&si);
3034     for (i = 0; i < 256; i++)
3035     {
3036         SetLastError(0xdeadbeef);
3037         node = (i < si.dwNumberOfProcessors) ? 0xFF : 0xAA;
3038         ret = pGetNumaProcessorNode(i, &node);
3039         if (i < si.dwNumberOfProcessors)
3040         {
3041             ok(ret, "GetNumaProcessorNode returned FALSE for processor %d\n", i);
3042             ok(node != 0xFF, "expected node != 0xFF, but got 0xFF\n");
3043         }
3044         else
3045         {
3046             ok(!ret, "GetNumaProcessorNode returned TRUE for processor %d\n", i);
3047             ok(node == 0xFF || broken(node == 0xAA) /* WinXP */, "expected node 0xFF, got %x\n", node);
3048             ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
3049         }
3050     }
3051 }
3052 
3053 static void test_session_info(void)
3054 {
3055     DWORD session_id, active_session;
3056     BOOL r;
3057 
3058     if (!pProcessIdToSessionId)
3059     {
3060         win_skip("ProcessIdToSessionId is missing\n");
3061         return;
3062     }
3063 
3064     r = pProcessIdToSessionId(GetCurrentProcessId(), &session_id);
3065     ok(r, "ProcessIdToSessionId failed: %u\n", GetLastError());
3066     trace("session_id = %x\n", session_id);
3067 
3068     active_session = pWTSGetActiveConsoleSessionId();
3069     trace("active_session = %x\n", active_session);
3070 }
3071 
3072 static void test_process_info(void)
3073 {
3074     char buf[4096];
3075     static const ULONG info_size[] =
3076     {
3077         sizeof(PROCESS_BASIC_INFORMATION) /* ProcessBasicInformation */,
3078         sizeof(QUOTA_LIMITS) /* ProcessQuotaLimits */,
3079         sizeof(IO_COUNTERS) /* ProcessIoCounters */,
3080         sizeof(VM_COUNTERS) /* ProcessVmCounters */,
3081         sizeof(KERNEL_USER_TIMES) /* ProcessTimes */,
3082         sizeof(ULONG) /* ProcessBasePriority */,
3083         sizeof(ULONG) /* ProcessRaisePriority */,
3084         sizeof(HANDLE) /* ProcessDebugPort */,
3085         sizeof(HANDLE) /* ProcessExceptionPort */,
3086         0 /* FIXME: sizeof(PROCESS_ACCESS_TOKEN) ProcessAccessToken */,
3087         0 /* FIXME: sizeof(PROCESS_LDT_INFORMATION) ProcessLdtInformation */,
3088         0 /* FIXME: sizeof(PROCESS_LDT_SIZE) ProcessLdtSize */,
3089         sizeof(ULONG) /* ProcessDefaultHardErrorMode */,
3090         0 /* ProcessIoPortHandlers: kernel-mode only */,
3091         0 /* FIXME: sizeof(POOLED_USAGE_AND_LIMITS) ProcessPooledUsageAndLimits */,
3092         0 /* FIXME: sizeof(PROCESS_WS_WATCH_INFORMATION) ProcessWorkingSetWatch */,
3093         sizeof(ULONG) /* ProcessUserModeIOPL */,
3094         sizeof(BOOLEAN) /* ProcessEnableAlignmentFaultFixup */,
3095         sizeof(PROCESS_PRIORITY_CLASS) /* ProcessPriorityClass */,
3096         sizeof(ULONG) /* ProcessWx86Information */,
3097         sizeof(ULONG) /* ProcessHandleCount */,
3098         sizeof(ULONG_PTR) /* ProcessAffinityMask */,
3099         sizeof(ULONG) /* ProcessPriorityBoost */,
3100         0 /* sizeof(PROCESS_DEVICEMAP_INFORMATION) ProcessDeviceMap */,
3101         0 /* sizeof(PROCESS_SESSION_INFORMATION) ProcessSessionInformation */,
3102         0 /* sizeof(PROCESS_FOREGROUND_BACKGROUND) ProcessForegroundInformation */,
3103         sizeof(ULONG_PTR) /* ProcessWow64Information */,
3104         sizeof(buf) /* ProcessImageFileName */,
3105         sizeof(ULONG) /* ProcessLUIDDeviceMapsEnabled */,
3106         sizeof(ULONG) /* ProcessBreakOnTermination */,
3107         sizeof(HANDLE) /* ProcessDebugObjectHandle */,
3108         sizeof(ULONG) /* ProcessDebugFlags */,
3109         sizeof(buf) /* ProcessHandleTracing */,
3110         sizeof(ULONG) /* ProcessIoPriority */,
3111         sizeof(ULONG) /* ProcessExecuteFlags */,
3112         0 /* FIXME: sizeof(?) ProcessTlsInformation */,
3113         0 /* FIXME: sizeof(?) ProcessCookie */,
3114         sizeof(SECTION_IMAGE_INFORMATION) /* ProcessImageInformation */,
3115         0 /* FIXME: sizeof(PROCESS_CYCLE_TIME_INFORMATION) ProcessCycleTime */,
3116         sizeof(ULONG) /* ProcessPagePriority */,
3117         40 /* ProcessInstrumentationCallback */,
3118         0 /* FIXME: sizeof(PROCESS_STACK_ALLOCATION_INFORMATION) ProcessThreadStackAllocation */,
3119         0 /* FIXME: sizeof(PROCESS_WS_WATCH_INFORMATION_EX[]) ProcessWorkingSetWatchEx */,
3120         sizeof(buf) /* ProcessImageFileNameWin32 */,
3121         sizeof(HANDLE) /* ProcessImageFileMapping */,
3122         0 /* FIXME: sizeof(PROCESS_AFFINITY_UPDATE_MODE) ProcessAffinityUpdateMode */,
3123         0 /* FIXME: sizeof(PROCESS_MEMORY_ALLOCATION_MODE) ProcessMemoryAllocationMode */,
3124         sizeof(USHORT) /* ProcessGroupInformation */,
3125         sizeof(ULONG) /* ProcessTokenVirtualizationEnabled */,
3126         sizeof(ULONG_PTR) /* ProcessConsoleHostProcess */,
3127         0 /* FIXME: sizeof(PROCESS_WINDOW_INFORMATION) ProcessWindowInformation */,
3128 #if 0 /* FIXME: Add remaining classes */
3129         sizeof(PROCESS_HANDLE_SNAPSHOT_INFORMATION) /* ProcessHandleInformation */,
3130         sizeof(PROCESS_MITIGATION_POLICY_INFORMATION) /* ProcessMitigationPolicy */,
3131         sizeof(ProcessDynamicFunctionTableInformation) /* ProcessDynamicFunctionTableInformation */,
3132         sizeof(?) /* ProcessHandleCheckingMode */,
3133         sizeof(PROCESS_KEEPALIVE_COUNT_INFORMATION) /* ProcessKeepAliveCount */,
3134         sizeof(PROCESS_REVOKE_FILE_HANDLES_INFORMATION) /* ProcessRevokeFileHandles */,
3135         sizeof(PROCESS_WORKING_SET_CONTROL) /* ProcessWorkingSetControl */,
3136         sizeof(?) /* ProcessHandleTable */,
3137         sizeof(?) /* ProcessCheckStackExtentsMode */,
3138         sizeof(buf) /* ProcessCommandLineInformation */,
3139         sizeof(PS_PROTECTION) /* ProcessProtectionInformation */,
3140         sizeof(PROCESS_MEMORY_EXHAUSTION_INFO) /* ProcessMemoryExhaustion */,
3141         sizeof(PROCESS_FAULT_INFORMATION) /* ProcessFaultInformation */,
3142         sizeof(PROCESS_TELEMETRY_ID_INFORMATION) /* ProcessTelemetryIdInformation */,
3143         sizeof(PROCESS_COMMIT_RELEASE_INFORMATION) /* ProcessCommitReleaseInformation */,
3144         sizeof(?) /* ProcessDefaultCpuSetsInformation */,
3145         sizeof(?) /* ProcessAllowedCpuSetsInformation */,
3146         0 /* ProcessReserved1Information */,
3147         0 /* ProcessReserved2Information */,
3148         sizeof(?) /* ProcessSubsystemProcess */,
3149         sizeof(PROCESS_JOB_MEMORY_INFO) /* ProcessJobMemoryInformation */,
3150 #endif
3151     };
3152     HANDLE hproc;
3153     ULONG i, status, ret_len, size;
3154 
3155     if (!pNtQueryInformationProcess)
3156     {
3157         win_skip("NtQueryInformationProcess is not available on this platform\n");
3158         return;
3159     }
3160 
3161     hproc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, GetCurrentProcessId());
3162     if (!hproc)
3163     {
3164         win_skip("PROCESS_QUERY_LIMITED_INFORMATION is not supported on this platform\n");
3165         return;
3166     }
3167 
3168     for (i = 0; i < MaxProcessInfoClass; i++)
3169     {
3170         size = info_size[i];
3171         if (!size) size = sizeof(buf);
3172         ret_len = 0;
3173         status = pNtQueryInformationProcess(hproc, i, buf, info_size[i], &ret_len);
3174         if (status == STATUS_NOT_IMPLEMENTED) continue;
3175         if (status == STATUS_INVALID_INFO_CLASS) continue;
3176         if (status == STATUS_INFO_LENGTH_MISMATCH) continue;
3177 
3178         switch (i)
3179         {
3180         case ProcessBasicInformation:
3181         case ProcessQuotaLimits:
3182         case ProcessTimes:
3183         case ProcessPriorityClass:
3184         case ProcessPriorityBoost:
3185         case ProcessLUIDDeviceMapsEnabled:
3186         case 33 /* ProcessIoPriority */:
3187         case ProcessIoCounters:
3188         case ProcessVmCounters:
3189         case ProcessWow64Information:
3190         case ProcessDefaultHardErrorMode:
3191         case ProcessHandleCount:
3192         case ProcessImageFileName:
3193         case ProcessImageInformation:
3194         case ProcessPagePriority:
3195         case ProcessImageFileNameWin32:
3196             ok(status == STATUS_SUCCESS, "for info %u expected STATUS_SUCCESS, got %08x (ret_len %u)\n", i, status, ret_len);
3197             break;
3198 
3199         case ProcessAffinityMask:
3200         case ProcessBreakOnTermination:
3201         case ProcessGroupInformation:
3202         case ProcessConsoleHostProcess:
3203             ok(status == STATUS_ACCESS_DENIED /* before win8 */ || status == STATUS_SUCCESS /* win8 is less strict */,
3204                "for info %u expected STATUS_SUCCESS, got %08x (ret_len %u)\n", i, status, ret_len);
3205             break;
3206 
3207         case ProcessDebugObjectHandle:
3208             ok(status == STATUS_ACCESS_DENIED || status == STATUS_PORT_NOT_SET,
3209                "for info %u expected STATUS_ACCESS_DENIED, got %08x (ret_len %u)\n", i, status, ret_len);
3210             break;
3211 
3212         case ProcessExecuteFlags:
3213         case ProcessDebugPort:
3214         case ProcessDebugFlags:
3215         case ProcessCookie:
3216 todo_wine
3217             ok(status == STATUS_ACCESS_DENIED, "for info %u expected STATUS_ACCESS_DENIED, got %08x (ret_len %u)\n", i, status, ret_len);
3218             break;
3219 
3220         default:
3221             ok(status == STATUS_ACCESS_DENIED, "for info %u expected STATUS_ACCESS_DENIED, got %08x (ret_len %u)\n", i, status, ret_len);
3222             break;
3223         }
3224     }
3225 
3226     CloseHandle(hproc);
3227 }
3228 
3229 static void test_GetLogicalProcessorInformationEx(void)
3230 {
3231     SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *info;
3232     DWORD len;
3233     BOOL ret;
3234 
3235     if (!pGetLogicalProcessorInformationEx)
3236     {
3237         win_skip("GetLogicalProcessorInformationEx() is not supported\n");
3238         return;
3239     }
3240 
3241     ret = pGetLogicalProcessorInformationEx(RelationAll, NULL, NULL);
3242     ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "got %d, error %d\n", ret, GetLastError());
3243 
3244     len = 0;
3245     ret = pGetLogicalProcessorInformationEx(RelationProcessorCore, NULL, &len);
3246     ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d, error %d\n", ret, GetLastError());
3247     ok(len > 0, "got %u\n", len);
3248 
3249     len = 0;
3250     ret = pGetLogicalProcessorInformationEx(RelationAll, NULL, &len);
3251     ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d, error %d\n", ret, GetLastError());
3252     ok(len > 0, "got %u\n", len);
3253 
3254     info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
3255     ret = pGetLogicalProcessorInformationEx(RelationAll, info, &len);
3256     ok(ret, "got %d, error %d\n", ret, GetLastError());
3257     ok(info->Size > 0, "got %u\n", info->Size);
3258     HeapFree(GetProcessHeap(), 0, info);
3259 }
3260 
3261 static void test_largepages(void)
3262 {
3263     SIZE_T size;
3264 
3265     if (!pGetLargePageMinimum) {
3266         skip("No GetLargePageMinimum support.\n");
3267         return;
3268     }
3269     size = pGetLargePageMinimum();
3270 
3271     ok((size == 0) || (size == 2*1024*1024) || (size == 4*1024*1024), "GetLargePageMinimum reports %ld size\n", size);
3272 }
3273 
3274 struct proc_thread_attr
3275 {
3276     DWORD_PTR attr;
3277     SIZE_T size;
3278     void *value;
3279 };
3280 
3281 struct _PROC_THREAD_ATTRIBUTE_LIST
3282 {
3283     DWORD mask;  /* bitmask of items in list */
3284     DWORD size;  /* max number of items in list */
3285     DWORD count; /* number of items in list */
3286     DWORD pad;
3287     DWORD_PTR unk;
3288     struct proc_thread_attr attrs[10];
3289 };
3290 
3291 static void test_ProcThreadAttributeList(void)
3292 {
3293     BOOL ret;
3294     SIZE_T size, needed;
3295     int i;
3296     struct _PROC_THREAD_ATTRIBUTE_LIST list, expect_list;
3297     HANDLE handles[4];
3298 
3299     if (!pInitializeProcThreadAttributeList)
3300     {
3301         win_skip("No support for ProcThreadAttributeList\n");
3302         return;
3303     }
3304 
3305     for (i = 0; i <= 10; i++)
3306     {
3307         needed = FIELD_OFFSET(struct _PROC_THREAD_ATTRIBUTE_LIST, attrs[i]);
3308         ret = pInitializeProcThreadAttributeList(NULL, i, 0, &size);
3309         ok(!ret, "got %d\n", ret);
3310         if(i >= 4 && GetLastError() == ERROR_INVALID_PARAMETER) /* Vista only allows a maximium of 3 slots */
3311             break;
3312         ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d\n", GetLastError());
3313         ok(size == needed, "%d: got %ld expect %ld\n", i, size, needed);
3314 
3315         memset(&list, 0xcc, sizeof(list));
3316         ret = pInitializeProcThreadAttributeList(&list, i, 0, &size);
3317         ok(ret, "got %d\n", ret);
3318         ok(list.mask == 0, "%d: got %08x\n", i, list.mask);
3319         ok(list.size == i, "%d: got %08x\n", i, list.size);
3320         ok(list.count == 0, "%d: got %08x\n", i, list.count);
3321         ok(list.unk == 0, "%d: got %08lx\n", i, list.unk);
3322     }
3323 
3324     memset(handles, 0, sizeof(handles));
3325     memset(&expect_list, 0xcc, sizeof(expect_list));
3326     expect_list.mask = 0;
3327     expect_list.size = i - 1;
3328     expect_list.count = 0;
3329     expect_list.unk = 0;
3330 
3331     ret = pUpdateProcThreadAttribute(&list, 0, 0xcafe, handles, sizeof(PROCESSOR_NUMBER), NULL, NULL);
3332     ok(!ret, "got %d\n", ret);
3333     ok(GetLastError() == ERROR_NOT_SUPPORTED, "got %d\n", GetLastError());
3334 
3335     ret = pUpdateProcThreadAttribute(&list, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, handles, sizeof(handles[0]) / 2, NULL, NULL);
3336     ok(!ret, "got %d\n", ret);
3337     ok(GetLastError() == ERROR_BAD_LENGTH, "got %d\n", GetLastError());
3338 
3339     ret = pUpdateProcThreadAttribute(&list, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, handles, sizeof(handles[0]) * 2, NULL, NULL);
3340     ok(!ret, "got %d\n", ret);
3341     ok(GetLastError() == ERROR_BAD_LENGTH, "got %d\n", GetLastError());
3342 
3343     ret = pUpdateProcThreadAttribute(&list, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, handles, sizeof(handles[0]), NULL, NULL);
3344     ok(ret, "got %d\n", ret);
3345 
3346     expect_list.mask |= 1 << ProcThreadAttributeParentProcess;
3347     expect_list.attrs[0].attr = PROC_THREAD_ATTRIBUTE_PARENT_PROCESS;
3348     expect_list.attrs[0].size = sizeof(handles[0]);
3349     expect_list.attrs[0].value = handles;
3350     expect_list.count++;
3351 
3352     ret = pUpdateProcThreadAttribute(&list, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, handles, sizeof(handles[0]), NULL, NULL);
3353     ok(!ret, "got %d\n", ret);
3354     ok(GetLastError() == ERROR_OBJECT_NAME_EXISTS, "got %d\n", GetLastError());
3355 
3356     ret = pUpdateProcThreadAttribute(&list, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles, sizeof(handles) - 1, NULL, NULL);
3357     ok(!ret, "got %d\n", ret);
3358     ok(GetLastError() == ERROR_BAD_LENGTH, "got %d\n", GetLastError());
3359 
3360     ret = pUpdateProcThreadAttribute(&list, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles, sizeof(handles), NULL, NULL);
3361     ok(ret, "got %d\n", ret);
3362 
3363     expect_list.mask |= 1 << ProcThreadAttributeHandleList;
3364     expect_list.attrs[1].attr = PROC_THREAD_ATTRIBUTE_HANDLE_LIST;
3365     expect_list.attrs[1].size = sizeof(handles);
3366     expect_list.attrs[1].value = handles;
3367     expect_list.count++;
3368 
3369     ret = pUpdateProcThreadAttribute(&list, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles, sizeof(handles), NULL, NULL);
3370     ok(!ret, "got %d\n", ret);
3371     ok(GetLastError() == ERROR_OBJECT_NAME_EXISTS, "got %d\n", GetLastError());
3372 
3373     ret = pUpdateProcThreadAttribute(&list, 0, PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR, handles, sizeof(PROCESSOR_NUMBER), NULL, NULL);
3374     ok(ret || (!ret && GetLastError() == ERROR_NOT_SUPPORTED), "got %d gle %d\n", ret, GetLastError());
3375 
3376     if (ret)
3377     {
3378         expect_list.mask |= 1 << ProcThreadAttributeIdealProcessor;
3379         expect_list.attrs[2].attr = PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR;
3380         expect_list.attrs[2].size = sizeof(PROCESSOR_NUMBER);
3381         expect_list.attrs[2].value = handles;
3382         expect_list.count++;
3383     }
3384 
3385     ok(!memcmp(&list, &expect_list, size), "mismatch\n");
3386 
3387     pDeleteProcThreadAttributeList(&list);
3388 }
3389 
3390 static void test_GetActiveProcessorCount(void)
3391 {
3392     DWORD count;
3393 
3394     if (!pGetActiveProcessorCount)
3395     {
3396         win_skip("GetActiveProcessorCount not available, skipping test\n");
3397         return;
3398     }
3399 
3400     count = pGetActiveProcessorCount(0);
3401     ok(count, "GetActiveProcessorCount failed, error %u\n", GetLastError());
3402 
3403     /* Test would fail on systems with more than 6400 processors */
3404     SetLastError(0xdeadbeef);
3405     count = pGetActiveProcessorCount(101);
3406     ok(count == 0, "Expeced GetActiveProcessorCount to fail\n");
3407     ok(GetLastError() == ERROR_INVALID_PARAMETER, "Expected ERROR_INVALID_PARAMETER, got %u\n", GetLastError());
3408 }
3409 
3410 START_TEST(process)
3411 {
3412     HANDLE job;
3413     BOOL b = init();
3414     ok(b, "Basic init of CreateProcess test\n");
3415     if (!b) return;
3416 
3417     if (myARGC >= 3)
3418     {
3419         if (!strcmp(myARGV[2], "dump") && myARGC >= 4)
3420         {
3421             doChild(myARGV[3], (myARGC >= 5) ? myARGV[4] : NULL);
3422             return;
3423         }
3424         else if (!strcmp(myARGV[2], "wait"))
3425         {
3426             Sleep(30000);
3427             ok(0, "Child process not killed\n");
3428             return;
3429         }
3430         else if (!strcmp(myARGV[2], "exit"))
3431         {
3432             Sleep(100);
3433             return;
3434         }
3435         else if (!strcmp(myARGV[2], "nested") && myARGC >= 4)
3436         {
3437             char                buffer[MAX_PATH];
3438             STARTUPINFOA        startup;
3439             PROCESS_INFORMATION info;
3440 
3441             memset(&startup, 0, sizeof(startup));
3442             startup.cb = sizeof(startup);
3443             startup.dwFlags = STARTF_USESHOWWINDOW;
3444             startup.wShowWindow = SW_SHOWNORMAL;
3445 
3446             sprintf(buffer, "\"%s\" tests/process.c dump \"%s\"", selfname, myARGV[3]);
3447             ok(CreateProcessA(NULL, buffer, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &startup, &info), "CreateProcess failed\n");
3448             CloseHandle(info.hProcess);
3449             CloseHandle(info.hThread);
3450             return;
3451         }
3452 
3453         ok(0, "Unexpected command %s\n", myARGV[2]);
3454         return;
3455     }
3456 
3457     test_process_info();
3458     test_TerminateProcess();
3459     test_Startup();
3460     test_CommandLine();
3461     test_Directory();
3462     test_Toolhelp();
3463     test_Environment();
3464     test_SuspendFlag();
3465     test_DebuggingFlag();
3466     test_Console();
3467     test_ExitCode();
3468     test_OpenProcess();
3469     test_GetProcessVersion();
3470     test_GetProcessImageFileNameA();
3471     test_QueryFullProcessImageNameA();
3472     test_QueryFullProcessImageNameW();
3473     test_Handles();
3474     test_IsWow64Process();
3475     test_SystemInfo();
3476     test_RegistryQuota();
3477     test_DuplicateHandle();
3478     test_StartupNoConsole();
3479     test_DetachConsoleHandles();
3480     test_DetachStdHandles();
3481     test_GetNumaProcessorNode();
3482     test_session_info();
3483     test_GetLogicalProcessorInformationEx();
3484     test_GetActiveProcessorCount();
3485     test_largepages();
3486     test_ProcThreadAttributeList();
3487 
3488     /* things that can be tested:
3489      *  lookup:         check the way program to be executed is searched
3490      *  handles:        check the handle inheritance stuff (+sec options)
3491      *  console:        check if console creation parameters work
3492      */
3493 
3494     if (!pCreateJobObjectW)
3495     {
3496         win_skip("No job object support\n");
3497         return;
3498     }
3499 
3500     test_IsProcessInJob();
3501     test_TerminateJobObject();
3502     test_QueryInformationJobObject();
3503     test_CompletionPort();
3504     test_KillOnJobClose();
3505     test_WaitForJobObject();
3506     job = test_AddSelfToJob();
3507     test_jobInheritance(job);
3508     test_BreakawayOk(job);
3509     CloseHandle(job);
3510 }
3511