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