msxml3: Remove superfluous pointer casts.
[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 #include <stdio.h>
32 #include <assert.h>
33 #include <windows.h>
34
35 #include "winetest.h"
36 #include "resource.h"
37
38 struct wine_test
39 {
40     char *name;
41     int resource;
42     int subtest_count;
43     char **subtests;
44     char *exename;
45 };
46
47 char *tag = NULL;
48 static struct wine_test *wine_tests;
49 static int nr_of_files, nr_of_tests;
50 static const char whitespace[] = " \t\r\n";
51 static const char testexe[] = "_test.exe";
52 static char build_id[64];
53
54 /* filters for running only specific tests */
55 static char *filters[64];
56 static unsigned int nb_filters = 0;
57
58 /* check if test is being filtered out */
59 static BOOL test_filtered_out( LPCSTR module, LPCSTR testname )
60 {
61     char *p, dllname[MAX_PATH];
62     unsigned int i, len;
63
64     strcpy( dllname, module );
65     CharLowerA( dllname );
66     p = strstr( dllname, testexe );
67     if (p) *p = 0;
68     len = strlen(dllname);
69
70     if (!nb_filters) return FALSE;
71     for (i = 0; i < nb_filters; i++)
72     {
73         if (!strncmp( dllname, filters[i], len ))
74         {
75             if (!filters[i][len]) return FALSE;
76             if (filters[i][len] != ':') continue;
77             if (!testname || !strcmp( testname, &filters[i][len+1] )) return FALSE;
78         }
79     }
80     return TRUE;
81 }
82
83 static char * get_file_version(char * file_name)
84 {
85     static char version[32];
86     DWORD size;
87     DWORD handle;
88
89     size = GetFileVersionInfoSizeA(file_name, &handle);
90     if (size) {
91         char * data = xmalloc(size);
92         if (data) {
93             if (GetFileVersionInfoA(file_name, handle, size, data)) {
94                 static char backslash[] = "\\";
95                 VS_FIXEDFILEINFO *pFixedVersionInfo;
96                 UINT len;
97                 if (VerQueryValueA(data, backslash, (LPVOID *)&pFixedVersionInfo, &len)) {
98                     sprintf(version, "%d.%d.%d.%d",
99                             pFixedVersionInfo->dwFileVersionMS >> 16,
100                             pFixedVersionInfo->dwFileVersionMS & 0xffff,
101                             pFixedVersionInfo->dwFileVersionLS >> 16,
102                             pFixedVersionInfo->dwFileVersionLS & 0xffff);
103                 } else
104                     sprintf(version, "version not available");
105             } else
106                 sprintf(version, "unknown");
107             free(data);
108         } else
109             sprintf(version, "failed");
110     } else
111         sprintf(version, "version not available");
112
113     return version;
114 }
115
116 static int running_under_wine (void)
117 {
118     HMODULE module = GetModuleHandleA("ntdll.dll");
119
120     if (!module) return 0;
121     return (GetProcAddress(module, "wine_server_call") != NULL);
122 }
123
124 static int running_on_visible_desktop (void)
125 {
126     HWND desktop;
127     HMODULE huser32 = GetModuleHandle("user32.dll");
128     FARPROC pGetProcessWindowStation = GetProcAddress(huser32, "GetProcessWindowStation");
129     FARPROC pGetUserObjectInformationA = GetProcAddress(huser32, "GetUserObjectInformationA");
130
131     desktop = GetDesktopWindow();
132     if (!GetWindowLongPtrW(desktop, GWLP_WNDPROC)) /* Win9x */
133         return IsWindowVisible(desktop);
134
135     if (pGetProcessWindowStation && pGetUserObjectInformationA)
136     {
137         DWORD len;
138         HWINSTA wstation;
139         USEROBJECTFLAGS uoflags;
140
141         wstation = (HWINSTA)pGetProcessWindowStation();
142         assert(pGetUserObjectInformationA(wstation, UOI_FLAGS, &uoflags, sizeof(uoflags), &len));
143         return (uoflags.dwFlags & WSF_VISIBLE) != 0;
144     }
145     return IsWindowVisible(desktop);
146 }
147
148 static void print_version (void)
149 {
150 #ifdef __i386__
151     static const char platform[] = "i386";
152 #elif defined(__x86_64__)
153     static const char platform[] = "x86_64";
154 #elif defined(__sparc__)
155     static const char platform[] = "sparc";
156 #elif defined(__ALPHA__)
157     static const char platform[] = "alpha";
158 #elif defined(__powerpc__)
159     static const char platform[] = "powerpc";
160 #endif
161     OSVERSIONINFOEX ver;
162     BOOL ext, wow64;
163     int is_win2k3_r2;
164     const char *(CDECL *wine_get_build_id)(void);
165     void (CDECL *wine_get_host_version)( const char **sysname, const char **release );
166     BOOL (WINAPI *pIsWow64Process)(HANDLE hProcess, PBOOL Wow64Process);
167
168     ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
169     if (!(ext = GetVersionEx ((OSVERSIONINFO *) &ver)))
170     {
171         ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
172         if (!GetVersionEx ((OSVERSIONINFO *) &ver))
173             report (R_FATAL, "Can't get OS version.");
174     }
175     pIsWow64Process = (void *)GetProcAddress(GetModuleHandleA("kernel32.dll"),"IsWow64Process");
176     if (!pIsWow64Process || !pIsWow64Process( GetCurrentProcess(), &wow64 )) wow64 = FALSE;
177
178     xprintf ("    Platform=%s%s\n", platform, wow64 ? " (WOW64)" : "");
179     xprintf ("    bRunningUnderWine=%d\n", running_under_wine ());
180     xprintf ("    bRunningOnVisibleDesktop=%d\n", running_on_visible_desktop ());
181     xprintf ("    dwMajorVersion=%u\n    dwMinorVersion=%u\n"
182              "    dwBuildNumber=%u\n    PlatformId=%u\n    szCSDVersion=%s\n",
183              ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
184              ver.dwPlatformId, ver.szCSDVersion);
185
186     wine_get_build_id = (void *)GetProcAddress(GetModuleHandleA("ntdll.dll"), "wine_get_build_id");
187     wine_get_host_version = (void *)GetProcAddress(GetModuleHandleA("ntdll.dll"), "wine_get_host_version");
188     if (wine_get_build_id) xprintf( "    WineBuild=%s\n", wine_get_build_id() );
189     if (wine_get_host_version)
190     {
191         const char *sysname, *release;
192         wine_get_host_version( &sysname, &release );
193         xprintf( "    Host system=%s\n    Host version=%s\n", sysname, release );
194     }
195     is_win2k3_r2 = GetSystemMetrics(SM_SERVERR2);
196     if(is_win2k3_r2)
197         xprintf("    R2 build number=%d\n", is_win2k3_r2);
198
199     if (!ext) return;
200
201     xprintf ("    wServicePackMajor=%d\n    wServicePackMinor=%d\n"
202              "    wSuiteMask=%d\n    wProductType=%d\n    wReserved=%d\n",
203              ver.wServicePackMajor, ver.wServicePackMinor, ver.wSuiteMask,
204              ver.wProductType, ver.wReserved);
205 }
206
207 static inline int is_dot_dir(const char* x)
208 {
209     return ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))));
210 }
211
212 static void remove_dir (const char *dir)
213 {
214     HANDLE  hFind;
215     WIN32_FIND_DATA wfd;
216     char path[MAX_PATH];
217     size_t dirlen = strlen (dir);
218
219     /* Make sure the directory exists before going further */
220     memcpy (path, dir, dirlen);
221     strcpy (path + dirlen++, "\\*");
222     hFind = FindFirstFile (path, &wfd);
223     if (hFind == INVALID_HANDLE_VALUE) return;
224
225     do {
226         char *lp = wfd.cFileName;
227
228         if (!lp[0]) lp = wfd.cAlternateFileName; /* ? FIXME not (!lp) ? */
229         if (is_dot_dir (lp)) continue;
230         strcpy (path + dirlen, lp);
231         if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
232             remove_dir(path);
233         else if (!DeleteFile (path))
234             report (R_WARNING, "Can't delete file %s: error %d",
235                     path, GetLastError ());
236     } while (FindNextFile (hFind, &wfd));
237     FindClose (hFind);
238     if (!RemoveDirectory (dir))
239         report (R_WARNING, "Can't remove directory %s: error %d",
240                 dir, GetLastError ());
241 }
242
243 static const char* get_test_source_file(const char* test, const char* subtest)
244 {
245     static const char* special_dirs[][2] = {
246         { 0, 0 }
247     };
248     static char buffer[MAX_PATH];
249     int i;
250
251     for (i = 0; special_dirs[i][0]; i++) {
252         if (strcmp(test, special_dirs[i][0]) == 0) {
253             test = special_dirs[i][1];
254             break;
255         }
256     }
257
258     snprintf(buffer, sizeof(buffer), "dlls/%s/tests/%s.c", test, subtest);
259     return buffer;
260 }
261
262 static void* extract_rcdata (LPTSTR name, int type, DWORD* size)
263 {
264     HRSRC rsrc;
265     HGLOBAL hdl;
266     LPVOID addr;
267     
268     if (!(rsrc = FindResource (NULL, name, MAKEINTRESOURCE(type))) ||
269         !(*size = SizeofResource (0, rsrc)) ||
270         !(hdl = LoadResource (0, rsrc)) ||
271         !(addr = LockResource (hdl)))
272         return NULL;
273     return addr;
274 }
275
276 /* Fills in the name and exename fields */
277 static void
278 extract_test (struct wine_test *test, const char *dir, LPTSTR res_name)
279 {
280     BYTE* code;
281     DWORD size;
282     char *exepos;
283     HANDLE hfile;
284     DWORD written;
285
286     code = extract_rcdata (res_name, TESTRES, &size);
287     if (!code) report (R_FATAL, "Can't find test resource %s: %d",
288                        res_name, GetLastError ());
289     test->name = xstrdup( res_name );
290     test->exename = strmake (NULL, "%s\\%s", dir, test->name);
291     exepos = strstr (test->name, testexe);
292     if (!exepos) report (R_FATAL, "Not an .exe file: %s", test->name);
293     *exepos = 0;
294     test->name = xrealloc (test->name, exepos - test->name + 1);
295     report (R_STEP, "Extracting: %s", test->name);
296
297     hfile = CreateFileA(test->exename, GENERIC_READ | GENERIC_WRITE, 0, NULL,
298                         CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
299     if (hfile == INVALID_HANDLE_VALUE)
300         report (R_FATAL, "Failed to open file %s.", test->exename);
301
302     if (!WriteFile(hfile, code, size, &written, NULL))
303         report (R_FATAL, "Failed to write file %s.", test->exename);
304
305     CloseHandle(hfile);
306 }
307
308 /* Run a command for MS milliseconds.  If OUT != NULL, also redirect
309    stdout to there.
310
311    Return the exit status, -2 if can't create process or the return
312    value of WaitForSingleObject.
313  */
314 static int
315 run_ex (char *cmd, HANDLE out_file, const char *tempdir, DWORD ms)
316 {
317     STARTUPINFO si;
318     PROCESS_INFORMATION pi;
319     DWORD wait, status;
320
321     GetStartupInfo (&si);
322     si.dwFlags    = STARTF_USESTDHANDLES;
323     si.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
324     si.hStdOutput = out_file ? out_file : GetStdHandle( STD_OUTPUT_HANDLE );
325     si.hStdError  = out_file ? out_file : GetStdHandle( STD_ERROR_HANDLE );
326
327     if (!CreateProcessA (NULL, cmd, NULL, NULL, TRUE, CREATE_DEFAULT_ERROR_MODE,
328                          NULL, tempdir, &si, &pi)) {
329         status = -2;
330     } else {
331         CloseHandle (pi.hThread);
332         wait = WaitForSingleObject (pi.hProcess, ms);
333         if (wait == WAIT_OBJECT_0) {
334             GetExitCodeProcess (pi.hProcess, &status);
335         } else {
336             switch (wait) {
337             case WAIT_FAILED:
338                 report (R_ERROR, "Wait for '%s' failed: %d", cmd,
339                         GetLastError ());
340                 break;
341             case WAIT_TIMEOUT:
342                 report (R_ERROR, "Process '%s' timed out.", cmd);
343                 break;
344             default:
345                 report (R_ERROR, "Wait returned %d", wait);
346             }
347             status = wait;
348             if (!TerminateProcess (pi.hProcess, 257))
349                 report (R_ERROR, "TerminateProcess failed: %d",
350                         GetLastError ());
351             wait = WaitForSingleObject (pi.hProcess, 5000);
352             switch (wait) {
353             case WAIT_FAILED:
354                 report (R_ERROR,
355                         "Wait for termination of '%s' failed: %d",
356                         cmd, GetLastError ());
357                 break;
358             case WAIT_OBJECT_0:
359                 break;
360             case WAIT_TIMEOUT:
361                 report (R_ERROR, "Can't kill process '%s'", cmd);
362                 break;
363             default:
364                 report (R_ERROR, "Waiting for termination: %d",
365                         wait);
366             }
367         }
368         CloseHandle (pi.hProcess);
369     }
370
371     return status;
372 }
373
374 static DWORD
375 get_subtests (const char *tempdir, struct wine_test *test, LPTSTR res_name)
376 {
377     char *cmd;
378     HANDLE subfile;
379     DWORD err, total;
380     char buffer[8192], *index;
381     static const char header[] = "Valid test names:";
382     int status, allocated;
383     char tmpdir[MAX_PATH], subname[MAX_PATH];
384     SECURITY_ATTRIBUTES sa;
385
386     test->subtest_count = 0;
387
388     if (!GetTempPathA( MAX_PATH, tmpdir ) ||
389         !GetTempFileNameA( tmpdir, "sub", 0, subname ))
390         report (R_FATAL, "Can't name subtests file.");
391
392     /* make handle inheritable */
393     sa.nLength = sizeof(sa);
394     sa.lpSecurityDescriptor = NULL;
395     sa.bInheritHandle = TRUE;
396
397     subfile = CreateFileA( subname, GENERIC_READ|GENERIC_WRITE,
398                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
399                            &sa, CREATE_ALWAYS, 0, NULL );
400
401     if ((subfile == INVALID_HANDLE_VALUE) &&
402         (GetLastError() == ERROR_INVALID_PARAMETER)) {
403         /* FILE_SHARE_DELETE not supported on win9x */
404         subfile = CreateFileA( subname, GENERIC_READ|GENERIC_WRITE,
405                            FILE_SHARE_READ | FILE_SHARE_WRITE,
406                            &sa, CREATE_ALWAYS, 0, NULL );
407     }
408     if (subfile == INVALID_HANDLE_VALUE) {
409         err = GetLastError();
410         report (R_ERROR, "Can't open subtests output of %s: %u",
411                 test->name, GetLastError());
412         goto quit;
413     }
414
415     extract_test (test, tempdir, res_name);
416     cmd = strmake (NULL, "%s --list", test->exename);
417     status = run_ex (cmd, subfile, tempdir, 5000);
418     err = GetLastError();
419     free (cmd);
420
421     if (status == -2)
422     {
423         report (R_ERROR, "Cannot run %s error %u", test->exename, err);
424         goto quit;
425     }
426
427     SetFilePointer( subfile, 0, NULL, FILE_BEGIN );
428     ReadFile( subfile, buffer, sizeof(buffer), &total, NULL );
429     CloseHandle( subfile );
430     if (sizeof buffer == total) {
431         report (R_ERROR, "Subtest list of %s too big.",
432                 test->name, sizeof buffer);
433         err = ERROR_OUTOFMEMORY;
434         goto quit;
435     }
436     buffer[total] = 0;
437
438     index = strstr (buffer, header);
439     if (!index) {
440         report (R_ERROR, "Can't parse subtests output of %s",
441                 test->name);
442         err = ERROR_INTERNAL_ERROR;
443         goto quit;
444     }
445     index += sizeof header;
446
447     allocated = 10;
448     test->subtests = xmalloc (allocated * sizeof(char*));
449     index = strtok (index, whitespace);
450     while (index) {
451         if (test->subtest_count == allocated) {
452             allocated *= 2;
453             test->subtests = xrealloc (test->subtests,
454                                        allocated * sizeof(char*));
455         }
456         if (!test_filtered_out( test->name, index ))
457             test->subtests[test->subtest_count++] = xstrdup(index);
458         index = strtok (NULL, whitespace);
459     }
460     test->subtests = xrealloc (test->subtests,
461                                test->subtest_count * sizeof(char*));
462     err = 0;
463
464  quit:
465     if (!DeleteFileA (subname))
466         report (R_WARNING, "Can't delete file '%s': %u", subname, GetLastError());
467     return err;
468 }
469
470 static void
471 run_test (struct wine_test* test, const char* subtest, HANDLE out_file, const char *tempdir)
472 {
473     int status;
474     const char* file = get_test_source_file(test->name, subtest);
475     char *cmd = strmake (NULL, "%s %s", test->exename, subtest);
476
477     xprintf ("%s:%s start %s -\n", test->name, subtest, file);
478     status = run_ex (cmd, out_file, tempdir, 120000);
479     free (cmd);
480     xprintf ("%s:%s done (%d)\n", test->name, subtest, status);
481 }
482
483 static BOOL CALLBACK
484 EnumTestFileProc (HMODULE hModule, LPCTSTR lpszType,
485                   LPTSTR lpszName, LONG_PTR lParam)
486 {
487     if (!test_filtered_out( lpszName, NULL )) (*(int*)lParam)++;
488     return TRUE;
489 }
490
491 static BOOL CALLBACK
492 extract_test_proc (HMODULE hModule, LPCTSTR lpszType,
493                    LPTSTR lpszName, LONG_PTR lParam)
494 {
495     const char *tempdir = (const char *)lParam;
496     char dllname[MAX_PATH];
497     HMODULE dll;
498     DWORD err;
499
500     if (test_filtered_out( lpszName, NULL )) return TRUE;
501
502     /* Check if the main dll is present on this system */
503     CharLowerA(lpszName);
504     strcpy(dllname, lpszName);
505     *strstr(dllname, testexe) = 0;
506
507     dll = LoadLibraryExA(dllname, NULL, LOAD_LIBRARY_AS_DATAFILE);
508     if (!dll) {
509         xprintf ("    %s=dll is missing\n", dllname);
510         return TRUE;
511     }
512     FreeLibrary(dll);
513
514     if (!(err = get_subtests( tempdir, &wine_tests[nr_of_files], lpszName )))
515     {
516         xprintf ("    %s=%s\n", dllname, get_file_version(dllname));
517         nr_of_tests += wine_tests[nr_of_files].subtest_count;
518         nr_of_files++;
519     }
520     else
521     {
522         xprintf ("    %s=load error %u\n", dllname, err);
523     }
524     return TRUE;
525 }
526
527 static char *
528 run_tests (char *logname)
529 {
530     int i;
531     char *strres, *eol, *nextline;
532     DWORD strsize;
533     SECURITY_ATTRIBUTES sa;
534     char tmppath[MAX_PATH], tempdir[MAX_PATH+4];
535
536     SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
537
538     if (!GetTempPathA( MAX_PATH, tmppath ))
539         report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
540
541     if (!logname) {
542         static char tmpname[MAX_PATH];
543         if (!GetTempFileNameA( tmppath, "res", 0, tmpname ))
544             report (R_FATAL, "Can't name logfile.");
545         logname = tmpname;
546     }
547     report (R_OUT, logname);
548
549     /* make handle inheritable */
550     sa.nLength = sizeof(sa);
551     sa.lpSecurityDescriptor = NULL;
552     sa.bInheritHandle = TRUE;
553
554     logfile = CreateFileA( logname, GENERIC_READ|GENERIC_WRITE,
555                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
556                            &sa, CREATE_ALWAYS, 0, NULL );
557
558     if ((logfile == INVALID_HANDLE_VALUE) &&
559         (GetLastError() == ERROR_INVALID_PARAMETER)) {
560         /* FILE_SHARE_DELETE not supported on win9x */
561         logfile = CreateFileA( logname, GENERIC_READ|GENERIC_WRITE,
562                            FILE_SHARE_READ | FILE_SHARE_WRITE,
563                            &sa, CREATE_ALWAYS, 0, NULL );
564     }
565     if (logfile == INVALID_HANDLE_VALUE)
566         report (R_FATAL, "Could not open logfile: %u", GetLastError());
567
568     if (!GetTempPathA( MAX_PATH, tmppath ))
569         report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
570
571     /* try stable path for ZoneAlarm */
572     strcpy( tempdir, tmppath );
573     strcat( tempdir, "wct" );
574     if (!CreateDirectoryA( tempdir, NULL ))
575     {
576         if (!GetTempFileNameA( tmppath, "wct", 0, tempdir ))
577             report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
578         DeleteFileA( tempdir );
579         if (!CreateDirectoryA( tempdir, NULL ))
580             report (R_FATAL, "Could not create directory: %s", tempdir);
581     }
582     report (R_DIR, tempdir);
583
584     xprintf ("Version 4\n");
585     xprintf ("Tests from build %s\n", build_id[0] ? build_id : "-" );
586     strres = extract_rcdata (MAKEINTRESOURCE(TESTS_URL), STRINGRES, &strsize);
587     xprintf ("Archive: ");
588     if (strres) xprintf ("%.*s", strsize, strres);
589     else xprintf ("-\n");
590     xprintf ("Tag: %s\n", tag);
591     xprintf ("Build info:\n");
592     strres = extract_rcdata (MAKEINTRESOURCE(BUILD_INFO), STRINGRES, &strsize);
593     while (strres) {
594         eol = memchr (strres, '\n', strsize);
595         if (!eol) {
596             nextline = NULL;
597             eol = strres + strsize;
598         } else {
599             strsize -= eol - strres + 1;
600             nextline = strsize?eol+1:NULL;
601             if (eol > strres && *(eol-1) == '\r') eol--;
602         }
603         xprintf ("    %.*s\n", eol-strres, strres);
604         strres = nextline;
605     }
606     xprintf ("Operating system version:\n");
607     print_version ();
608     xprintf ("Dll info:\n" );
609
610     report (R_STATUS, "Counting tests");
611     if (!EnumResourceNames (NULL, MAKEINTRESOURCE(TESTRES),
612                             EnumTestFileProc, (LPARAM)&nr_of_files))
613         report (R_FATAL, "Can't enumerate test files: %d",
614                 GetLastError ());
615     wine_tests = xmalloc (nr_of_files * sizeof wine_tests[0]);
616
617     report (R_STATUS, "Extracting tests");
618     report (R_PROGRESS, 0, nr_of_files);
619     nr_of_files = 0;
620     nr_of_tests = 0;
621     if (!EnumResourceNames (NULL, MAKEINTRESOURCE(TESTRES),
622                             extract_test_proc, (LPARAM)tempdir))
623         report (R_FATAL, "Can't enumerate test files: %d",
624                 GetLastError ());
625
626     xprintf ("Test output:\n" );
627
628     report (R_DELTA, 0, "Extracting: Done");
629
630     report (R_STATUS, "Running tests");
631     report (R_PROGRESS, 1, nr_of_tests);
632     for (i = 0; i < nr_of_files; i++) {
633         struct wine_test *test = wine_tests + i;
634         int j;
635
636         for (j = 0; j < test->subtest_count; j++) {
637             report (R_STEP, "Running: %s:%s", test->name,
638                     test->subtests[j]);
639             run_test (test, test->subtests[j], logfile, tempdir);
640         }
641     }
642     report (R_DELTA, 0, "Running: Done");
643
644     report (R_STATUS, "Cleaning up");
645     CloseHandle( logfile );
646     logfile = 0;
647     remove_dir (tempdir);
648     free (wine_tests);
649
650     return logname;
651 }
652
653 static BOOL WINAPI ctrl_handler(DWORD ctrl_type)
654 {
655     if (ctrl_type == CTRL_C_EVENT) {
656         printf("Ignoring Ctrl-C, use Ctrl-Break if you really want to terminate\n");
657         return TRUE;
658     }
659
660     return FALSE;
661 }
662
663 static void
664 usage (void)
665 {
666     fprintf (stderr,
667 "Usage: winetest [OPTION]... [TESTS]\n\n"
668 "  -c       console mode, no GUI\n"
669 "  -e       preserve the environment\n"
670 "  -h       print this message and exit\n"
671 "  -p       shutdown when the tests are done\n"
672 "  -q       quiet mode, no output at all\n"
673 "  -o FILE  put report into FILE, do not submit\n"
674 "  -s FILE  submit FILE, do not run tests\n"
675 "  -t TAG   include TAG of characters [-.0-9a-zA-Z] in the report\n");
676 }
677
678 int main( int argc, char *argv[] )
679 {
680     char *logname = NULL;
681     const char *cp, *submit = NULL;
682     int reset_env = 1;
683     int poweroff = 0;
684     int interactive = 1;
685     int i;
686
687     if (!LoadStringA( 0, IDS_BUILD_ID, build_id, sizeof(build_id) )) build_id[0] = 0;
688
689     for (i = 1; argv[i]; i++)
690     {
691         if (argv[i][0] != '-' || argv[i][2]) {
692             if (nb_filters == sizeof(filters)/sizeof(filters[0]))
693             {
694                 report (R_ERROR, "Too many test filters specified");
695                 exit (2);
696             }
697             filters[nb_filters++] = argv[i];
698         }
699         else switch (argv[i][1]) {
700         case 'c':
701             report (R_TEXTMODE);
702             interactive = 0;
703             break;
704         case 'e':
705             reset_env = 0;
706             break;
707         case 'h':
708         case '?':
709             usage ();
710             exit (0);
711         case 'p':
712             poweroff = 1;
713             break;
714         case 'q':
715             report (R_QUIET);
716             interactive = 0;
717             break;
718         case 's':
719             if (!(submit = argv[++i]))
720             {
721                 usage();
722                 exit( 2 );
723             }
724             if (tag)
725                 report (R_WARNING, "ignoring tag for submission");
726             send_file (submit);
727             break;
728         case 'o':
729             if (!(logname = argv[++i]))
730             {
731                 usage();
732                 exit( 2 );
733             }
734             break;
735         case 't':
736             if (!(tag = argv[++i]))
737             {
738                 usage();
739                 exit( 2 );
740             }
741             if (strlen (tag) > MAXTAGLEN)
742                 report (R_FATAL, "tag is too long (maximum %d characters)",
743                         MAXTAGLEN);
744             cp = findbadtagchar (tag);
745             if (cp) {
746                 report (R_ERROR, "invalid char in tag: %c", *cp);
747                 usage ();
748                 exit (2);
749             }
750             break;
751         default:
752             report (R_ERROR, "invalid option: -%c", argv[i][1]);
753             usage ();
754             exit (2);
755         }
756     }
757     if (!submit) {
758         report (R_STATUS, "Starting up");
759
760         if (!running_on_visible_desktop ())
761             report (R_FATAL, "Tests must be run on a visible desktop");
762
763         SetConsoleCtrlHandler(ctrl_handler, TRUE);
764
765         if (reset_env)
766         {
767             SetEnvironmentVariableA( "WINETEST_PLATFORM", running_under_wine () ? "wine" : "windows" );
768             SetEnvironmentVariableA( "WINETEST_DEBUG", "1" );
769             SetEnvironmentVariableA( "WINETEST_INTERACTIVE", "0" );
770             SetEnvironmentVariableA( "WINETEST_REPORT_SUCCESS", "0" );
771         }
772
773         if (!nb_filters)  /* don't submit results when filtering */
774         {
775             while (!tag) {
776                 if (!interactive)
777                     report (R_FATAL, "Please specify a tag (-t option) if "
778                             "running noninteractive!");
779                 if (guiAskTag () == IDABORT) exit (1);
780             }
781             report (R_TAG);
782
783             if (!build_id[0])
784                 report( R_WARNING, "You won't be able to submit results without a valid build id.\n"
785                         "To submit results, winetest needs to be built from a git checkout." );
786         }
787
788         if (!logname) {
789             logname = run_tests (NULL);
790             if (build_id[0] && !nb_filters &&
791                 report (R_ASK, MB_YESNO, "Do you want to submit the test results?") == IDYES)
792                 if (!send_file (logname) && !DeleteFileA(logname))
793                     report (R_WARNING, "Can't remove logfile: %u", GetLastError());
794         } else run_tests (logname);
795         report (R_STATUS, "Finished");
796     }
797     if (poweroff)
798     {
799         HANDLE hToken;
800         TOKEN_PRIVILEGES npr;
801
802         /* enable the shutdown privilege for the current process */
803         if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
804         {
805             LookupPrivilegeValueA(0, SE_SHUTDOWN_NAME, &npr.Privileges[0].Luid);
806             npr.PrivilegeCount = 1;
807             npr.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
808             AdjustTokenPrivileges(hToken, FALSE, &npr, 0, 0, 0);
809             CloseHandle(hToken);
810         }
811         ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF | EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER);
812     }
813     exit (0);
814 }