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