winetest: Add the ability to retrieve the dll path for com dlls from the registry.
[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     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 (LPCTSTR name, LPCTSTR type, DWORD* size)
288 {
289     HRSRC rsrc;
290     HGLOBAL hdl;
291     LPVOID addr;
292     
293     if (!(rsrc = FindResource (NULL, name, 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 = heap_strdup( 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 = heap_realloc (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 = heap_alloc(strlen(curpath) + 1 + strlen(path) + 1);
353     strcpy(newpath, curpath);
354     strcat(newpath, ";");
355     strcat(newpath, path);
356     SetEnvironmentVariableA("PATH", newpath);
357
358     heap_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         break;
397     default:
398         report (R_ERROR, "Wait returned %d", status);
399         break;
400     }
401     if (!TerminateProcess (pi.hProcess, 257))
402         report (R_ERROR, "TerminateProcess failed: %d", GetLastError ());
403     wait = wait_process( pi.hProcess, 5000 );
404     switch (wait)
405     {
406     case WAIT_OBJECT_0:
407         break;
408     case WAIT_FAILED:
409         report (R_ERROR, "Wait for termination of '%s' failed: %d", cmd, GetLastError ());
410         break;
411     case WAIT_TIMEOUT:
412         report (R_ERROR, "Can't kill process '%s'", cmd);
413         break;
414     default:
415         report (R_ERROR, "Waiting for termination: %d", wait);
416         break;
417     }
418     CloseHandle (pi.hProcess);
419     return status;
420 }
421
422 static DWORD
423 get_subtests (const char *tempdir, struct wine_test *test, LPTSTR res_name)
424 {
425     char *cmd;
426     HANDLE subfile;
427     DWORD err, total;
428     char buffer[8192], *index;
429     static const char header[] = "Valid test names:";
430     int status, allocated;
431     char tmpdir[MAX_PATH], subname[MAX_PATH];
432     SECURITY_ATTRIBUTES sa;
433
434     test->subtest_count = 0;
435
436     if (!GetTempPathA( MAX_PATH, tmpdir ) ||
437         !GetTempFileNameA( tmpdir, "sub", 0, subname ))
438         report (R_FATAL, "Can't name subtests file.");
439
440     /* make handle inheritable */
441     sa.nLength = sizeof(sa);
442     sa.lpSecurityDescriptor = NULL;
443     sa.bInheritHandle = TRUE;
444
445     subfile = CreateFileA( subname, GENERIC_READ|GENERIC_WRITE,
446                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
447                            &sa, CREATE_ALWAYS, 0, NULL );
448
449     if ((subfile == INVALID_HANDLE_VALUE) &&
450         (GetLastError() == ERROR_INVALID_PARAMETER)) {
451         /* FILE_SHARE_DELETE not supported on win9x */
452         subfile = CreateFileA( subname, GENERIC_READ|GENERIC_WRITE,
453                            FILE_SHARE_READ | FILE_SHARE_WRITE,
454                            &sa, CREATE_ALWAYS, 0, NULL );
455     }
456     if (subfile == INVALID_HANDLE_VALUE) {
457         err = GetLastError();
458         report (R_ERROR, "Can't open subtests output of %s: %u",
459                 test->name, GetLastError());
460         goto quit;
461     }
462
463     extract_test (test, tempdir, res_name);
464     cmd = strmake (NULL, "%s --list", test->exename);
465     if (test->maindllpath) {
466         /* We need to add the path (to the main dll) to PATH */
467         append_path(test->maindllpath);
468     }
469     status = run_ex (cmd, subfile, tempdir, 5000);
470     err = GetLastError();
471     if (test->maindllpath) {
472         /* Restore PATH again */
473         SetEnvironmentVariableA("PATH", curpath);
474     }
475     heap_free (cmd);
476
477     if (status == -2)
478     {
479         report (R_ERROR, "Cannot run %s error %u", test->exename, err);
480         goto quit;
481     }
482
483     SetFilePointer( subfile, 0, NULL, FILE_BEGIN );
484     ReadFile( subfile, buffer, sizeof(buffer), &total, NULL );
485     CloseHandle( subfile );
486     if (sizeof buffer == total) {
487         report (R_ERROR, "Subtest list of %s too big.",
488                 test->name, sizeof buffer);
489         err = ERROR_OUTOFMEMORY;
490         goto quit;
491     }
492     buffer[total] = 0;
493
494     index = strstr (buffer, header);
495     if (!index) {
496         report (R_ERROR, "Can't parse subtests output of %s",
497                 test->name);
498         err = ERROR_INTERNAL_ERROR;
499         goto quit;
500     }
501     index += sizeof header;
502
503     allocated = 10;
504     test->subtests = heap_alloc (allocated * sizeof(char*));
505     index = strtok (index, whitespace);
506     while (index) {
507         if (test->subtest_count == allocated) {
508             allocated *= 2;
509             test->subtests = heap_realloc (test->subtests,
510                                            allocated * sizeof(char*));
511         }
512         if (!test_filtered_out( test->name, index ))
513             test->subtests[test->subtest_count++] = heap_strdup(index);
514         index = strtok (NULL, whitespace);
515     }
516     test->subtests = heap_realloc (test->subtests,
517                                    test->subtest_count * sizeof(char*));
518     err = 0;
519
520  quit:
521     if (!DeleteFileA (subname))
522         report (R_WARNING, "Can't delete file '%s': %u", subname, GetLastError());
523     return err;
524 }
525
526 static void
527 run_test (struct wine_test* test, const char* subtest, HANDLE out_file, const char *tempdir)
528 {
529     int status;
530     const char* file = get_test_source_file(test->name, subtest);
531     char *cmd = strmake (NULL, "%s %s", test->exename, subtest);
532
533     xprintf ("%s:%s start %s -\n", test->name, subtest, file);
534     status = run_ex (cmd, out_file, tempdir, 120000);
535     heap_free (cmd);
536     xprintf ("%s:%s done (%d)\n", test->name, subtest, status);
537 }
538
539 static BOOL CALLBACK
540 EnumTestFileProc (HMODULE hModule, LPCTSTR lpszType,
541                   LPTSTR lpszName, LONG_PTR lParam)
542 {
543     if (!test_filtered_out( lpszName, NULL )) (*(int*)lParam)++;
544     return TRUE;
545 }
546
547 static const struct clsid_mapping
548 {
549     const char *name;
550     CLSID clsid;
551 } clsid_list[] =
552 {
553     {"oledb32", {0xc8b522d1, 0x5cf3, 0x11ce, {0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}},
554     {NULL, {0, 0, 0, {0,0,0,0,0,0,0,0}}}
555 };
556
557
558 static BOOL get_main_clsid(const char *name, CLSID *clsid)
559 {
560     const struct clsid_mapping *mapping;
561
562     for(mapping = clsid_list; mapping->name; mapping++)
563     {
564         if(!strcasecmp(name, mapping->name))
565         {
566             *clsid = mapping->clsid;
567             return TRUE;
568         }
569     }
570     return FALSE;
571 }
572
573 static HMODULE load_com_dll(const char *name)
574 {
575     HMODULE dll = NULL;
576     HKEY hkey;
577     char keyname[100];
578     char dllname[MAX_PATH];
579     CLSID clsid;
580
581     if(!get_main_clsid(name, &clsid)) return NULL;
582
583     sprintf(keyname, "CLSID\\{%08x-%04x-%04x-%02x%2x-%02x%2x%02x%2x%02x%2x}\\InprocServer32",
584             clsid.Data1, clsid.Data2, clsid.Data3, clsid.Data4[0], clsid.Data4[1],
585             clsid.Data4[2], clsid.Data4[3], clsid.Data4[4], clsid.Data4[5],
586             clsid.Data4[6], clsid.Data4[7]);
587
588     if(RegOpenKeyA(HKEY_CLASSES_ROOT, keyname, &hkey) == ERROR_SUCCESS)
589     {
590         LONG size = sizeof(dllname);
591         if(RegQueryValueA(hkey, NULL, dllname, &size) == ERROR_SUCCESS)
592             dll = LoadLibraryExA(dllname, NULL, LOAD_LIBRARY_AS_DATAFILE);
593         RegCloseKey(hkey);
594     }
595
596     return dll;
597 }
598
599 static void get_dll_path(HMODULE dll, char **path, char *filename)
600 {
601     char dllpath[MAX_PATH];
602
603     GetModuleFileNameA(dll, dllpath, MAX_PATH);
604     strcpy(filename, dllpath);
605     *strrchr(dllpath, '\\') = '\0';
606     *path = heap_strdup( dllpath );
607 }
608
609 static BOOL CALLBACK
610 extract_test_proc (HMODULE hModule, LPCTSTR lpszType,
611                    LPTSTR lpszName, LONG_PTR lParam)
612 {
613     const char *tempdir = (const char *)lParam;
614     char dllname[MAX_PATH];
615     char filename[MAX_PATH];
616     WCHAR dllnameW[MAX_PATH];
617     HMODULE dll;
618     DWORD err;
619
620     if (test_filtered_out( lpszName, NULL )) return TRUE;
621
622     /* Check if the main dll is present on this system */
623     CharLowerA(lpszName);
624     strcpy(dllname, lpszName);
625     *strstr(dllname, testexe) = 0;
626
627     wine_tests[nr_of_files].maindllpath = NULL;
628     strcpy(filename, dllname);
629     dll = LoadLibraryExA(dllname, NULL, LOAD_LIBRARY_AS_DATAFILE);
630
631     if(!dll)
632     {
633         dll = load_com_dll(dllname);
634         if(dll) get_dll_path(dll, &wine_tests[nr_of_files].maindllpath, filename);
635     }
636
637     if (!dll && pLoadLibraryShim)
638     {
639         MultiByteToWideChar(CP_ACP, 0, dllname, -1, dllnameW, MAX_PATH);
640         if (FAILED( pLoadLibraryShim(dllnameW, NULL, NULL, &dll) ))
641             dll = 0;
642         else
643             get_dll_path(dll, &wine_tests[nr_of_files].maindllpath, filename);
644     }
645
646     if (!dll)
647     {
648         xprintf ("    %s=dll is missing\n", dllname);
649         return TRUE;
650     }
651     if (!strcmp( dllname, "mshtml" ) && running_under_wine() && !gecko_check())
652     {
653         FreeLibrary(dll);
654         xprintf ("    %s=load error Gecko is not installed\n", dllname);
655         return TRUE;
656     }
657     FreeLibrary(dll);
658
659     if (!(err = get_subtests( tempdir, &wine_tests[nr_of_files], lpszName )))
660     {
661         xprintf ("    %s=%s\n", dllname, get_file_version(filename));
662         nr_of_tests += wine_tests[nr_of_files].subtest_count;
663         nr_of_files++;
664     }
665     else
666     {
667         xprintf ("    %s=load error %u\n", dllname, err);
668     }
669     return TRUE;
670 }
671
672 static char *
673 run_tests (char *logname, char *outdir)
674 {
675     int i;
676     char *strres, *eol, *nextline;
677     DWORD strsize;
678     SECURITY_ATTRIBUTES sa;
679     char tmppath[MAX_PATH], tempdir[MAX_PATH+4];
680     DWORD needed;
681
682     /* Get the current PATH only once */
683     needed = GetEnvironmentVariableA("PATH", NULL, 0);
684     curpath = heap_alloc(needed);
685     GetEnvironmentVariableA("PATH", curpath, needed);
686
687     SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
688
689     if (!GetTempPathA( MAX_PATH, tmppath ))
690         report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
691
692     if (!logname) {
693         static char tmpname[MAX_PATH];
694         if (!GetTempFileNameA( tmppath, "res", 0, tmpname ))
695             report (R_FATAL, "Can't name logfile.");
696         logname = tmpname;
697     }
698     report (R_OUT, logname);
699
700     /* make handle inheritable */
701     sa.nLength = sizeof(sa);
702     sa.lpSecurityDescriptor = NULL;
703     sa.bInheritHandle = TRUE;
704
705     logfile = CreateFileA( logname, GENERIC_READ|GENERIC_WRITE,
706                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
707                            &sa, CREATE_ALWAYS, 0, NULL );
708
709     if ((logfile == INVALID_HANDLE_VALUE) &&
710         (GetLastError() == ERROR_INVALID_PARAMETER)) {
711         /* FILE_SHARE_DELETE not supported on win9x */
712         logfile = CreateFileA( logname, GENERIC_READ|GENERIC_WRITE,
713                            FILE_SHARE_READ | FILE_SHARE_WRITE,
714                            &sa, CREATE_ALWAYS, 0, NULL );
715     }
716     if (logfile == INVALID_HANDLE_VALUE)
717         report (R_FATAL, "Could not open logfile: %u", GetLastError());
718
719     /* try stable path for ZoneAlarm */
720     if (!outdir) {
721         strcpy( tempdir, tmppath );
722         strcat( tempdir, "wct" );
723
724         if (!CreateDirectoryA( tempdir, NULL ))
725         {
726             if (!GetTempFileNameA( tmppath, "wct", 0, tempdir ))
727                 report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
728             DeleteFileA( tempdir );
729             if (!CreateDirectoryA( tempdir, NULL ))
730                 report (R_FATAL, "Could not create directory: %s", tempdir);
731         }
732     }
733     else
734         strcpy( tempdir, outdir);
735
736     report (R_DIR, tempdir);
737
738     xprintf ("Version 4\n");
739     xprintf ("Tests from build %s\n", build_id[0] ? build_id : "-" );
740     xprintf ("Archive: -\n");  /* no longer used */
741     xprintf ("Tag: %s\n", tag);
742     xprintf ("Build info:\n");
743     strres = extract_rcdata ("BUILD_INFO", "STRINGRES", &strsize);
744     while (strres) {
745         eol = memchr (strres, '\n', strsize);
746         if (!eol) {
747             nextline = NULL;
748             eol = strres + strsize;
749         } else {
750             strsize -= eol - strres + 1;
751             nextline = strsize?eol+1:NULL;
752             if (eol > strres && *(eol-1) == '\r') eol--;
753         }
754         xprintf ("    %.*s\n", eol-strres, strres);
755         strres = nextline;
756     }
757     xprintf ("Operating system version:\n");
758     print_version ();
759     xprintf ("Dll info:\n" );
760
761     report (R_STATUS, "Counting tests");
762     if (!EnumResourceNames (NULL, "TESTRES", EnumTestFileProc, (LPARAM)&nr_of_files))
763         report (R_FATAL, "Can't enumerate test files: %d",
764                 GetLastError ());
765     wine_tests = heap_alloc (nr_of_files * sizeof wine_tests[0]);
766
767     /* Do this only once during extraction (and version checking) */
768     hmscoree = LoadLibraryA("mscoree.dll");
769     pLoadLibraryShim = NULL;
770     if (hmscoree)
771         pLoadLibraryShim = (void *)GetProcAddress(hmscoree, "LoadLibraryShim");
772
773     report (R_STATUS, "Extracting tests");
774     report (R_PROGRESS, 0, nr_of_files);
775     nr_of_files = 0;
776     nr_of_tests = 0;
777     if (!EnumResourceNames (NULL, "TESTRES", extract_test_proc, (LPARAM)tempdir))
778         report (R_FATAL, "Can't enumerate test files: %d",
779                 GetLastError ());
780
781     FreeLibrary(hmscoree);
782
783     xprintf ("Test output:\n" );
784
785     report (R_DELTA, 0, "Extracting: Done");
786
787     report (R_STATUS, "Running tests");
788     report (R_PROGRESS, 1, nr_of_tests);
789     for (i = 0; i < nr_of_files; i++) {
790         struct wine_test *test = wine_tests + i;
791         int j;
792
793         if (test->maindllpath) {
794             /* We need to add the path (to the main dll) to PATH */
795             append_path(test->maindllpath);
796         }
797
798         for (j = 0; j < test->subtest_count; j++) {
799             report (R_STEP, "Running: %s:%s", test->name,
800                     test->subtests[j]);
801             run_test (test, test->subtests[j], logfile, tempdir);
802         }
803
804         if (test->maindllpath) {
805             /* Restore PATH again */
806             SetEnvironmentVariableA("PATH", curpath);
807         }
808     }
809     report (R_DELTA, 0, "Running: Done");
810
811     report (R_STATUS, "Cleaning up");
812     CloseHandle( logfile );
813     logfile = 0;
814     if (!outdir)
815         remove_dir (tempdir);
816     heap_free(wine_tests);
817     heap_free(curpath);
818
819     return logname;
820 }
821
822 static BOOL WINAPI ctrl_handler(DWORD ctrl_type)
823 {
824     if (ctrl_type == CTRL_C_EVENT) {
825         printf("Ignoring Ctrl-C, use Ctrl-Break if you really want to terminate\n");
826         return TRUE;
827     }
828
829     return FALSE;
830 }
831
832
833 static BOOL CALLBACK
834 extract_only_proc (HMODULE hModule, LPCTSTR lpszType, LPTSTR lpszName, LONG_PTR lParam)
835 {
836     const char *target_dir = (const char *)lParam;
837     char filename[MAX_PATH];
838
839     if (test_filtered_out( lpszName, NULL )) return TRUE;
840
841     strcpy(filename, lpszName);
842     CharLowerA(filename);
843
844     extract_test( &wine_tests[nr_of_files], target_dir, filename );
845     nr_of_files++;
846     return TRUE;
847 }
848
849 static void extract_only (const char *target_dir)
850 {
851     BOOL res;
852
853     report (R_DIR, target_dir);
854     res = CreateDirectoryA( target_dir, NULL );
855     if (!res && GetLastError() != ERROR_ALREADY_EXISTS)
856         report (R_FATAL, "Could not create directory: %s (%d)", target_dir, GetLastError ());
857
858     nr_of_files = 0;
859     report (R_STATUS, "Counting tests");
860     if (!EnumResourceNames (NULL, "TESTRES", EnumTestFileProc, (LPARAM)&nr_of_files))
861         report (R_FATAL, "Can't enumerate test files: %d", GetLastError ());
862
863     wine_tests = heap_alloc (nr_of_files * sizeof wine_tests[0] );
864
865     report (R_STATUS, "Extracting tests");
866     report (R_PROGRESS, 0, nr_of_files);
867     nr_of_files = 0;
868     if (!EnumResourceNames (NULL, "TESTRES", extract_only_proc, (LPARAM)target_dir))
869         report (R_FATAL, "Can't enumerate test files: %d", GetLastError ());
870
871     report (R_DELTA, 0, "Extracting: Done");
872 }
873
874 static void
875 usage (void)
876 {
877     fprintf (stderr,
878 "Usage: winetest [OPTION]... [TESTS]\n\n"
879 " --help    print this message and exit\n"
880 " --version print the build version and exit\n"
881 " -c        console mode, no GUI\n"
882 " -d DIR    Use DIR as temp directory (default: %%TEMP%%\\wct)\n"
883 " -e        preserve the environment\n"
884 " -h        print this message and exit\n"
885 " -p        shutdown when the tests are done\n"
886 " -q        quiet mode, no output at all\n"
887 " -o FILE   put report into FILE, do not submit\n"
888 " -s FILE   submit FILE, do not run tests\n"
889 " -t TAG    include TAG of characters [-.0-9a-zA-Z] in the report\n"
890 " -x DIR    Extract tests to DIR (default: .\\wct) and exit\n");
891 }
892
893 int main( int argc, char *argv[] )
894 {
895     char *logname = NULL, *outdir = NULL;
896     const char *extract = NULL;
897     const char *cp, *submit = NULL;
898     int reset_env = 1;
899     int poweroff = 0;
900     int interactive = 1;
901     int i;
902
903     if (!LoadStringA( 0, IDS_BUILD_ID, build_id, sizeof(build_id) )) build_id[0] = 0;
904
905     for (i = 1; i < argc && argv[i]; i++)
906     {
907         if (!strcmp(argv[i], "--help")) {
908             usage ();
909             exit (0);
910         }
911         else if (!strcmp(argv[i], "--version")) {
912             printf("%-12.12s\n", build_id[0] ? build_id : "unknown");
913             exit (0);
914         }
915         else if ((argv[i][0] != '-' && argv[i][0] != '/') || argv[i][2]) {
916             if (nb_filters == sizeof(filters)/sizeof(filters[0]))
917             {
918                 report (R_ERROR, "Too many test filters specified");
919                 exit (2);
920             }
921             filters[nb_filters++] = argv[i];
922         }
923         else switch (argv[i][1]) {
924         case 'c':
925             report (R_TEXTMODE);
926             interactive = 0;
927             break;
928         case 'e':
929             reset_env = 0;
930             break;
931         case 'h':
932         case '?':
933             usage ();
934             exit (0);
935         case 'p':
936             poweroff = 1;
937             break;
938         case 'q':
939             report (R_QUIET);
940             interactive = 0;
941             break;
942         case 's':
943             if (!(submit = argv[++i]))
944             {
945                 usage();
946                 exit( 2 );
947             }
948             if (tag)
949                 report (R_WARNING, "ignoring tag for submission");
950             send_file (submit);
951             break;
952         case 'o':
953             if (!(logname = argv[++i]))
954             {
955                 usage();
956                 exit( 2 );
957             }
958             break;
959         case 't':
960             if (!(tag = argv[++i]))
961             {
962                 usage();
963                 exit( 2 );
964             }
965             if (strlen (tag) > MAXTAGLEN)
966                 report (R_FATAL, "tag is too long (maximum %d characters)",
967                         MAXTAGLEN);
968             cp = findbadtagchar (tag);
969             if (cp) {
970                 report (R_ERROR, "invalid char in tag: %c", *cp);
971                 usage ();
972                 exit (2);
973             }
974             break;
975         case 'x':
976             report (R_TEXTMODE);
977             if (!(extract = argv[++i]))
978                 extract = ".\\wct";
979
980             extract_only (extract);
981             break;
982         case 'd':
983             outdir = argv[++i];
984             break;
985         default:
986             report (R_ERROR, "invalid option: -%c", argv[i][1]);
987             usage ();
988             exit (2);
989         }
990     }
991     if (!submit && !extract) {
992         report (R_STATUS, "Starting up");
993
994         if (!running_on_visible_desktop ())
995             report (R_FATAL, "Tests must be run on a visible desktop");
996
997         SetConsoleCtrlHandler(ctrl_handler, TRUE);
998
999         if (reset_env)
1000         {
1001             SetEnvironmentVariableA( "WINETEST_PLATFORM", running_under_wine () ? "wine" : "windows" );
1002             SetEnvironmentVariableA( "WINETEST_DEBUG", "1" );
1003             SetEnvironmentVariableA( "WINETEST_INTERACTIVE", "0" );
1004             SetEnvironmentVariableA( "WINETEST_REPORT_SUCCESS", "0" );
1005         }
1006
1007         if (!nb_filters)  /* don't submit results when filtering */
1008         {
1009             while (!tag) {
1010                 if (!interactive)
1011                     report (R_FATAL, "Please specify a tag (-t option) if "
1012                             "running noninteractive!");
1013                 if (guiAskTag () == IDABORT) exit (1);
1014             }
1015             report (R_TAG);
1016
1017             if (!build_id[0])
1018                 report( R_WARNING, "You won't be able to submit results without a valid build id.\n"
1019                         "To submit results, winetest needs to be built from a git checkout." );
1020         }
1021
1022         if (!logname) {
1023             logname = run_tests (NULL, outdir);
1024             if (build_id[0] && !nb_filters &&
1025                 report (R_ASK, MB_YESNO, "Do you want to submit the test results?") == IDYES)
1026                 if (!send_file (logname) && !DeleteFileA(logname))
1027                     report (R_WARNING, "Can't remove logfile: %u", GetLastError());
1028         } else run_tests (logname, outdir);
1029         report (R_STATUS, "Finished");
1030     }
1031     if (poweroff)
1032     {
1033         HANDLE hToken;
1034         TOKEN_PRIVILEGES npr;
1035
1036         /* enable the shutdown privilege for the current process */
1037         if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
1038         {
1039             LookupPrivilegeValueA(0, SE_SHUTDOWN_NAME, &npr.Privileges[0].Luid);
1040             npr.PrivilegeCount = 1;
1041             npr.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1042             AdjustTokenPrivileges(hToken, FALSE, &npr, 0, 0, 0);
1043             CloseHandle(hToken);
1044         }
1045         ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF | EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER);
1046     }
1047     exit (0);
1048 }