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