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