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