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