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