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