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