wscript: Fix tests on wow64.
[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 = GetModuleHandle("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     OSVERSIONINFOEX 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(OSVERSIONINFOEX);
334     if (!(ext = GetVersionEx ((OSVERSIONINFO *) &ver)))
335     {
336         ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
337         if (!GetVersionEx ((OSVERSIONINFO *) &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     xprintf ("    SystemDefaultLCID=%x\n", GetSystemDefaultLCID());
395     xprintf ("    UserDefaultLCID=%x\n", GetUserDefaultLCID());
396     xprintf ("    ThreadLocale=%x\n", GetThreadLocale());
397 }
398
399 static inline int is_dot_dir(const char* x)
400 {
401     return ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))));
402 }
403
404 static void remove_dir (const char *dir)
405 {
406     HANDLE  hFind;
407     WIN32_FIND_DATA wfd;
408     char path[MAX_PATH];
409     size_t dirlen = strlen (dir);
410
411     /* Make sure the directory exists before going further */
412     memcpy (path, dir, dirlen);
413     strcpy (path + dirlen++, "\\*");
414     hFind = FindFirstFile (path, &wfd);
415     if (hFind == INVALID_HANDLE_VALUE) return;
416
417     do {
418         char *lp = wfd.cFileName;
419
420         if (!lp[0]) lp = wfd.cAlternateFileName; /* ? FIXME not (!lp) ? */
421         if (is_dot_dir (lp)) continue;
422         strcpy (path + dirlen, lp);
423         if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
424             remove_dir(path);
425         else if (!DeleteFile (path))
426             report (R_WARNING, "Can't delete file %s: error %d",
427                     path, GetLastError ());
428     } while (FindNextFile (hFind, &wfd));
429     FindClose (hFind);
430     if (!RemoveDirectory (dir))
431         report (R_WARNING, "Can't remove directory %s: error %d",
432                 dir, GetLastError ());
433 }
434
435 static const char* get_test_source_file(const char* test, const char* subtest)
436 {
437     static const char* special_dirs[][2] = {
438         { 0, 0 }
439     };
440     static char buffer[MAX_PATH];
441     int i, len = strlen(test);
442
443     if (len > 4 && !strcmp( test + len - 4, ".exe" ))
444     {
445         len = sprintf(buffer, "programs/%s", test) - 4;
446         buffer[len] = 0;
447     }
448     else len = sprintf(buffer, "dlls/%s", test);
449
450     for (i = 0; special_dirs[i][0]; i++) {
451         if (strcmp(test, special_dirs[i][0]) == 0) {
452             strcpy( buffer, special_dirs[i][1] );
453             len = strlen(buffer);
454             break;
455         }
456     }
457
458     sprintf(buffer + len, "/tests/%s.c", subtest);
459     return buffer;
460 }
461
462 static void* extract_rcdata (LPCTSTR name, LPCTSTR type, DWORD* size)
463 {
464     HRSRC rsrc;
465     HGLOBAL hdl;
466     LPVOID addr;
467     
468     if (!(rsrc = FindResource (NULL, name, type)) ||
469         !(*size = SizeofResource (0, rsrc)) ||
470         !(hdl = LoadResource (0, rsrc)) ||
471         !(addr = LockResource (hdl)))
472         return NULL;
473     return addr;
474 }
475
476 /* Fills in the name and exename fields */
477 static void
478 extract_test (struct wine_test *test, const char *dir, LPTSTR res_name)
479 {
480     BYTE* code;
481     DWORD size;
482     char *exepos;
483     HANDLE hfile;
484     DWORD written;
485
486     code = extract_rcdata (res_name, "TESTRES", &size);
487     if (!code) report (R_FATAL, "Can't find test resource %s: %d",
488                        res_name, GetLastError ());
489     test->name = heap_strdup( res_name );
490     test->exename = strmake (NULL, "%s\\%s", dir, test->name);
491     exepos = strstr (test->name, testexe);
492     if (!exepos) report (R_FATAL, "Not an .exe file: %s", test->name);
493     *exepos = 0;
494     test->name = heap_realloc (test->name, exepos - test->name + 1);
495     report (R_STEP, "Extracting: %s", test->name);
496
497     hfile = CreateFileA(test->exename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
498                         CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
499     if (hfile == INVALID_HANDLE_VALUE)
500         report (R_FATAL, "Failed to open file %s.", test->exename);
501
502     if (!WriteFile(hfile, code, size, &written, NULL))
503         report (R_FATAL, "Failed to write file %s.", test->exename);
504
505     CloseHandle(hfile);
506 }
507
508 static DWORD wait_process( HANDLE process, DWORD timeout )
509 {
510     DWORD wait, diff = 0, start = GetTickCount();
511     MSG msg;
512
513     while (diff < timeout)
514     {
515         wait = MsgWaitForMultipleObjects( 1, &process, FALSE, timeout - diff, QS_ALLINPUT );
516         if (wait != WAIT_OBJECT_0 + 1) return wait;
517         while (PeekMessageA( &msg, 0, 0, 0, PM_REMOVE )) DispatchMessage( &msg );
518         diff = GetTickCount() - start;
519     }
520     return WAIT_TIMEOUT;
521 }
522
523 static void append_path( const char *path)
524 {
525     char *newpath;
526
527     newpath = heap_alloc(strlen(curpath) + 1 + strlen(path) + 1);
528     strcpy(newpath, curpath);
529     strcat(newpath, ";");
530     strcat(newpath, path);
531     SetEnvironmentVariableA("PATH", newpath);
532
533     heap_free(newpath);
534 }
535
536 /* Run a command for MS milliseconds.  If OUT != NULL, also redirect
537    stdout to there.
538
539    Return the exit status, -2 if can't create process or the return
540    value of WaitForSingleObject.
541  */
542 static int
543 run_ex (char *cmd, HANDLE out_file, const char *tempdir, DWORD ms)
544 {
545     STARTUPINFO si;
546     PROCESS_INFORMATION pi;
547     DWORD wait, status;
548
549     GetStartupInfo (&si);
550     si.dwFlags    = STARTF_USESTDHANDLES;
551     si.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
552     si.hStdOutput = out_file ? out_file : GetStdHandle( STD_OUTPUT_HANDLE );
553     si.hStdError  = out_file ? out_file : GetStdHandle( STD_ERROR_HANDLE );
554
555     if (!CreateProcessA (NULL, cmd, NULL, NULL, TRUE, CREATE_DEFAULT_ERROR_MODE,
556                          NULL, tempdir, &si, &pi))
557         return -2;
558
559     CloseHandle (pi.hThread);
560     status = wait_process( pi.hProcess, ms );
561     switch (status)
562     {
563     case WAIT_OBJECT_0:
564         GetExitCodeProcess (pi.hProcess, &status);
565         CloseHandle (pi.hProcess);
566         return status;
567     case WAIT_FAILED:
568         report (R_ERROR, "Wait for '%s' failed: %d", cmd, GetLastError ());
569         break;
570     case WAIT_TIMEOUT:
571         break;
572     default:
573         report (R_ERROR, "Wait returned %d", status);
574         break;
575     }
576     if (!TerminateProcess (pi.hProcess, 257))
577         report (R_ERROR, "TerminateProcess failed: %d", GetLastError ());
578     wait = wait_process( pi.hProcess, 5000 );
579     switch (wait)
580     {
581     case WAIT_OBJECT_0:
582         break;
583     case WAIT_FAILED:
584         report (R_ERROR, "Wait for termination of '%s' failed: %d", cmd, GetLastError ());
585         break;
586     case WAIT_TIMEOUT:
587         report (R_ERROR, "Can't kill process '%s'", cmd);
588         break;
589     default:
590         report (R_ERROR, "Waiting for termination: %d", wait);
591         break;
592     }
593     CloseHandle (pi.hProcess);
594     return status;
595 }
596
597 static DWORD
598 get_subtests (const char *tempdir, struct wine_test *test, LPTSTR res_name)
599 {
600     char *cmd;
601     HANDLE subfile;
602     DWORD err, total;
603     char buffer[8192], *index;
604     static const char header[] = "Valid test names:";
605     int status, allocated;
606     char tmpdir[MAX_PATH], subname[MAX_PATH];
607     SECURITY_ATTRIBUTES sa;
608
609     test->subtest_count = 0;
610
611     if (!GetTempPathA( MAX_PATH, tmpdir ) ||
612         !GetTempFileNameA( tmpdir, "sub", 0, subname ))
613         report (R_FATAL, "Can't name subtests file.");
614
615     /* make handle inheritable */
616     sa.nLength = sizeof(sa);
617     sa.lpSecurityDescriptor = NULL;
618     sa.bInheritHandle = TRUE;
619
620     subfile = CreateFileA( subname, GENERIC_READ|GENERIC_WRITE,
621                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
622                            &sa, CREATE_ALWAYS, 0, NULL );
623
624     if ((subfile == INVALID_HANDLE_VALUE) &&
625         (GetLastError() == ERROR_INVALID_PARAMETER)) {
626         /* FILE_SHARE_DELETE not supported on win9x */
627         subfile = CreateFileA( subname, GENERIC_READ|GENERIC_WRITE,
628                            FILE_SHARE_READ | FILE_SHARE_WRITE,
629                            &sa, CREATE_ALWAYS, 0, NULL );
630     }
631     if (subfile == INVALID_HANDLE_VALUE) {
632         err = GetLastError();
633         report (R_ERROR, "Can't open subtests output of %s: %u",
634                 test->name, GetLastError());
635         goto quit;
636     }
637
638     cmd = strmake (NULL, "%s --list", test->exename);
639     if (test->maindllpath) {
640         /* We need to add the path (to the main dll) to PATH */
641         append_path(test->maindllpath);
642     }
643     status = run_ex (cmd, subfile, tempdir, 5000);
644     err = GetLastError();
645     if (test->maindllpath) {
646         /* Restore PATH again */
647         SetEnvironmentVariableA("PATH", curpath);
648     }
649     heap_free (cmd);
650
651     if (status == -2)
652     {
653         report (R_ERROR, "Cannot run %s error %u", test->exename, err);
654         goto quit;
655     }
656
657     SetFilePointer( subfile, 0, NULL, FILE_BEGIN );
658     ReadFile( subfile, buffer, sizeof(buffer), &total, NULL );
659     CloseHandle( subfile );
660     if (sizeof buffer == total) {
661         report (R_ERROR, "Subtest list of %s too big.",
662                 test->name, sizeof buffer);
663         err = ERROR_OUTOFMEMORY;
664         goto quit;
665     }
666     buffer[total] = 0;
667
668     index = strstr (buffer, header);
669     if (!index) {
670         report (R_ERROR, "Can't parse subtests output of %s",
671                 test->name);
672         err = ERROR_INTERNAL_ERROR;
673         goto quit;
674     }
675     index += sizeof header;
676
677     allocated = 10;
678     test->subtests = heap_alloc (allocated * sizeof(char*));
679     index = strtok (index, whitespace);
680     while (index) {
681         if (test->subtest_count == allocated) {
682             allocated *= 2;
683             test->subtests = heap_realloc (test->subtests,
684                                            allocated * sizeof(char*));
685         }
686         test->subtests[test->subtest_count++] = heap_strdup(index);
687         index = strtok (NULL, whitespace);
688     }
689     test->subtests = heap_realloc (test->subtests,
690                                    test->subtest_count * sizeof(char*));
691     err = 0;
692
693  quit:
694     if (!DeleteFileA (subname))
695         report (R_WARNING, "Can't delete file '%s': %u", subname, GetLastError());
696     return err;
697 }
698
699 static void
700 run_test (struct wine_test* test, const char* subtest, HANDLE out_file, const char *tempdir)
701 {
702     const char* file = get_test_source_file(test->name, subtest);
703
704     if (test_filtered_out( test->name, subtest ))
705     {
706         report (R_STEP, "Skipping: %s:%s", test->name, subtest);
707         xprintf ("%s:%s skipped %s -\n", test->name, subtest, file);
708         nr_of_skips++;
709     }
710     else
711     {
712         int status;
713         char *cmd = strmake (NULL, "%s %s", test->exename, subtest);
714         report (R_STEP, "Running: %s:%s", test->name, subtest);
715         xprintf ("%s:%s start %s -\n", test->name, subtest, file);
716         status = run_ex (cmd, out_file, tempdir, 120000);
717         heap_free (cmd);
718         xprintf ("%s:%s done (%d)\n", test->name, subtest, status);
719         if (status) failures++;
720     }
721 }
722
723 static BOOL CALLBACK
724 EnumTestFileProc (HMODULE hModule, LPCTSTR lpszType,
725                   LPTSTR lpszName, LONG_PTR lParam)
726 {
727     if (!test_filtered_out( lpszName, NULL )) (*(int*)lParam)++;
728     return TRUE;
729 }
730
731 static const struct clsid_mapping
732 {
733     const char *name;
734     CLSID clsid;
735 } clsid_list[] =
736 {
737     {"oledb32", {0xc8b522d1, 0x5cf3, 0x11ce, {0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}},
738     {NULL, {0, 0, 0, {0,0,0,0,0,0,0,0}}}
739 };
740
741
742 static BOOL get_main_clsid(const char *name, CLSID *clsid)
743 {
744     const struct clsid_mapping *mapping;
745
746     for(mapping = clsid_list; mapping->name; mapping++)
747     {
748         if(!strcasecmp(name, mapping->name))
749         {
750             *clsid = mapping->clsid;
751             return TRUE;
752         }
753     }
754     return FALSE;
755 }
756
757 static HMODULE load_com_dll(const char *name, char **path, char *filename)
758 {
759     HMODULE dll = NULL;
760     HKEY hkey;
761     char keyname[100];
762     char dllname[MAX_PATH];
763     char *p;
764     CLSID clsid;
765
766     if(!get_main_clsid(name, &clsid)) return NULL;
767
768     sprintf(keyname, "CLSID\\{%08x-%04x-%04x-%02x%2x-%02x%2x%02x%2x%02x%2x}\\InprocServer32",
769             clsid.Data1, clsid.Data2, clsid.Data3, clsid.Data4[0], clsid.Data4[1],
770             clsid.Data4[2], clsid.Data4[3], clsid.Data4[4], clsid.Data4[5],
771             clsid.Data4[6], clsid.Data4[7]);
772
773     if(RegOpenKeyA(HKEY_CLASSES_ROOT, keyname, &hkey) == ERROR_SUCCESS)
774     {
775         LONG size = sizeof(dllname);
776         if(RegQueryValueA(hkey, NULL, dllname, &size) == ERROR_SUCCESS)
777         {
778             if ((dll = LoadLibraryExA(dllname, NULL, LOAD_LIBRARY_AS_DATAFILE)))
779             {
780                 strcpy( filename, dllname );
781                 p = strrchr(dllname, '\\');
782                 if (p) *p = 0;
783                 *path = heap_strdup( dllname );
784             }
785         }
786         RegCloseKey(hkey);
787     }
788
789     return dll;
790 }
791
792 static void get_dll_path(HMODULE dll, char **path, char *filename)
793 {
794     char dllpath[MAX_PATH];
795
796     GetModuleFileNameA(dll, dllpath, MAX_PATH);
797     strcpy(filename, dllpath);
798     *strrchr(dllpath, '\\') = '\0';
799     *path = heap_strdup( dllpath );
800 }
801
802 static BOOL CALLBACK
803 extract_test_proc (HMODULE hModule, LPCTSTR lpszType,
804                    LPTSTR lpszName, LONG_PTR lParam)
805 {
806     const char *tempdir = (const char *)lParam;
807     char dllname[MAX_PATH];
808     char filename[MAX_PATH];
809     WCHAR dllnameW[MAX_PATH];
810     HMODULE dll;
811     DWORD err;
812     HANDLE actctx;
813     ULONG_PTR cookie;
814
815     if (aborting) return TRUE;
816
817     /* Check if the main dll is present on this system */
818     CharLowerA(lpszName);
819     strcpy(dllname, lpszName);
820     *strstr(dllname, testexe) = 0;
821
822     if (test_filtered_out( lpszName, NULL ))
823     {
824         nr_of_skips++;
825         xprintf ("    %s=skipped\n", dllname);
826         return TRUE;
827     }
828     extract_test (&wine_tests[nr_of_files], tempdir, lpszName);
829
830     if (pCreateActCtxA != NULL && pActivateActCtx != NULL &&
831         pDeactivateActCtx != NULL && pReleaseActCtx != NULL)
832     {
833         ACTCTXA actctxinfo;
834         memset(&actctxinfo, 0, sizeof(ACTCTXA));
835         actctxinfo.cbSize = sizeof(ACTCTXA);
836         actctxinfo.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID;
837         actctxinfo.lpSource = wine_tests[nr_of_files].exename;
838         actctxinfo.lpResourceName = CREATEPROCESS_MANIFEST_RESOURCE_ID;
839         actctx = pCreateActCtxA(&actctxinfo);
840         if (actctx != INVALID_HANDLE_VALUE &&
841             ! pActivateActCtx(actctx, &cookie))
842         {
843             pReleaseActCtx(actctx);
844             actctx = INVALID_HANDLE_VALUE;
845         }
846     } else actctx = INVALID_HANDLE_VALUE;
847
848     wine_tests[nr_of_files].maindllpath = NULL;
849     strcpy(filename, dllname);
850     dll = LoadLibraryExA(dllname, NULL, LOAD_LIBRARY_AS_DATAFILE);
851
852     if (!dll) dll = load_com_dll(dllname, &wine_tests[nr_of_files].maindllpath, filename);
853
854     if (!dll && pLoadLibraryShim)
855     {
856         MultiByteToWideChar(CP_ACP, 0, dllname, -1, dllnameW, MAX_PATH);
857         if (SUCCEEDED( pLoadLibraryShim(dllnameW, NULL, NULL, &dll) ) && dll)
858         {
859             get_dll_path(dll, &wine_tests[nr_of_files].maindllpath, filename);
860             FreeLibrary(dll);
861             dll = LoadLibraryExA(filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
862         }
863         else dll = 0;
864     }
865
866     if (!dll)
867     {
868         xprintf ("    %s=dll is missing\n", dllname);
869         if (actctx != INVALID_HANDLE_VALUE)
870         {
871             pDeactivateActCtx(0, cookie);
872             pReleaseActCtx(actctx);
873         }
874         return TRUE;
875     }
876     if (is_native_dll(dll))
877     {
878         FreeLibrary(dll);
879         xprintf ("    %s=load error Configured as native\n", dllname);
880         nr_native_dlls++;
881         if (actctx != INVALID_HANDLE_VALUE)
882         {
883             pDeactivateActCtx(0, cookie);
884             pReleaseActCtx(actctx);
885         }
886         return TRUE;
887     }
888     FreeLibrary(dll);
889
890     if (!(err = get_subtests( tempdir, &wine_tests[nr_of_files], lpszName )))
891     {
892         xprintf ("    %s=%s\n", dllname, get_file_version(filename));
893         nr_of_tests += wine_tests[nr_of_files].subtest_count;
894         nr_of_files++;
895     }
896     else
897     {
898         xprintf ("    %s=load error %u\n", dllname, err);
899     }
900
901     if (actctx != INVALID_HANDLE_VALUE)
902     {
903         pDeactivateActCtx(0, cookie);
904         pReleaseActCtx(actctx);
905     }
906     return TRUE;
907 }
908
909 static char *
910 run_tests (char *logname, char *outdir)
911 {
912     int i;
913     char *strres, *eol, *nextline;
914     DWORD strsize;
915     SECURITY_ATTRIBUTES sa;
916     char tmppath[MAX_PATH], tempdir[MAX_PATH+4];
917     DWORD needed;
918     HMODULE kernel32;
919
920     /* Get the current PATH only once */
921     needed = GetEnvironmentVariableA("PATH", NULL, 0);
922     curpath = heap_alloc(needed);
923     GetEnvironmentVariableA("PATH", curpath, needed);
924
925     SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
926
927     if (!GetTempPathA( MAX_PATH, tmppath ))
928         report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
929
930     if (!logname) {
931         static char tmpname[MAX_PATH];
932         if (!GetTempFileNameA( tmppath, "res", 0, tmpname ))
933             report (R_FATAL, "Can't name logfile.");
934         logname = tmpname;
935     }
936     report (R_OUT, logname);
937
938     /* make handle inheritable */
939     sa.nLength = sizeof(sa);
940     sa.lpSecurityDescriptor = NULL;
941     sa.bInheritHandle = TRUE;
942
943     logfile = CreateFileA( logname, GENERIC_READ|GENERIC_WRITE,
944                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
945                            &sa, CREATE_ALWAYS, 0, NULL );
946
947     if ((logfile == INVALID_HANDLE_VALUE) &&
948         (GetLastError() == ERROR_INVALID_PARAMETER)) {
949         /* FILE_SHARE_DELETE not supported on win9x */
950         logfile = CreateFileA( logname, GENERIC_READ|GENERIC_WRITE,
951                            FILE_SHARE_READ | FILE_SHARE_WRITE,
952                            &sa, CREATE_ALWAYS, 0, NULL );
953     }
954     if (logfile == INVALID_HANDLE_VALUE)
955         report (R_FATAL, "Could not open logfile: %u", GetLastError());
956
957     /* try stable path for ZoneAlarm */
958     if (!outdir) {
959         strcpy( tempdir, tmppath );
960         strcat( tempdir, "wct" );
961
962         if (!CreateDirectoryA( tempdir, NULL ))
963         {
964             if (!GetTempFileNameA( tmppath, "wct", 0, tempdir ))
965                 report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
966             DeleteFileA( tempdir );
967             if (!CreateDirectoryA( tempdir, NULL ))
968                 report (R_FATAL, "Could not create directory: %s", tempdir);
969         }
970     }
971     else
972         strcpy( tempdir, outdir);
973
974     report (R_DIR, tempdir);
975
976     xprintf ("Version 4\n");
977     xprintf ("Tests from build %s\n", build_id[0] ? build_id : "-" );
978     xprintf ("Archive: -\n");  /* no longer used */
979     xprintf ("Tag: %s\n", tag);
980     xprintf ("Build info:\n");
981     strres = extract_rcdata ("BUILD_INFO", "STRINGRES", &strsize);
982     while (strres) {
983         eol = memchr (strres, '\n', strsize);
984         if (!eol) {
985             nextline = NULL;
986             eol = strres + strsize;
987         } else {
988             strsize -= eol - strres + 1;
989             nextline = strsize?eol+1:NULL;
990             if (eol > strres && *(eol-1) == '\r') eol--;
991         }
992         xprintf ("    %.*s\n", eol-strres, strres);
993         strres = nextline;
994     }
995     xprintf ("Operating system version:\n");
996     print_version ();
997     print_language ();
998     xprintf ("Dll info:\n" );
999
1000     report (R_STATUS, "Counting tests");
1001     if (!EnumResourceNames (NULL, "TESTRES", EnumTestFileProc, (LPARAM)&nr_of_files))
1002         report (R_FATAL, "Can't enumerate test files: %d",
1003                 GetLastError ());
1004     wine_tests = heap_alloc (nr_of_files * sizeof wine_tests[0]);
1005
1006     /* Do this only once during extraction (and version checking) */
1007     hmscoree = LoadLibraryA("mscoree.dll");
1008     pLoadLibraryShim = NULL;
1009     if (hmscoree)
1010         pLoadLibraryShim = (void *)GetProcAddress(hmscoree, "LoadLibraryShim");
1011     kernel32 = GetModuleHandleA("kernel32.dll");
1012     pCreateActCtxA = (void *)GetProcAddress(kernel32, "CreateActCtxA");
1013     pActivateActCtx = (void *)GetProcAddress(kernel32, "ActivateActCtx");
1014     pDeactivateActCtx = (void *)GetProcAddress(kernel32, "DeactivateActCtx");
1015     pReleaseActCtx = (void *)GetProcAddress(kernel32, "ReleaseActCtx");
1016
1017     report (R_STATUS, "Extracting tests");
1018     report (R_PROGRESS, 0, nr_of_files);
1019     nr_of_files = 0;
1020     nr_of_tests = 0;
1021     nr_of_skips = 0;
1022     if (!EnumResourceNames (NULL, "TESTRES", extract_test_proc, (LPARAM)tempdir))
1023         report (R_FATAL, "Can't enumerate test files: %d",
1024                 GetLastError ());
1025
1026     FreeLibrary(hmscoree);
1027
1028     if (aborting) return logname;
1029
1030     xprintf ("Test output:\n" );
1031
1032     report (R_DELTA, 0, "Extracting: Done");
1033
1034     if (nr_native_dlls)
1035         report( R_WARNING, "Some dlls are configured as native, you won't be able to submit results." );
1036
1037     report (R_STATUS, "Running tests");
1038     report (R_PROGRESS, 1, nr_of_tests);
1039     for (i = 0; i < nr_of_files; i++) {
1040         struct wine_test *test = wine_tests + i;
1041         int j;
1042
1043         if (aborting) break;
1044
1045         if (test->maindllpath) {
1046             /* We need to add the path (to the main dll) to PATH */
1047             append_path(test->maindllpath);
1048         }
1049
1050         for (j = 0; j < test->subtest_count; j++) {
1051             if (aborting) break;
1052             run_test (test, test->subtests[j], logfile, tempdir);
1053         }
1054
1055         if (test->maindllpath) {
1056             /* Restore PATH again */
1057             SetEnvironmentVariableA("PATH", curpath);
1058         }
1059     }
1060     report (R_DELTA, 0, "Running: Done");
1061
1062     report (R_STATUS, "Cleaning up");
1063     CloseHandle( logfile );
1064     logfile = 0;
1065     if (!outdir)
1066         remove_dir (tempdir);
1067     heap_free(wine_tests);
1068     heap_free(curpath);
1069
1070     return logname;
1071 }
1072
1073 static BOOL WINAPI ctrl_handler(DWORD ctrl_type)
1074 {
1075     if (ctrl_type == CTRL_C_EVENT) {
1076         printf("Ignoring Ctrl-C, use Ctrl-Break if you really want to terminate\n");
1077         return TRUE;
1078     }
1079
1080     return FALSE;
1081 }
1082
1083
1084 static BOOL CALLBACK
1085 extract_only_proc (HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam)
1086 {
1087     const char *target_dir = (const char *)lParam;
1088     char filename[MAX_PATH];
1089
1090     if (test_filtered_out( lpszName, NULL )) return TRUE;
1091
1092     strcpy(filename, lpszName);
1093     CharLowerA(filename);
1094
1095     extract_test( &wine_tests[nr_of_files], target_dir, filename );
1096     nr_of_files++;
1097     return TRUE;
1098 }
1099
1100 static void extract_only (const char *target_dir)
1101 {
1102     BOOL res;
1103
1104     report (R_DIR, target_dir);
1105     res = CreateDirectoryA( target_dir, NULL );
1106     if (!res && GetLastError() != ERROR_ALREADY_EXISTS)
1107         report (R_FATAL, "Could not create directory: %s (%d)", target_dir, GetLastError ());
1108
1109     nr_of_files = 0;
1110     report (R_STATUS, "Counting tests");
1111     if (!EnumResourceNames (NULL, "TESTRES", EnumTestFileProc, (LPARAM)&nr_of_files))
1112         report (R_FATAL, "Can't enumerate test files: %d", GetLastError ());
1113
1114     wine_tests = heap_alloc (nr_of_files * sizeof wine_tests[0] );
1115
1116     report (R_STATUS, "Extracting tests");
1117     report (R_PROGRESS, 0, nr_of_files);
1118     nr_of_files = 0;
1119     if (!EnumResourceNames (NULL, "TESTRES", extract_only_proc, (LPARAM)target_dir))
1120         report (R_FATAL, "Can't enumerate test files: %d", GetLastError ());
1121
1122     report (R_DELTA, 0, "Extracting: Done");
1123 }
1124
1125 static void
1126 usage (void)
1127 {
1128     fprintf (stderr,
1129 "Usage: winetest [OPTION]... [TESTS]\n\n"
1130 " --help    print this message and exit\n"
1131 " --version print the build version and exit\n"
1132 " -c        console mode, no GUI\n"
1133 " -d DIR    Use DIR as temp directory (default: %%TEMP%%\\wct)\n"
1134 " -e        preserve the environment\n"
1135 " -h        print this message and exit\n"
1136 " -i INFO   an optional description of the test platform\n"
1137 " -m MAIL   an email address to enable developers to contact you\n"
1138 " -n        exclude the specified tests\n"
1139 " -p        shutdown when the tests are done\n"
1140 " -q        quiet mode, no output at all\n"
1141 " -o FILE   put report into FILE, do not submit\n"
1142 " -s FILE   submit FILE, do not run tests\n"
1143 " -t TAG    include TAG of characters [-.0-9a-zA-Z] in the report\n"
1144 " -u URL    include TestBot URL in the report\n"
1145 " -x DIR    Extract tests to DIR (default: .\\wct) and exit\n");
1146 }
1147
1148 int main( int argc, char *argv[] )
1149 {
1150     BOOL (WINAPI *pIsWow64Process)(HANDLE hProcess, PBOOL Wow64Process);
1151     char *logname = NULL, *outdir = NULL;
1152     const char *extract = NULL;
1153     const char *cp, *submit = NULL;
1154     int reset_env = 1;
1155     int poweroff = 0;
1156     int interactive = 1;
1157     int i;
1158
1159     if (!LoadStringA( 0, IDS_BUILD_ID, build_id, sizeof(build_id) )) build_id[0] = 0;
1160
1161     pIsWow64Process = (void *)GetProcAddress(GetModuleHandleA("kernel32.dll"),"IsWow64Process");
1162     if (!pIsWow64Process || !pIsWow64Process( GetCurrentProcess(), &is_wow64 )) is_wow64 = FALSE;
1163
1164     for (i = 1; i < argc && argv[i]; i++)
1165     {
1166         if (!strcmp(argv[i], "--help")) {
1167             usage ();
1168             exit (0);
1169         }
1170         else if (!strcmp(argv[i], "--version")) {
1171             printf("%-12.12s\n", build_id[0] ? build_id : "unknown");
1172             exit (0);
1173         }
1174         else if ((argv[i][0] != '-' && argv[i][0] != '/') || argv[i][2]) {
1175             if (nb_filters == sizeof(filters)/sizeof(filters[0]))
1176             {
1177                 report (R_ERROR, "Too many test filters specified");
1178                 exit (2);
1179             }
1180             filters[nb_filters++] = argv[i];
1181         }
1182         else switch (argv[i][1]) {
1183         case 'c':
1184             report (R_TEXTMODE);
1185             interactive = 0;
1186             break;
1187         case 'e':
1188             reset_env = 0;
1189             break;
1190         case 'h':
1191         case '?':
1192             usage ();
1193             exit (0);
1194         case 'i':
1195             if (!(description = argv[++i]))
1196             {
1197                 usage();
1198                 exit( 2 );
1199             }
1200             break;
1201         case 'm':
1202             if (!(email = argv[++i]))
1203             {
1204                 usage();
1205                 exit( 2 );
1206             }
1207             break;
1208         case 'n':
1209             exclude_tests = TRUE;
1210             break;
1211         case 'p':
1212             poweroff = 1;
1213             break;
1214         case 'q':
1215             report (R_QUIET);
1216             interactive = 0;
1217             break;
1218         case 's':
1219             if (!(submit = argv[++i]))
1220             {
1221                 usage();
1222                 exit( 2 );
1223             }
1224             if (tag)
1225                 report (R_WARNING, "ignoring tag for submission");
1226             send_file (submit);
1227             break;
1228         case 'o':
1229             if (!(logname = argv[++i]))
1230             {
1231                 usage();
1232                 exit( 2 );
1233             }
1234             break;
1235         case 't':
1236             if (!(tag = argv[++i]))
1237             {
1238                 usage();
1239                 exit( 2 );
1240             }
1241             if (strlen (tag) > MAXTAGLEN)
1242                 report (R_FATAL, "tag is too long (maximum %d characters)",
1243                         MAXTAGLEN);
1244             cp = findbadtagchar (tag);
1245             if (cp) {
1246                 report (R_ERROR, "invalid char in tag: %c", *cp);
1247                 usage ();
1248                 exit (2);
1249             }
1250             break;
1251         case 'u':
1252             if (!(url = argv[++i]))
1253             {
1254                 usage();
1255                 exit( 2 );
1256             }
1257             break;
1258         case 'x':
1259             report (R_TEXTMODE);
1260             if (!(extract = argv[++i]))
1261                 extract = ".\\wct";
1262
1263             extract_only (extract);
1264             break;
1265         case 'd':
1266             outdir = argv[++i];
1267             break;
1268         default:
1269             report (R_ERROR, "invalid option: -%c", argv[i][1]);
1270             usage ();
1271             exit (2);
1272         }
1273     }
1274     if (!submit && !extract) {
1275         int is_win9x = (GetVersion() & 0x80000000) != 0;
1276
1277         report (R_STATUS, "Starting up");
1278
1279         if (is_win9x)
1280             report (R_WARNING, "Running on win9x is not supported. You won't be able to submit results.");
1281
1282         if (!running_on_visible_desktop ())
1283             report (R_FATAL, "Tests must be run on a visible desktop");
1284
1285         if (running_under_wine())
1286         {
1287             if (!check_mount_mgr())
1288                 report (R_FATAL, "Mount manager not running, most likely your WINEPREFIX wasn't created correctly.");
1289
1290             if (!check_wow64_registry())
1291                 report (R_FATAL, "WoW64 keys missing, most likely your WINEPREFIX wasn't created correctly.");
1292
1293             if (!check_display_driver())
1294                 report (R_FATAL, "Unable to create a window, the display driver is not working.");
1295         }
1296
1297         SetConsoleCtrlHandler(ctrl_handler, TRUE);
1298
1299         if (reset_env)
1300         {
1301             SetEnvironmentVariableA( "WINETEST_PLATFORM", running_under_wine () ? "wine" : "windows" );
1302             SetEnvironmentVariableA( "WINETEST_DEBUG", "1" );
1303             SetEnvironmentVariableA( "WINETEST_INTERACTIVE", "0" );
1304             SetEnvironmentVariableA( "WINETEST_REPORT_SUCCESS", "0" );
1305         }
1306
1307         while (!tag) {
1308             if (!interactive)
1309                 report (R_FATAL, "Please specify a tag (-t option) if "
1310                         "running noninteractive!");
1311             if (guiAskTag () == IDABORT) exit (1);
1312         }
1313         report (R_TAG);
1314
1315         while (!email) {
1316             if (!interactive)
1317                 report (R_FATAL, "Please specify an email address (-m option) to enable developers\n"
1318                         "    to contact you about your report if necessary.");
1319             if (guiAskEmail () == IDABORT) exit (1);
1320         }
1321
1322         if (!build_id[0])
1323             report( R_WARNING, "You won't be able to submit results without a valid build id.\n"
1324                     "To submit results, winetest needs to be built from a git checkout." );
1325
1326         if (!logname) {
1327             logname = run_tests (NULL, outdir);
1328             if (aborting) {
1329                 DeleteFileA(logname);
1330                 exit (0);
1331             }
1332             if (failures > FAILURES_LIMIT)
1333                 report( R_WARNING,
1334                         "%d tests failed, there's probably something broken with your setup.\n"
1335                         "You need to address this before submitting results.", failures );
1336
1337             if (build_id[0] && nr_of_skips <= SKIP_LIMIT && failures <= FAILURES_LIMIT &&
1338                 !nr_native_dlls && !is_win9x &&
1339                 report (R_ASK, MB_YESNO, "Do you want to submit the test results?") == IDYES)
1340                 if (!send_file (logname) && !DeleteFileA(logname))
1341                     report (R_WARNING, "Can't remove logfile: %u", GetLastError());
1342         } else run_tests (logname, outdir);
1343         report (R_STATUS, "Finished");
1344     }
1345     if (poweroff)
1346     {
1347         HANDLE hToken;
1348         TOKEN_PRIVILEGES npr;
1349
1350         /* enable the shutdown privilege for the current process */
1351         if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
1352         {
1353             LookupPrivilegeValueA(0, SE_SHUTDOWN_NAME, &npr.Privileges[0].Luid);
1354             npr.PrivilegeCount = 1;
1355             npr.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1356             AdjustTokenPrivileges(hToken, FALSE, &npr, 0, 0, 0);
1357             CloseHandle(hToken);
1358         }
1359         ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF | EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER);
1360     }
1361     exit (0);
1362 }