Release 1.5.29.
[wine] / programs / winetest / main.c
1 /*
2  * Wine Conformance Test EXE
3  *
4  * Copyright 2003, 2004 Jakob Eriksson   (for Solid Form Sweden AB)
5  * Copyright 2003 Dimitrie O. Paun
6  * Copyright 2003 Ferenc Wagner
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  * This program is dedicated to Anna Lindh,
23  * Swedish Minister of Foreign Affairs.
24  * Anna was murdered September 11, 2003.
25  *
26  */
27
28 #include "config.h"
29 #include "wine/port.h"
30
31 #define COBJMACROS
32 #include <stdio.h>
33 #include <assert.h>
34 #include <windows.h>
35 #include <mshtml.h>
36
37 #include "winetest.h"
38 #include "resource.h"
39
40 /* Don't submit the results if more than SKIP_LIMIT tests have been skipped */
41 #define SKIP_LIMIT 10
42
43 /* Don't submit the results if more than FAILURES_LIMIT tests have failed */
44 #define FAILURES_LIMIT 50
45
46 struct wine_test
47 {
48     char *name;
49     int subtest_count;
50     char **subtests;
51     char *exename;
52     char *maindllpath;
53 };
54
55 char *tag = NULL;
56 char *description = NULL;
57 char *url = NULL;
58 char *email = NULL;
59 BOOL aborting = FALSE;
60 static struct wine_test *wine_tests;
61 static int nr_of_files, nr_of_tests, nr_of_skips;
62 static int nr_native_dlls;
63 static const char whitespace[] = " \t\r\n";
64 static const char testexe[] = "_test.exe";
65 static char build_id[64];
66 static BOOL is_wow64;
67 static int failures;
68
69 /* filters for running only specific tests */
70 static char *filters[64];
71 static unsigned int nb_filters = 0;
72 static BOOL exclude_tests = FALSE;
73
74 /* Needed to check for .NET dlls */
75 static HMODULE hmscoree;
76 static HRESULT (WINAPI *pLoadLibraryShim)(LPCWSTR, LPCWSTR, LPVOID, HMODULE *);
77
78 /* For SxS DLLs e.g. msvcr90 */
79 static HANDLE (WINAPI *pCreateActCtxA)(PACTCTXA);
80 static BOOL (WINAPI *pActivateActCtx)(HANDLE, ULONG_PTR *);
81 static BOOL (WINAPI *pDeactivateActCtx)(DWORD, ULONG_PTR);
82 static void (WINAPI *pReleaseActCtx)(HANDLE);
83
84 /* To store the current PATH setting (related to .NET only provided dlls) */
85 static char *curpath;
86
87 /* check if test is being filtered out */
88 static BOOL test_filtered_out( LPCSTR module, LPCSTR testname )
89 {
90     char *p, dllname[MAX_PATH];
91     unsigned int i, len;
92
93     strcpy( dllname, module );
94     CharLowerA( dllname );
95     p = strstr( dllname, testexe );
96     if (p) *p = 0;
97     len = strlen(dllname);
98
99     if (!nb_filters) return exclude_tests;
100     for (i = 0; i < nb_filters; i++)
101     {
102         if (!strncmp( dllname, filters[i], len ))
103         {
104             if (!filters[i][len]) return exclude_tests;
105             if (filters[i][len] != ':') continue;
106             if (testname && !strcmp( testname, &filters[i][len+1] )) return exclude_tests;
107             if (!testname && !exclude_tests) return FALSE;
108         }
109     }
110     return !exclude_tests;
111 }
112
113 static char * get_file_version(char * file_name)
114 {
115     static char version[32];
116     DWORD size;
117     DWORD handle;
118
119     size = GetFileVersionInfoSizeA(file_name, &handle);
120     if (size) {
121         char * data = heap_alloc(size);
122         if (data) {
123             if (GetFileVersionInfoA(file_name, handle, size, data)) {
124                 static char backslash[] = "\\";
125                 VS_FIXEDFILEINFO *pFixedVersionInfo;
126                 UINT len;
127                 if (VerQueryValueA(data, backslash, (LPVOID *)&pFixedVersionInfo, &len)) {
128                     sprintf(version, "%d.%d.%d.%d",
129                             pFixedVersionInfo->dwFileVersionMS >> 16,
130                             pFixedVersionInfo->dwFileVersionMS & 0xffff,
131                             pFixedVersionInfo->dwFileVersionLS >> 16,
132                             pFixedVersionInfo->dwFileVersionLS & 0xffff);
133                 } else
134                     sprintf(version, "version not available");
135             } else
136                 sprintf(version, "unknown");
137             heap_free(data);
138         } else
139             sprintf(version, "failed");
140     } else
141         sprintf(version, "version not available");
142
143     return version;
144 }
145
146 static int running_under_wine (void)
147 {
148     HMODULE module = GetModuleHandleA("ntdll.dll");
149
150     if (!module) return 0;
151     return (GetProcAddress(module, "wine_server_call") != NULL);
152 }
153
154 static int check_mount_mgr(void)
155 {
156     HANDLE handle = CreateFileA( "\\\\.\\MountPointManager", GENERIC_READ,
157                                  FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 );
158     if (handle == INVALID_HANDLE_VALUE) return FALSE;
159     CloseHandle( handle );
160     return TRUE;
161 }
162
163 static int check_wow64_registry(void)
164 {
165     char buffer[MAX_PATH];
166     DWORD type, size = MAX_PATH;
167     HKEY hkey;
168     BOOL ret;
169
170     if (!is_wow64) return TRUE;
171     if (RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion", &hkey ))
172         return FALSE;
173     ret = !RegQueryValueExA( hkey, "ProgramFilesDir (x86)", NULL, &type, (BYTE *)buffer, &size );
174     RegCloseKey( hkey );
175     return ret;
176 }
177
178 static int check_display_driver(void)
179 {
180     HWND hwnd = CreateWindowA( "STATIC", "", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
181                                0, 0, GetModuleHandleA(0), 0 );
182     if (!hwnd) return FALSE;
183     DestroyWindow( hwnd );
184     return TRUE;
185 }
186
187 static int running_on_visible_desktop (void)
188 {
189     HWND desktop;
190     HMODULE huser32 = GetModuleHandleA("user32.dll");
191     HWINSTA (WINAPI *pGetProcessWindowStation)(void);
192     BOOL (WINAPI *pGetUserObjectInformationA)(HANDLE,INT,LPVOID,DWORD,LPDWORD);
193
194     pGetProcessWindowStation = (void *)GetProcAddress(huser32, "GetProcessWindowStation");
195     pGetUserObjectInformationA = (void *)GetProcAddress(huser32, "GetUserObjectInformationA");
196
197     desktop = GetDesktopWindow();
198     if (!GetWindowLongPtrW(desktop, GWLP_WNDPROC)) /* Win9x */
199         return IsWindowVisible(desktop);
200
201     if (pGetProcessWindowStation && pGetUserObjectInformationA)
202     {
203         DWORD len;
204         HWINSTA wstation;
205         USEROBJECTFLAGS uoflags;
206
207         wstation = (HWINSTA)pGetProcessWindowStation();
208         assert(pGetUserObjectInformationA(wstation, UOI_FLAGS, &uoflags, sizeof(uoflags), &len));
209         return (uoflags.dwFlags & WSF_VISIBLE) != 0;
210     }
211     return IsWindowVisible(desktop);
212 }
213
214 static int running_as_admin (void)
215 {
216     PSID administrators = NULL;
217     SID_IDENTIFIER_AUTHORITY nt_authority = { SECURITY_NT_AUTHORITY };
218     HANDLE token;
219     DWORD groups_size;
220     PTOKEN_GROUPS groups;
221     DWORD group_index;
222
223     /* Create a well-known SID for the Administrators group. */
224     if (! AllocateAndInitializeSid(&nt_authority, 2, SECURITY_BUILTIN_DOMAIN_RID,
225                                    DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
226                                    &administrators))
227         return -1;
228
229     /* Get the process token */
230     if (! OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
231     {
232         FreeSid(administrators);
233         return -1;
234     }
235
236     /* Get the group info from the token */
237     groups_size = 0;
238     GetTokenInformation(token, TokenGroups, NULL, 0, &groups_size);
239     groups = heap_alloc(groups_size);
240     if (groups == NULL)
241     {
242         CloseHandle(token);
243         FreeSid(administrators);
244         return -1;
245     }
246     if (! GetTokenInformation(token, TokenGroups, groups, groups_size, &groups_size))
247     {
248         heap_free(groups);
249         CloseHandle(token);
250         FreeSid(administrators);
251         return -1;
252     }
253     CloseHandle(token);
254
255     /* Now check if the token groups include the Administrators group */
256     for (group_index = 0; group_index < groups->GroupCount; group_index++)
257     {
258         if (EqualSid(groups->Groups[group_index].Sid, administrators))
259         {
260             heap_free(groups);
261             FreeSid(administrators);
262             return 1;
263         }
264     }
265
266     /* If we end up here we didn't find the Administrators group */
267     heap_free(groups);
268     FreeSid(administrators);
269     return 0;
270 }
271
272 static int running_elevated (void)
273 {
274     HANDLE token;
275     TOKEN_ELEVATION elevation_info;
276     DWORD size;
277
278     /* Get the process token */
279     if (! OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
280         return -1;
281
282     /* Get the elevation info from the token */
283     if (! GetTokenInformation(token, TokenElevation, &elevation_info,
284                               sizeof(TOKEN_ELEVATION), &size))
285     {
286         CloseHandle(token);
287         return -1;
288     }
289     CloseHandle(token);
290
291     return elevation_info.TokenIsElevated;
292 }
293
294 /* check for native dll when running under wine */
295 static BOOL is_native_dll( HMODULE module )
296 {
297     static const char fakedll_signature[] = "Wine placeholder DLL";
298     const IMAGE_DOS_HEADER *dos;
299
300     if (!running_under_wine()) return FALSE;
301     if (!((ULONG_PTR)module & 1)) return FALSE;  /* not loaded as datafile */
302     /* builtin dlls can't be loaded as datafile, so we must have native or fake dll */
303     dos = (const IMAGE_DOS_HEADER *)((const char *)module - 1);
304     if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
305     if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
306         !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return FALSE;
307     return TRUE;
308 }
309
310 static void print_version (void)
311 {
312 #ifdef __i386__
313     static const char platform[] = "i386";
314 #elif defined(__x86_64__)
315     static const char platform[] = "x86_64";
316 #elif defined(__powerpc__)
317     static const char platform[] = "powerpc";
318 #elif defined(__arm__)
319     static const char platform[] = "arm";
320 #elif defined(__aarch64__)
321     static const char platform[] = "arm64";
322 #else
323 # error CPU unknown
324 #endif
325     OSVERSIONINFOEXA ver;
326     BOOL ext;
327     int is_win2k3_r2, is_admin, is_elevated;
328     const char *(CDECL *wine_get_build_id)(void);
329     void (CDECL *wine_get_host_version)( const char **sysname, const char **release );
330     BOOL (WINAPI *pGetProductInfo)(DWORD, DWORD, DWORD, DWORD, DWORD *);
331
332     ver.dwOSVersionInfoSize = sizeof(ver);
333     if (!(ext = GetVersionExA ((OSVERSIONINFOA *) &ver)))
334     {
335         ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
336         if (!GetVersionExA ((OSVERSIONINFOA *) &ver))
337             report (R_FATAL, "Can't get OS version.");
338     }
339     xprintf ("    Platform=%s%s\n", platform, is_wow64 ? " (WOW64)" : "");
340     xprintf ("    bRunningUnderWine=%d\n", running_under_wine ());
341     xprintf ("    bRunningOnVisibleDesktop=%d\n", running_on_visible_desktop ());
342     is_admin = running_as_admin ();
343     if (0 <= is_admin)
344     {
345         xprintf ("    Account=%s", is_admin ? "admin" : "non-admin");
346         is_elevated = running_elevated ();
347         if (0 <= is_elevated)
348             xprintf(", %s", is_elevated ? "elevated" : "not elevated");
349         xprintf ("\n");
350     }
351     xprintf ("    Submitter=%s\n", email );
352     if (description)
353         xprintf ("    Description=%s\n", description );
354     if (url)
355         xprintf ("    URL=%s\n", url );
356     xprintf ("    dwMajorVersion=%u\n    dwMinorVersion=%u\n"
357              "    dwBuildNumber=%u\n    PlatformId=%u\n    szCSDVersion=%s\n",
358              ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
359              ver.dwPlatformId, ver.szCSDVersion);
360
361     wine_get_build_id = (void *)GetProcAddress(GetModuleHandleA("ntdll.dll"), "wine_get_build_id");
362     wine_get_host_version = (void *)GetProcAddress(GetModuleHandleA("ntdll.dll"), "wine_get_host_version");
363     if (wine_get_build_id) xprintf( "    WineBuild=%s\n", wine_get_build_id() );
364     if (wine_get_host_version)
365     {
366         const char *sysname, *release;
367         wine_get_host_version( &sysname, &release );
368         xprintf( "    Host system=%s\n    Host version=%s\n", sysname, release );
369     }
370     is_win2k3_r2 = GetSystemMetrics(SM_SERVERR2);
371     if(is_win2k3_r2)
372         xprintf("    R2 build number=%d\n", is_win2k3_r2);
373
374     if (!ext) return;
375
376     xprintf ("    wServicePackMajor=%d\n    wServicePackMinor=%d\n"
377              "    wSuiteMask=%d\n    wProductType=%d\n    wReserved=%d\n",
378              ver.wServicePackMajor, ver.wServicePackMinor, ver.wSuiteMask,
379              ver.wProductType, ver.wReserved);
380
381     pGetProductInfo = (void *)GetProcAddress(GetModuleHandleA("kernel32.dll"),"GetProductInfo");
382     if (pGetProductInfo && !running_under_wine())
383     {
384         DWORD prodtype = 0;
385
386         pGetProductInfo(ver.dwMajorVersion, ver.dwMinorVersion, ver.wServicePackMajor, ver.wServicePackMinor, &prodtype);
387         xprintf("    dwProductInfo=%u\n", prodtype);
388     }
389 }
390
391 static void print_language(void)
392 {
393     HMODULE hkernel32;
394     LANGID (WINAPI *pGetUserDefaultUILanguage)(void);
395     LANGID (WINAPI *pGetThreadUILanguage)(void);
396
397     xprintf ("    SystemDefaultLCID=%x\n", GetSystemDefaultLCID());
398     xprintf ("    UserDefaultLCID=%x\n", GetUserDefaultLCID());
399     xprintf ("    ThreadLocale=%x\n", GetThreadLocale());
400
401     hkernel32 = GetModuleHandleA("kernel32.dll");
402     pGetUserDefaultUILanguage = (void*)GetProcAddress(hkernel32, "GetUserDefaultUILanguage");
403     pGetThreadUILanguage = (void*)GetProcAddress(hkernel32, "GetThreadUILanguage");
404     if (pGetUserDefaultUILanguage)
405         xprintf ("    UserDefaultUILanguage=%x\n", pGetUserDefaultUILanguage());
406     if (pGetThreadUILanguage)
407         xprintf ("    ThreadUILanguage=%x\n", pGetThreadUILanguage());
408 }
409
410 static inline int is_dot_dir(const char* x)
411 {
412     return ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))));
413 }
414
415 static void remove_dir (const char *dir)
416 {
417     HANDLE  hFind;
418     WIN32_FIND_DATAA wfd;
419     char path[MAX_PATH];
420     size_t dirlen = strlen (dir);
421
422     /* Make sure the directory exists before going further */
423     memcpy (path, dir, dirlen);
424     strcpy (path + dirlen++, "\\*");
425     hFind = FindFirstFileA (path, &wfd);
426     if (hFind == INVALID_HANDLE_VALUE) return;
427
428     do {
429         char *lp = wfd.cFileName;
430
431         if (!lp[0]) lp = wfd.cAlternateFileName; /* ? FIXME not (!lp) ? */
432         if (is_dot_dir (lp)) continue;
433         strcpy (path + dirlen, lp);
434         if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
435             remove_dir(path);
436         else if (!DeleteFileA(path))
437             report (R_WARNING, "Can't delete file %s: error %d",
438                     path, GetLastError ());
439     } while (FindNextFileA(hFind, &wfd));
440     FindClose (hFind);
441     if (!RemoveDirectoryA(dir))
442         report (R_WARNING, "Can't remove directory %s: error %d",
443                 dir, GetLastError ());
444 }
445
446 static const char* get_test_source_file(const char* test, const char* subtest)
447 {
448     static const char* special_dirs[][2] = {
449         { 0, 0 }
450     };
451     static char buffer[MAX_PATH];
452     int i, len = strlen(test);
453
454     if (len > 4 && !strcmp( test + len - 4, ".exe" ))
455     {
456         len = sprintf(buffer, "programs/%s", test) - 4;
457         buffer[len] = 0;
458     }
459     else len = sprintf(buffer, "dlls/%s", test);
460
461     for (i = 0; special_dirs[i][0]; i++) {
462         if (strcmp(test, special_dirs[i][0]) == 0) {
463             strcpy( buffer, special_dirs[i][1] );
464             len = strlen(buffer);
465             break;
466         }
467     }
468
469     sprintf(buffer + len, "/tests/%s.c", subtest);
470     return buffer;
471 }
472
473 static void* extract_rcdata (LPCSTR name, LPCSTR type, DWORD* size)
474 {
475     HRSRC rsrc;
476     HGLOBAL hdl;
477     LPVOID addr;
478     
479     if (!(rsrc = FindResourceA(NULL, name, type)) ||
480         !(*size = SizeofResource (0, rsrc)) ||
481         !(hdl = LoadResource (0, rsrc)) ||
482         !(addr = LockResource (hdl)))
483         return NULL;
484     return addr;
485 }
486
487 /* Fills in the name and exename fields */
488 static void
489 extract_test (struct wine_test *test, const char *dir, LPSTR res_name)
490 {
491     BYTE* code;
492     DWORD size;
493     char *exepos;
494     HANDLE hfile;
495     DWORD written;
496
497     code = extract_rcdata (res_name, "TESTRES", &size);
498     if (!code) report (R_FATAL, "Can't find test resource %s: %d",
499                        res_name, GetLastError ());
500     test->name = heap_strdup( res_name );
501     test->exename = strmake (NULL, "%s\\%s", dir, test->name);
502     exepos = strstr (test->name, testexe);
503     if (!exepos) report (R_FATAL, "Not an .exe file: %s", test->name);
504     *exepos = 0;
505     test->name = heap_realloc (test->name, exepos - test->name + 1);
506     report (R_STEP, "Extracting: %s", test->name);
507
508     hfile = CreateFileA(test->exename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
509                         CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
510     if (hfile == INVALID_HANDLE_VALUE)
511         report (R_FATAL, "Failed to open file %s.", test->exename);
512
513     if (!WriteFile(hfile, code, size, &written, NULL))
514         report (R_FATAL, "Failed to write file %s.", test->exename);
515
516     CloseHandle(hfile);
517 }
518
519 static DWORD wait_process( HANDLE process, DWORD timeout )
520 {
521     DWORD wait, diff = 0, start = GetTickCount();
522     MSG msg;
523
524     while (diff < timeout)
525     {
526         wait = MsgWaitForMultipleObjects( 1, &process, FALSE, timeout - diff, QS_ALLINPUT );
527         if (wait != WAIT_OBJECT_0 + 1) return wait;
528         while (PeekMessageA( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessageA( &msg );
529         diff = GetTickCount() - start;
530     }
531     return WAIT_TIMEOUT;
532 }
533
534 static void append_path( const char *path)
535 {
536     char *newpath;
537
538     newpath = heap_alloc(strlen(curpath) + 1 + strlen(path) + 1);
539     strcpy(newpath, curpath);
540     strcat(newpath, ";");
541     strcat(newpath, path);
542     SetEnvironmentVariableA("PATH", newpath);
543
544     heap_free(newpath);
545 }
546
547 /* Run a command for MS milliseconds.  If OUT != NULL, also redirect
548    stdout to there.
549
550    Return the exit status, -2 if can't create process or the return
551    value of WaitForSingleObject.
552  */
553 static int
554 run_ex (char *cmd, HANDLE out_file, const char *tempdir, DWORD ms)
555 {
556     STARTUPINFOA si;
557     PROCESS_INFORMATION pi;
558     DWORD wait, status;
559
560     GetStartupInfoA (&si);
561     si.dwFlags    = STARTF_USESTDHANDLES;
562     si.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
563     si.hStdOutput = out_file ? out_file : GetStdHandle( STD_OUTPUT_HANDLE );
564     si.hStdError  = out_file ? out_file : GetStdHandle( STD_ERROR_HANDLE );
565
566     if (!CreateProcessA (NULL, cmd, NULL, NULL, TRUE, CREATE_DEFAULT_ERROR_MODE,
567                          NULL, tempdir, &si, &pi))
568         return -2;
569
570     CloseHandle (pi.hThread);
571     status = wait_process( pi.hProcess, ms );
572     switch (status)
573     {
574     case WAIT_OBJECT_0:
575         GetExitCodeProcess (pi.hProcess, &status);
576         CloseHandle (pi.hProcess);
577         return status;
578     case WAIT_FAILED:
579         report (R_ERROR, "Wait for '%s' failed: %d", cmd, GetLastError ());
580         break;
581     case WAIT_TIMEOUT:
582         break;
583     default:
584         report (R_ERROR, "Wait returned %d", status);
585         break;
586     }
587     if (!TerminateProcess (pi.hProcess, 257))
588         report (R_ERROR, "TerminateProcess failed: %d", GetLastError ());
589     wait = wait_process( pi.hProcess, 5000 );
590     switch (wait)
591     {
592     case WAIT_OBJECT_0:
593         break;
594     case WAIT_FAILED:
595         report (R_ERROR, "Wait for termination of '%s' failed: %d", cmd, GetLastError ());
596         break;
597     case WAIT_TIMEOUT:
598         report (R_ERROR, "Can't kill process '%s'", cmd);
599         break;
600     default:
601         report (R_ERROR, "Waiting for termination: %d", wait);
602         break;
603     }
604     CloseHandle (pi.hProcess);
605     return status;
606 }
607
608 static DWORD
609 get_subtests (const char *tempdir, struct wine_test *test, LPSTR res_name)
610 {
611     char *cmd;
612     HANDLE subfile;
613     DWORD err, total;
614     char buffer[8192], *index;
615     static const char header[] = "Valid test names:";
616     int status, allocated;
617     char tmpdir[MAX_PATH], subname[MAX_PATH];
618     SECURITY_ATTRIBUTES sa;
619
620     test->subtest_count = 0;
621
622     if (!GetTempPathA( MAX_PATH, tmpdir ) ||
623         !GetTempFileNameA( tmpdir, "sub", 0, subname ))
624         report (R_FATAL, "Can't name subtests file.");
625
626     /* make handle inheritable */
627     sa.nLength = sizeof(sa);
628     sa.lpSecurityDescriptor = NULL;
629     sa.bInheritHandle = TRUE;
630
631     subfile = CreateFileA( subname, GENERIC_READ|GENERIC_WRITE,
632                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
633                            &sa, CREATE_ALWAYS, 0, NULL );
634
635     if ((subfile == INVALID_HANDLE_VALUE) &&
636         (GetLastError() == ERROR_INVALID_PARAMETER)) {
637         /* FILE_SHARE_DELETE not supported on win9x */
638         subfile = CreateFileA( subname, GENERIC_READ|GENERIC_WRITE,
639                            FILE_SHARE_READ | FILE_SHARE_WRITE,
640                            &sa, CREATE_ALWAYS, 0, NULL );
641     }
642     if (subfile == INVALID_HANDLE_VALUE) {
643         err = GetLastError();
644         report (R_ERROR, "Can't open subtests output of %s: %u",
645                 test->name, GetLastError());
646         goto quit;
647     }
648
649     cmd = strmake (NULL, "%s --list", test->exename);
650     if (test->maindllpath) {
651         /* We need to add the path (to the main dll) to PATH */
652         append_path(test->maindllpath);
653     }
654     status = run_ex (cmd, subfile, tempdir, 5000);
655     err = GetLastError();
656     if (test->maindllpath) {
657         /* Restore PATH again */
658         SetEnvironmentVariableA("PATH", curpath);
659     }
660     heap_free (cmd);
661
662     if (status == -2)
663     {
664         report (R_ERROR, "Cannot run %s error %u", test->exename, err);
665         CloseHandle( subfile );
666         goto quit;
667     }
668
669     SetFilePointer( subfile, 0, NULL, FILE_BEGIN );
670     ReadFile( subfile, buffer, sizeof(buffer), &total, NULL );
671     CloseHandle( subfile );
672     if (sizeof buffer == total) {
673         report (R_ERROR, "Subtest list of %s too big.",
674                 test->name, sizeof buffer);
675         err = ERROR_OUTOFMEMORY;
676         goto quit;
677     }
678     buffer[total] = 0;
679
680     index = strstr (buffer, header);
681     if (!index) {
682         report (R_ERROR, "Can't parse subtests output of %s",
683                 test->name);
684         err = ERROR_INTERNAL_ERROR;
685         goto quit;
686     }
687     index += sizeof header;
688
689     allocated = 10;
690     test->subtests = heap_alloc (allocated * sizeof(char*));
691     index = strtok (index, whitespace);
692     while (index) {
693         if (test->subtest_count == allocated) {
694             allocated *= 2;
695             test->subtests = heap_realloc (test->subtests,
696                                            allocated * sizeof(char*));
697         }
698         test->subtests[test->subtest_count++] = heap_strdup(index);
699         index = strtok (NULL, whitespace);
700     }
701     test->subtests = heap_realloc (test->subtests,
702                                    test->subtest_count * sizeof(char*));
703     err = 0;
704
705  quit:
706     if (!DeleteFileA (subname))
707         report (R_WARNING, "Can't delete file '%s': %u", subname, GetLastError());
708     return err;
709 }
710
711 static void
712 run_test (struct wine_test* test, const char* subtest, HANDLE out_file, const char *tempdir)
713 {
714     const char* file = get_test_source_file(test->name, subtest);
715
716     if (test_filtered_out( test->name, subtest ))
717     {
718         report (R_STEP, "Skipping: %s:%s", test->name, subtest);
719         xprintf ("%s:%s skipped %s -\n", test->name, subtest, file);
720         nr_of_skips++;
721     }
722     else
723     {
724         int status;
725         DWORD start = GetTickCount();
726         char *cmd = strmake (NULL, "%s %s", test->exename, subtest);
727         report (R_STEP, "Running: %s:%s", test->name, subtest);
728         xprintf ("%s:%s start %s -\n", test->name, subtest, file);
729         status = run_ex (cmd, out_file, tempdir, 120000);
730         heap_free (cmd);
731         xprintf ("%s:%s done (%d) in %ds\n", test->name, subtest, status, (GetTickCount()-start)/1000);
732         if (status) failures++;
733     }
734     if (failures) report (R_STATUS, "Running tests - %u failures", failures);
735 }
736
737 static BOOL CALLBACK
738 EnumTestFileProc (HMODULE hModule, LPCSTR lpszType,
739                   LPSTR lpszName, LONG_PTR lParam)
740 {
741     if (!test_filtered_out( lpszName, NULL )) (*(int*)lParam)++;
742     return TRUE;
743 }
744
745 static const struct clsid_mapping
746 {
747     const char *name;
748     CLSID clsid;
749 } clsid_list[] =
750 {
751     {"oledb32", {0xc8b522d1, 0x5cf3, 0x11ce, {0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}},
752     {NULL, {0, 0, 0, {0,0,0,0,0,0,0,0}}}
753 };
754
755
756 static BOOL get_main_clsid(const char *name, CLSID *clsid)
757 {
758     const struct clsid_mapping *mapping;
759
760     for(mapping = clsid_list; mapping->name; mapping++)
761     {
762         if(!strcasecmp(name, mapping->name))
763         {
764             *clsid = mapping->clsid;
765             return TRUE;
766         }
767     }
768     return FALSE;
769 }
770
771 static HMODULE load_com_dll(const char *name, char **path, char *filename)
772 {
773     HMODULE dll = NULL;
774     HKEY hkey;
775     char keyname[100];
776     char dllname[MAX_PATH];
777     char *p;
778     CLSID clsid;
779
780     if(!get_main_clsid(name, &clsid)) return NULL;
781
782     sprintf(keyname, "CLSID\\{%08x-%04x-%04x-%02x%2x-%02x%2x%02x%2x%02x%2x}\\InprocServer32",
783             clsid.Data1, clsid.Data2, clsid.Data3, clsid.Data4[0], clsid.Data4[1],
784             clsid.Data4[2], clsid.Data4[3], clsid.Data4[4], clsid.Data4[5],
785             clsid.Data4[6], clsid.Data4[7]);
786
787     if(RegOpenKeyA(HKEY_CLASSES_ROOT, keyname, &hkey) == ERROR_SUCCESS)
788     {
789         LONG size = sizeof(dllname);
790         if(RegQueryValueA(hkey, NULL, dllname, &size) == ERROR_SUCCESS)
791         {
792             if ((dll = LoadLibraryExA(dllname, NULL, LOAD_LIBRARY_AS_DATAFILE)))
793             {
794                 strcpy( filename, dllname );
795                 p = strrchr(dllname, '\\');
796                 if (p) *p = 0;
797                 *path = heap_strdup( dllname );
798             }
799         }
800         RegCloseKey(hkey);
801     }
802
803     return dll;
804 }
805
806 static void get_dll_path(HMODULE dll, char **path, char *filename)
807 {
808     char dllpath[MAX_PATH];
809
810     GetModuleFileNameA(dll, dllpath, MAX_PATH);
811     strcpy(filename, dllpath);
812     *strrchr(dllpath, '\\') = '\0';
813     *path = heap_strdup( dllpath );
814 }
815
816 static BOOL CALLBACK
817 extract_test_proc (HMODULE hModule, LPCSTR lpszType, LPSTR lpszName, LONG_PTR lParam)
818 {
819     const char *tempdir = (const char *)lParam;
820     char dllname[MAX_PATH];
821     char filename[MAX_PATH];
822     WCHAR dllnameW[MAX_PATH];
823     HMODULE dll;
824     DWORD err;
825     HANDLE actctx;
826     ULONG_PTR cookie;
827
828     if (aborting) return TRUE;
829
830     /* Check if the main dll is present on this system */
831     CharLowerA(lpszName);
832     strcpy(dllname, lpszName);
833     *strstr(dllname, testexe) = 0;
834
835     if (test_filtered_out( lpszName, NULL ))
836     {
837         nr_of_skips++;
838         xprintf ("    %s=skipped\n", dllname);
839         return TRUE;
840     }
841     extract_test (&wine_tests[nr_of_files], tempdir, lpszName);
842
843     if (pCreateActCtxA != NULL && pActivateActCtx != NULL &&
844         pDeactivateActCtx != NULL && pReleaseActCtx != NULL)
845     {
846         ACTCTXA actctxinfo;
847         memset(&actctxinfo, 0, sizeof(ACTCTXA));
848         actctxinfo.cbSize = sizeof(ACTCTXA);
849         actctxinfo.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID;
850         actctxinfo.lpSource = wine_tests[nr_of_files].exename;
851         actctxinfo.lpResourceName = (LPSTR)CREATEPROCESS_MANIFEST_RESOURCE_ID;
852         actctx = pCreateActCtxA(&actctxinfo);
853         if (actctx != INVALID_HANDLE_VALUE &&
854             ! pActivateActCtx(actctx, &cookie))
855         {
856             pReleaseActCtx(actctx);
857             actctx = INVALID_HANDLE_VALUE;
858         }
859     } else actctx = INVALID_HANDLE_VALUE;
860
861     wine_tests[nr_of_files].maindllpath = NULL;
862     strcpy(filename, dllname);
863     dll = LoadLibraryExA(dllname, NULL, LOAD_LIBRARY_AS_DATAFILE);
864
865     if (!dll) dll = load_com_dll(dllname, &wine_tests[nr_of_files].maindllpath, filename);
866
867     if (!dll && pLoadLibraryShim)
868     {
869         MultiByteToWideChar(CP_ACP, 0, dllname, -1, dllnameW, MAX_PATH);
870         if (SUCCEEDED( pLoadLibraryShim(dllnameW, NULL, NULL, &dll) ) && dll)
871         {
872             get_dll_path(dll, &wine_tests[nr_of_files].maindllpath, filename);
873             FreeLibrary(dll);
874             dll = LoadLibraryExA(filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
875         }
876         else dll = 0;
877     }
878
879     if (!dll)
880     {
881         xprintf ("    %s=dll is missing\n", dllname);
882         if (actctx != INVALID_HANDLE_VALUE)
883         {
884             pDeactivateActCtx(0, cookie);
885             pReleaseActCtx(actctx);
886         }
887         return TRUE;
888     }
889     if (is_native_dll(dll))
890     {
891         FreeLibrary(dll);
892         xprintf ("    %s=load error Configured as native\n", dllname);
893         nr_native_dlls++;
894         if (actctx != INVALID_HANDLE_VALUE)
895         {
896             pDeactivateActCtx(0, cookie);
897             pReleaseActCtx(actctx);
898         }
899         return TRUE;
900     }
901     FreeLibrary(dll);
902
903     if (!(err = get_subtests( tempdir, &wine_tests[nr_of_files], lpszName )))
904     {
905         xprintf ("    %s=%s\n", dllname, get_file_version(filename));
906         nr_of_tests += wine_tests[nr_of_files].subtest_count;
907         nr_of_files++;
908     }
909     else
910     {
911         xprintf ("    %s=load error %u\n", dllname, err);
912     }
913
914     if (actctx != INVALID_HANDLE_VALUE)
915     {
916         pDeactivateActCtx(0, cookie);
917         pReleaseActCtx(actctx);
918     }
919     return TRUE;
920 }
921
922 static char *
923 run_tests (char *logname, char *outdir)
924 {
925     int i;
926     char *strres, *eol, *nextline;
927     DWORD strsize;
928     SECURITY_ATTRIBUTES sa;
929     char tmppath[MAX_PATH], tempdir[MAX_PATH+4];
930     DWORD needed;
931     HMODULE kernel32;
932
933     /* Get the current PATH only once */
934     needed = GetEnvironmentVariableA("PATH", NULL, 0);
935     curpath = heap_alloc(needed);
936     GetEnvironmentVariableA("PATH", curpath, needed);
937
938     SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
939
940     if (!GetTempPathA( MAX_PATH, tmppath ))
941         report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
942
943     if (!logname) {
944         static char tmpname[MAX_PATH];
945         if (!GetTempFileNameA( tmppath, "res", 0, tmpname ))
946             report (R_FATAL, "Can't name logfile.");
947         logname = tmpname;
948     }
949     report (R_OUT, logname);
950
951     /* make handle inheritable */
952     sa.nLength = sizeof(sa);
953     sa.lpSecurityDescriptor = NULL;
954     sa.bInheritHandle = TRUE;
955
956     logfile = CreateFileA( logname, GENERIC_READ|GENERIC_WRITE,
957                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
958                            &sa, CREATE_ALWAYS, 0, NULL );
959
960     if ((logfile == INVALID_HANDLE_VALUE) &&
961         (GetLastError() == ERROR_INVALID_PARAMETER)) {
962         /* FILE_SHARE_DELETE not supported on win9x */
963         logfile = CreateFileA( logname, GENERIC_READ|GENERIC_WRITE,
964                            FILE_SHARE_READ | FILE_SHARE_WRITE,
965                            &sa, CREATE_ALWAYS, 0, NULL );
966     }
967     if (logfile == INVALID_HANDLE_VALUE)
968         report (R_FATAL, "Could not open logfile: %u", GetLastError());
969
970     /* try stable path for ZoneAlarm */
971     if (!outdir) {
972         strcpy( tempdir, tmppath );
973         strcat( tempdir, "wct" );
974
975         if (!CreateDirectoryA( tempdir, NULL ))
976         {
977             if (!GetTempFileNameA( tmppath, "wct", 0, tempdir ))
978                 report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
979             DeleteFileA( tempdir );
980             if (!CreateDirectoryA( tempdir, NULL ))
981                 report (R_FATAL, "Could not create directory: %s", tempdir);
982         }
983     }
984     else
985         strcpy( tempdir, outdir);
986
987     report (R_DIR, tempdir);
988
989     xprintf ("Version 4\n");
990     xprintf ("Tests from build %s\n", build_id[0] ? build_id : "-" );
991     xprintf ("Archive: -\n");  /* no longer used */
992     xprintf ("Tag: %s\n", tag);
993     xprintf ("Build info:\n");
994     strres = extract_rcdata ("BUILD_INFO", "STRINGRES", &strsize);
995     while (strres) {
996         eol = memchr (strres, '\n', strsize);
997         if (!eol) {
998             nextline = NULL;
999             eol = strres + strsize;
1000         } else {
1001             strsize -= eol - strres + 1;
1002             nextline = strsize?eol+1:NULL;
1003             if (eol > strres && *(eol-1) == '\r') eol--;
1004         }
1005         xprintf ("    %.*s\n", eol-strres, strres);
1006         strres = nextline;
1007     }
1008     xprintf ("Operating system version:\n");
1009     print_version ();
1010     print_language ();
1011     xprintf ("Dll info:\n" );
1012
1013     report (R_STATUS, "Counting tests");
1014     if (!EnumResourceNamesA (NULL, "TESTRES", EnumTestFileProc, (LPARAM)&nr_of_files))
1015         report (R_FATAL, "Can't enumerate test files: %d",
1016                 GetLastError ());
1017     wine_tests = heap_alloc (nr_of_files * sizeof wine_tests[0]);
1018
1019     /* Do this only once during extraction (and version checking) */
1020     hmscoree = LoadLibraryA("mscoree.dll");
1021     pLoadLibraryShim = NULL;
1022     if (hmscoree)
1023         pLoadLibraryShim = (void *)GetProcAddress(hmscoree, "LoadLibraryShim");
1024     kernel32 = GetModuleHandleA("kernel32.dll");
1025     pCreateActCtxA = (void *)GetProcAddress(kernel32, "CreateActCtxA");
1026     pActivateActCtx = (void *)GetProcAddress(kernel32, "ActivateActCtx");
1027     pDeactivateActCtx = (void *)GetProcAddress(kernel32, "DeactivateActCtx");
1028     pReleaseActCtx = (void *)GetProcAddress(kernel32, "ReleaseActCtx");
1029
1030     report (R_STATUS, "Extracting tests");
1031     report (R_PROGRESS, 0, nr_of_files);
1032     nr_of_files = 0;
1033     nr_of_tests = 0;
1034     nr_of_skips = 0;
1035     if (!EnumResourceNamesA (NULL, "TESTRES", extract_test_proc, (LPARAM)tempdir))
1036         report (R_FATAL, "Can't enumerate test files: %d",
1037                 GetLastError ());
1038
1039     FreeLibrary(hmscoree);
1040
1041     if (aborting) return logname;
1042
1043     xprintf ("Test output:\n" );
1044
1045     report (R_DELTA, 0, "Extracting: Done");
1046
1047     if (nr_native_dlls)
1048         report( R_WARNING, "Some dlls are configured as native, you won't be able to submit results." );
1049
1050     report (R_STATUS, "Running tests");
1051     report (R_PROGRESS, 1, nr_of_tests);
1052     for (i = 0; i < nr_of_files; i++) {
1053         struct wine_test *test = wine_tests + i;
1054         int j;
1055
1056         if (aborting) break;
1057
1058         if (test->maindllpath) {
1059             /* We need to add the path (to the main dll) to PATH */
1060             append_path(test->maindllpath);
1061         }
1062
1063         for (j = 0; j < test->subtest_count; j++) {
1064             if (aborting) break;
1065             run_test (test, test->subtests[j], logfile, tempdir);
1066         }
1067
1068         if (test->maindllpath) {
1069             /* Restore PATH again */
1070             SetEnvironmentVariableA("PATH", curpath);
1071         }
1072     }
1073     report (R_DELTA, 0, "Running: Done");
1074
1075     report (R_STATUS, "Cleaning up");
1076     CloseHandle( logfile );
1077     logfile = 0;
1078     if (!outdir)
1079         remove_dir (tempdir);
1080     heap_free(wine_tests);
1081     heap_free(curpath);
1082
1083     return logname;
1084 }
1085
1086 static BOOL WINAPI ctrl_handler(DWORD ctrl_type)
1087 {
1088     if (ctrl_type == CTRL_C_EVENT) {
1089         printf("Ignoring Ctrl-C, use Ctrl-Break if you really want to terminate\n");
1090         return TRUE;
1091     }
1092
1093     return FALSE;
1094 }
1095
1096
1097 static BOOL CALLBACK
1098 extract_only_proc (HMODULE hModule, LPCSTR lpszType, LPSTR lpszName, LONG_PTR lParam)
1099 {
1100     const char *target_dir = (const char *)lParam;
1101     char filename[MAX_PATH];
1102
1103     if (test_filtered_out( lpszName, NULL )) return TRUE;
1104
1105     strcpy(filename, lpszName);
1106     CharLowerA(filename);
1107
1108     extract_test( &wine_tests[nr_of_files], target_dir, filename );
1109     nr_of_files++;
1110     return TRUE;
1111 }
1112
1113 static void extract_only (const char *target_dir)
1114 {
1115     BOOL res;
1116
1117     report (R_DIR, target_dir);
1118     res = CreateDirectoryA( target_dir, NULL );
1119     if (!res && GetLastError() != ERROR_ALREADY_EXISTS)
1120         report (R_FATAL, "Could not create directory: %s (%d)", target_dir, GetLastError ());
1121
1122     nr_of_files = 0;
1123     report (R_STATUS, "Counting tests");
1124     if (!EnumResourceNamesA(NULL, "TESTRES", EnumTestFileProc, (LPARAM)&nr_of_files))
1125         report (R_FATAL, "Can't enumerate test files: %d", GetLastError ());
1126
1127     wine_tests = heap_alloc (nr_of_files * sizeof wine_tests[0] );
1128
1129     report (R_STATUS, "Extracting tests");
1130     report (R_PROGRESS, 0, nr_of_files);
1131     nr_of_files = 0;
1132     if (!EnumResourceNamesA(NULL, "TESTRES", extract_only_proc, (LPARAM)target_dir))
1133         report (R_FATAL, "Can't enumerate test files: %d", GetLastError ());
1134
1135     report (R_DELTA, 0, "Extracting: Done");
1136 }
1137
1138 static void
1139 usage (void)
1140 {
1141     fprintf (stderr,
1142 "Usage: winetest [OPTION]... [TESTS]\n\n"
1143 " --help    print this message and exit\n"
1144 " --version print the build version and exit\n"
1145 " -c        console mode, no GUI\n"
1146 " -d DIR    Use DIR as temp directory (default: %%TEMP%%\\wct)\n"
1147 " -e        preserve the environment\n"
1148 " -h        print this message and exit\n"
1149 " -i INFO   an optional description of the test platform\n"
1150 " -m MAIL   an email address to enable developers to contact you\n"
1151 " -n        exclude the specified tests\n"
1152 " -p        shutdown when the tests are done\n"
1153 " -q        quiet mode, no output at all\n"
1154 " -o FILE   put report into FILE, do not submit\n"
1155 " -s FILE   submit FILE, do not run tests\n"
1156 " -t TAG    include TAG of characters [-.0-9a-zA-Z] in the report\n"
1157 " -u URL    include TestBot URL in the report\n"
1158 " -x DIR    Extract tests to DIR (default: .\\wct) and exit\n");
1159 }
1160
1161 int main( int argc, char *argv[] )
1162 {
1163     BOOL (WINAPI *pIsWow64Process)(HANDLE hProcess, PBOOL Wow64Process);
1164     char *logname = NULL, *outdir = NULL;
1165     const char *extract = NULL;
1166     const char *cp, *submit = NULL;
1167     int reset_env = 1;
1168     int poweroff = 0;
1169     int interactive = 1;
1170     int i;
1171
1172     if (!LoadStringA( 0, IDS_BUILD_ID, build_id, sizeof(build_id) )) build_id[0] = 0;
1173
1174     pIsWow64Process = (void *)GetProcAddress(GetModuleHandleA("kernel32.dll"),"IsWow64Process");
1175     if (!pIsWow64Process || !pIsWow64Process( GetCurrentProcess(), &is_wow64 )) is_wow64 = FALSE;
1176
1177     for (i = 1; i < argc && argv[i]; i++)
1178     {
1179         if (!strcmp(argv[i], "--help")) {
1180             usage ();
1181             exit (0);
1182         }
1183         else if (!strcmp(argv[i], "--version")) {
1184             printf("%-12.12s\n", build_id[0] ? build_id : "unknown");
1185             exit (0);
1186         }
1187         else if ((argv[i][0] != '-' && argv[i][0] != '/') || argv[i][2]) {
1188             if (nb_filters == sizeof(filters)/sizeof(filters[0]))
1189             {
1190                 report (R_ERROR, "Too many test filters specified");
1191                 exit (2);
1192             }
1193             filters[nb_filters++] = argv[i];
1194         }
1195         else switch (argv[i][1]) {
1196         case 'c':
1197             report (R_TEXTMODE);
1198             interactive = 0;
1199             break;
1200         case 'e':
1201             reset_env = 0;
1202             break;
1203         case 'h':
1204         case '?':
1205             usage ();
1206             exit (0);
1207         case 'i':
1208             if (!(description = argv[++i]))
1209             {
1210                 usage();
1211                 exit( 2 );
1212             }
1213             break;
1214         case 'm':
1215             if (!(email = argv[++i]))
1216             {
1217                 usage();
1218                 exit( 2 );
1219             }
1220             break;
1221         case 'n':
1222             exclude_tests = TRUE;
1223             break;
1224         case 'p':
1225             poweroff = 1;
1226             break;
1227         case 'q':
1228             report (R_QUIET);
1229             interactive = 0;
1230             break;
1231         case 's':
1232             if (!(submit = argv[++i]))
1233             {
1234                 usage();
1235                 exit( 2 );
1236             }
1237             if (tag)
1238                 report (R_WARNING, "ignoring tag for submission");
1239             send_file (submit);
1240             break;
1241         case 'o':
1242             if (!(logname = argv[++i]))
1243             {
1244                 usage();
1245                 exit( 2 );
1246             }
1247             break;
1248         case 't':
1249             if (!(tag = argv[++i]))
1250             {
1251                 usage();
1252                 exit( 2 );
1253             }
1254             if (strlen (tag) > MAXTAGLEN)
1255                 report (R_FATAL, "tag is too long (maximum %d characters)",
1256                         MAXTAGLEN);
1257             cp = findbadtagchar (tag);
1258             if (cp) {
1259                 report (R_ERROR, "invalid char in tag: %c", *cp);
1260                 usage ();
1261                 exit (2);
1262             }
1263             break;
1264         case 'u':
1265             if (!(url = argv[++i]))
1266             {
1267                 usage();
1268                 exit( 2 );
1269             }
1270             break;
1271         case 'x':
1272             report (R_TEXTMODE);
1273             if (!(extract = argv[++i]))
1274                 extract = ".\\wct";
1275
1276             extract_only (extract);
1277             break;
1278         case 'd':
1279             outdir = argv[++i];
1280             break;
1281         default:
1282             report (R_ERROR, "invalid option: -%c", argv[i][1]);
1283             usage ();
1284             exit (2);
1285         }
1286     }
1287     if (!submit && !extract) {
1288         int is_win9x = (GetVersion() & 0x80000000) != 0;
1289
1290         report (R_STATUS, "Starting up");
1291
1292         if (is_win9x)
1293             report (R_WARNING, "Running on win9x is not supported. You won't be able to submit results.");
1294
1295         if (!running_on_visible_desktop ())
1296             report (R_FATAL, "Tests must be run on a visible desktop");
1297
1298         if (running_under_wine())
1299         {
1300             if (!check_mount_mgr())
1301                 report (R_FATAL, "Mount manager not running, most likely your WINEPREFIX wasn't created correctly.");
1302
1303             if (!check_wow64_registry())
1304                 report (R_FATAL, "WoW64 keys missing, most likely your WINEPREFIX wasn't created correctly.");
1305
1306             if (!check_display_driver())
1307                 report (R_FATAL, "Unable to create a window, the display driver is not working.");
1308         }
1309
1310         SetConsoleCtrlHandler(ctrl_handler, TRUE);
1311
1312         if (reset_env)
1313         {
1314             SetEnvironmentVariableA( "WINETEST_PLATFORM", running_under_wine () ? "wine" : "windows" );
1315             SetEnvironmentVariableA( "WINETEST_DEBUG", "1" );
1316             SetEnvironmentVariableA( "WINETEST_INTERACTIVE", "0" );
1317             SetEnvironmentVariableA( "WINETEST_REPORT_SUCCESS", "0" );
1318         }
1319
1320         while (!tag) {
1321             if (!interactive)
1322                 report (R_FATAL, "Please specify a tag (-t option) if "
1323                         "running noninteractive!");
1324             if (guiAskTag () == IDABORT) exit (1);
1325         }
1326         report (R_TAG);
1327
1328         while (!email) {
1329             if (!interactive)
1330                 report (R_FATAL, "Please specify an email address (-m option) to enable developers\n"
1331                         "    to contact you about your report if necessary.");
1332             if (guiAskEmail () == IDABORT) exit (1);
1333         }
1334
1335         if (!build_id[0])
1336             report( R_WARNING, "You won't be able to submit results without a valid build id.\n"
1337                     "To submit results, winetest needs to be built from a git checkout." );
1338
1339         if (!logname) {
1340             logname = run_tests (NULL, outdir);
1341             if (aborting) {
1342                 DeleteFileA(logname);
1343                 exit (0);
1344             }
1345             if (failures > FAILURES_LIMIT)
1346                 report( R_WARNING,
1347                         "%d tests failed, there's probably something broken with your setup.\n"
1348                         "You need to address this before submitting results.", failures );
1349
1350             if (build_id[0] && nr_of_skips <= SKIP_LIMIT && failures <= FAILURES_LIMIT &&
1351                 !nr_native_dlls && !is_win9x &&
1352                 report (R_ASK, MB_YESNO, "Do you want to submit the test results?") == IDYES)
1353                 if (!send_file (logname) && !DeleteFileA(logname))
1354                     report (R_WARNING, "Can't remove logfile: %u", GetLastError());
1355         } else run_tests (logname, outdir);
1356         report (R_STATUS, "Finished");
1357     }
1358     if (poweroff)
1359     {
1360         HANDLE hToken;
1361         TOKEN_PRIVILEGES npr;
1362
1363         /* enable the shutdown privilege for the current process */
1364         if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
1365         {
1366             LookupPrivilegeValueA(0, "SeShutdownPrivilege", &npr.Privileges[0].Luid);
1367             npr.PrivilegeCount = 1;
1368             npr.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1369             AdjustTokenPrivileges(hToken, FALSE, &npr, 0, 0, 0);
1370             CloseHandle(hToken);
1371         }
1372         ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF | EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER);
1373     }
1374     exit (0);
1375 }