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