Reverse the order for deleting the items in resetcontent to correctly
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 #include <stdio.h>
32 #include <stdlib.h>
33 #include <errno.h>
34 #ifdef HAVE_UNISTD_H
35 #  include <unistd.h>
36 #endif
37 #include <windows.h>
38
39 #include "winetest.h"
40 #include "resource.h"
41
42 struct wine_test
43 {
44     char *name;
45     int resource;
46     int subtest_count;
47     char **subtests;
48     char *exename;
49 };
50
51 struct rev_info
52 {
53     const char* file;
54     const char* rev;
55 };
56
57 static struct wine_test *wine_tests;
58 static struct rev_info *rev_infos = NULL;
59 static const char whitespace[] = " \t\r\n";
60
61 static int running_under_wine ()
62 {
63     HMODULE module = GetModuleHandleA("ntdll.dll");
64
65     if (!module) return 0;
66     return (GetProcAddress(module, "wine_server_call") != NULL);
67 }
68
69 static int running_on_visible_desktop ()
70 {
71     return (GetWindowLongA (GetDesktopWindow (), GWL_STYLE) & WS_VISIBLE) != 0;
72 }
73
74 void print_version ()
75 {
76     OSVERSIONINFOEX ver;
77     BOOL ext;
78
79     ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
80     if (!(ext = GetVersionEx ((OSVERSIONINFO *) &ver)))
81     {
82         ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
83         if (!GetVersionEx ((OSVERSIONINFO *) &ver))
84             report (R_FATAL, "Can't get OS version.");
85     }
86
87     xprintf ("    bRunningUnderWine=%d\n", running_under_wine ());
88     xprintf ("    bRunningOnVisibleDesktop=%d\n", running_on_visible_desktop ());
89     xprintf ("    dwMajorVersion=%ld\n    dwMinorVersion=%ld\n"
90              "    dwBuildNumber=%ld\n    PlatformId=%ld\n    szCSDVersion=%s\n",
91              ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber,
92              ver.dwPlatformId, ver.szCSDVersion);
93
94     if (!ext) return;
95
96     xprintf ("    wServicePackMajor=%d\n    wServicePackMinor=%d\n"
97              "    wSuiteMask=%d\n    wProductType=%d\n    wReserved=%d\n",
98              ver.wServicePackMajor, ver.wServicePackMinor, ver.wSuiteMask,
99              ver.wProductType, ver.wReserved);
100 }
101
102 static inline int is_dot_dir(const char* x)
103 {
104     return ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))));
105 }
106
107 void remove_dir (const char *dir)
108 {
109     HANDLE  hFind;
110     WIN32_FIND_DATA wfd;
111     char path[MAX_PATH];
112     size_t dirlen = strlen (dir);
113
114     /* Make sure the directory exists before going further */
115     memcpy (path, dir, dirlen);
116     strcpy (path + dirlen++, "\\*");
117     hFind = FindFirstFile (path, &wfd);
118     if (hFind == INVALID_HANDLE_VALUE) return;
119
120     do {
121         char *lp = wfd.cFileName;
122
123         if (!lp[0]) lp = wfd.cAlternateFileName; /* ? FIXME not (!lp) ? */
124         if (is_dot_dir (lp)) continue;
125         strcpy (path + dirlen, lp);
126         if (FILE_ATTRIBUTE_DIRECTORY & wfd.dwFileAttributes)
127             remove_dir(path);
128         else if (!DeleteFile (path))
129             report (R_WARNING, "Can't delete file %s: error %d",
130                     path, GetLastError ());
131     } while (FindNextFile (hFind, &wfd));
132     FindClose (hFind);
133     if (!RemoveDirectory (dir))
134         report (R_WARNING, "Can't remove directory %s: error %d",
135                 dir, GetLastError ());
136 }
137
138 const char* get_test_source_file(const char* test, const char* subtest)
139 {
140     static const char* special_dirs[][2] = {
141         { "gdi32", "gdi"}, { "kernel32", "kernel" },
142         { "msacm32", "msacm" },
143         { "user32", "user" }, { "winspool.drv", "winspool" },
144         { "ws2_32", "winsock" }, { 0, 0 }
145     };
146     static char buffer[MAX_PATH];
147     int i;
148
149     for (i = 0; special_dirs[i][0]; i++) {
150         if (strcmp(test, special_dirs[i][0]) == 0) {
151             test = special_dirs[i][1];
152             break;
153         }
154     }
155
156     snprintf(buffer, sizeof(buffer), "dlls/%s/tests/%s.c", test, subtest);
157     return buffer;
158 }
159
160 const char* get_file_rev(const char* file)
161 {
162     const struct rev_info* rev;
163  
164     for(rev = rev_infos; rev->file; rev++) {
165         if (strcmp(rev->file, file) == 0) return rev->rev;
166     }
167
168     return "-";
169 }
170
171 void extract_rev_infos ()
172 {
173     char revinfo[256], *p;
174     int size = 0, i, len;
175     HMODULE module = GetModuleHandle (NULL);
176
177     for (i = 0; TRUE; i++) {
178         if (i >= size) {
179             size += 100;
180             rev_infos = xrealloc (rev_infos, size * sizeof (*rev_infos));
181         }
182         memset(rev_infos + i, 0, sizeof(rev_infos[i]));
183
184         len = LoadStringA (module, REV_INFO+i, revinfo, sizeof(revinfo));
185         if (len == 0) break; /* end of revision info */
186         if (len >= sizeof(revinfo) - 1) 
187             report (R_FATAL, "Revision info too long.");
188         if(!(p = strrchr(revinfo, ':')))
189             report (R_FATAL, "Revision info malformed (i=%d)", i);
190         *p = 0;
191         rev_infos[i].file = strdup(revinfo);
192         rev_infos[i].rev = strdup(p + 1);
193     }
194 }
195
196 void* extract_rcdata (int id, int type, DWORD* size)
197 {
198     HRSRC rsrc;
199     HGLOBAL hdl;
200     LPVOID addr;
201     
202     if (!(rsrc = FindResource (NULL, (LPTSTR)id, MAKEINTRESOURCE(type))) ||
203         !(*size = SizeofResource (0, rsrc)) ||
204         !(hdl = LoadResource (0, rsrc)) ||
205         !(addr = LockResource (hdl)))
206         return NULL;
207     return addr;
208 }
209
210 /* Fills in the name and exename fields */
211 void
212 extract_test (struct wine_test *test, const char *dir, int id)
213 {
214     BYTE* code;
215     DWORD size;
216     FILE* fout;
217     int strlen, bufflen = 128;
218     char *exepos;
219
220     code = extract_rcdata (id, TESTRES, &size);
221     if (!code) report (R_FATAL, "Can't find test resource %d: %d",
222                        id, GetLastError ());
223     test->name = xmalloc (bufflen);
224     while ((strlen = LoadStringA (NULL, id, test->name, bufflen))
225            == bufflen - 1) {
226         bufflen *= 2;
227         test->name = xrealloc (test->name, bufflen);
228     }
229     if (!strlen) report (R_FATAL, "Can't read name of test %d.", id);
230     test->exename = strmake (NULL, "%s/%s", dir, test->name);
231     exepos = strstr (test->name, "_test.exe");
232     if (!exepos) report (R_FATAL, "Not an .exe file: %s", test->name);
233     *exepos = 0;
234     test->name = xrealloc (test->name, exepos - test->name + 1);
235     report (R_STEP, "Extracting: %s", test->name);
236
237     if (!(fout = fopen (test->exename, "wb")) ||
238         (fwrite (code, size, 1, fout) != 1) ||
239         fclose (fout)) report (R_FATAL, "Failed to write file %s.",
240                                test->exename);
241 }
242
243 /* Run a command for MS milliseconds.  If OUT != NULL, also redirect
244    stdout to there.
245
246    Return the exit status, -2 if can't create process or the return
247    value of WaitForSingleObject.
248  */
249 int
250 run_ex (char *cmd, const char *out, DWORD ms)
251 {
252     STARTUPINFO si;
253     PROCESS_INFORMATION pi;
254     int fd, oldstdout = -1;
255     DWORD wait, status;
256
257     GetStartupInfo (&si);
258     si.wShowWindow = SW_HIDE;
259     si.dwFlags = STARTF_USESHOWWINDOW;
260
261     if (out) {
262         fd = open (out, O_WRONLY | O_CREAT, 0666);
263         if (-1 == fd)
264             report (R_FATAL, "Can't open '%s': %d", out, errno);
265         oldstdout = dup (1);
266         if (-1 == oldstdout)
267             report (R_FATAL, "Can't save stdout: %d", errno);
268         if (-1 == dup2 (fd, 1))
269             report (R_FATAL, "Can't redirect stdout: %d", errno);
270         close (fd);
271     }
272
273     if (!CreateProcessA (NULL, cmd, NULL, NULL, TRUE, 0,
274                          NULL, NULL, &si, &pi)) {
275         status = -2;
276     } else {
277         CloseHandle (pi.hThread);
278         wait = WaitForSingleObject (pi.hProcess, ms);
279         if (wait == WAIT_OBJECT_0) {
280             GetExitCodeProcess (pi.hProcess, &status);
281         } else {
282             switch (wait) {
283             case WAIT_FAILED:
284                 report (R_ERROR, "Wait for '%s' failed: %d", cmd,
285                         GetLastError ());
286                 break;
287             case WAIT_TIMEOUT:
288                 report (R_ERROR, "Process '%s' timed out.", cmd);
289                 break;
290             default:
291                 report (R_ERROR, "Wait returned %d", wait);
292             }
293             status = wait;
294             if (!TerminateProcess (pi.hProcess, 257))
295                 report (R_ERROR, "TerminateProcess failed: %d",
296                         GetLastError ());
297             wait = WaitForSingleObject (pi.hProcess, 5000);
298             switch (wait) {
299             case WAIT_FAILED:
300                 report (R_ERROR,
301                         "Wait for termination of '%s' failed: %d",
302                         cmd, GetLastError ());
303                 break;
304             case WAIT_OBJECT_0:
305                 break;
306             case WAIT_TIMEOUT:
307                 report (R_ERROR, "Can't kill process '%s'", cmd);
308                 break;
309             default:
310                 report (R_ERROR, "Waiting for termination: %d",
311                         wait);
312             }
313         }
314         CloseHandle (pi.hProcess);
315     }
316
317     if (out) {
318         close (1);
319         if (-1 == dup2 (oldstdout, 1))
320             report (R_FATAL, "Can't recover stdout: %d", errno);
321         close (oldstdout);
322     }
323     return status;
324 }
325
326 void
327 get_subtests (const char *tempdir, struct wine_test *test, int id)
328 {
329     char *subname;
330     FILE *subfile;
331     size_t total;
332     char buffer[8192], *index;
333     static const char header[] = "Valid test names:";
334     int allocated;
335
336     test->subtest_count = 0;
337
338     subname = tempnam (0, "sub");
339     if (!subname) report (R_FATAL, "Can't name subtests file.");
340
341     extract_test (test, tempdir, id);
342     run_ex (test->exename, subname, 5000);
343
344     subfile = fopen (subname, "r");
345     if (!subfile) {
346         report (R_ERROR, "Can't open subtests output of %s: %d",
347                 test->name, errno);
348         goto quit;
349     }
350     total = fread (buffer, 1, sizeof buffer, subfile);
351     fclose (subfile);
352     if (sizeof buffer == total) {
353         report (R_ERROR, "Subtest list of %s too big.",
354                 test->name, sizeof buffer);
355         goto quit;
356     }
357     buffer[total] = 0;
358
359     index = strstr (buffer, header);
360     if (!index) {
361         report (R_ERROR, "Can't parse subtests output of %s",
362                 test->name);
363         goto quit;
364     }
365     index += sizeof header;
366
367     allocated = 10;
368     test->subtests = xmalloc (allocated * sizeof(char*));
369     index = strtok (index, whitespace);
370     while (index) {
371         if (test->subtest_count == allocated) {
372             allocated *= 2;
373             test->subtests = xrealloc (test->subtests,
374                                        allocated * sizeof(char*));
375         }
376         test->subtests[test->subtest_count++] = strdup (index);
377         index = strtok (NULL, whitespace);
378     }
379     test->subtests = xrealloc (test->subtests,
380                                test->subtest_count * sizeof(char*));
381
382  quit:
383     if (remove (subname))
384         report (R_WARNING, "Can't delete file '%s': %d",
385                 subname, errno);
386     free (subname);
387 }
388
389 void
390 run_test (struct wine_test* test, const char* subtest)
391 {
392     int status;
393     const char* file = get_test_source_file(test->name, subtest);
394     const char* rev = get_file_rev(file);
395     char *cmd = strmake (NULL, "%s %s", test->exename, subtest);
396
397     xprintf ("%s:%s start %s %s\n", test->name, subtest, file, rev);
398     status = run_ex (cmd, NULL, 120000);
399     free (cmd);
400     xprintf ("%s:%s done (%d)\n", test->name, subtest, status);
401 }
402
403 BOOL CALLBACK
404 EnumTestFileProc (HMODULE hModule, LPCTSTR lpszType,
405                   LPTSTR lpszName, LONG_PTR lParam)
406 {
407     (*(int*)lParam)++;
408     return TRUE;
409 }
410
411 char *
412 run_tests (char *logname, const char *tag)
413 {
414     int nr_of_files = 0, nr_of_tests = 0, i;
415     char *tempdir;
416     int logfile;
417     char *strres, *eol, *nextline;
418     DWORD strsize;
419
420     SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
421
422     if (!logname) {
423         logname = tempnam (0, "res");
424         if (!logname) report (R_FATAL, "Can't name logfile.");
425     }
426     report (R_OUT, logname);
427
428     logfile = open (logname, O_WRONLY | O_CREAT | O_EXCL | O_APPEND,
429                     0666);
430     if (-1 == logfile) {
431         if (EEXIST == errno)
432             report (R_FATAL, "File %s already exists.", logname);
433         else report (R_FATAL, "Could not open logfile: %d", errno);
434     }
435     if (-1 == dup2 (logfile, 1))
436         report (R_FATAL, "Can't redirect stdout: %d", errno);
437     close (logfile);
438
439     tempdir = tempnam (0, "wct");
440     if (!tempdir)
441         report (R_FATAL, "Can't name temporary dir (check %%TEMP%%).");
442     report (R_DIR, tempdir);
443     if (!CreateDirectory (tempdir, NULL))
444         report (R_FATAL, "Could not create directory: %s", tempdir);
445
446     xprintf ("Version 3\n");
447     strres = extract_rcdata (WINE_BUILD, STRINGRES, &strsize);
448     xprintf ("Tests from build ");
449     if (strres) xprintf ("%.*s", strsize, strres);
450     else xprintf ("-\n");
451     strres = extract_rcdata (TESTS_URL, STRINGRES, &strsize);
452     xprintf ("Archive: ");
453     if (strres) xprintf ("%.*s", strsize, strres);
454     else xprintf ("-\n");
455     xprintf ("Tag: %s\n", tag?tag:"");
456     xprintf ("Build info:\n");
457     strres = extract_rcdata (BUILD_INFO, STRINGRES, &strsize);
458     while (strres) {
459         eol = memchr (strres, '\n', strsize);
460         if (!eol) {
461             nextline = NULL;
462             eol = strres + strsize;
463         } else {
464             strsize -= eol - strres + 1;
465             nextline = strsize?eol+1:NULL;
466             if (eol > strres && *(eol-1) == '\r') eol--;
467         }
468         xprintf ("    %.*s\n", eol-strres, strres);
469         strres = nextline;
470     }
471     xprintf ("Operating system version:\n");
472     print_version ();
473     xprintf ("Test output:\n" );
474
475     report (R_STATUS, "Counting tests");
476     if (!EnumResourceNames (NULL, MAKEINTRESOURCE(TESTRES),
477                             EnumTestFileProc, (LPARAM)&nr_of_files))
478         report (R_FATAL, "Can't enumerate test files: %d",
479                 GetLastError ());
480     wine_tests = xmalloc (nr_of_files * sizeof wine_tests[0]);
481
482     report (R_STATUS, "Extracting tests");
483     report (R_PROGRESS, 0, nr_of_files);
484     for (i = 0; i < nr_of_files; i++) {
485         get_subtests (tempdir, wine_tests+i, i);
486         nr_of_tests += wine_tests[i].subtest_count;
487     }
488     report (R_DELTA, 0, "Extracting: Done");
489
490     report (R_STATUS, "Running tests");
491     report (R_PROGRESS, 1, nr_of_tests);
492     for (i = 0; i < nr_of_files; i++) {
493         struct wine_test *test = wine_tests + i;
494         int j;
495
496         for (j = 0; j < test->subtest_count; j++) {
497             report (R_STEP, "Running: %s:%s", test->name,
498                     test->subtests[j]);
499             run_test (test, test->subtests[j]);
500         }
501     }
502     report (R_DELTA, 0, "Running: Done");
503
504     report (R_STATUS, "Cleaning up");
505     close (1);
506     remove_dir (tempdir);
507     free (tempdir);
508     free (wine_tests);
509
510     return logname;
511 }
512
513 void
514 usage ()
515 {
516     fprintf (stderr, "\
517 Usage: winetest [OPTION]...\n\n\
518   -c       console mode, no GUI\n\
519   -e       preserve the environment\n\
520   -h       print this message and exit\n\
521   -q       quiet mode, no output at all\n\
522   -o FILE  put report into FILE, do not submit\n\
523   -s FILE  submit FILE, do not run tests\n\
524   -t TAG   include TAG of characters [-.0-9a-zA-Z] in the report\n");
525 }
526
527 int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrevInst,
528                     LPSTR cmdLine, int cmdShow)
529 {
530     char *logname = NULL;
531     const char *cp, *submit = NULL, *tag = NULL;
532     int reset_env = 1;
533
534     /* initialize the revision information first */
535     extract_rev_infos();
536
537     cmdLine = strtok (cmdLine, whitespace);
538     while (cmdLine) {
539         if (cmdLine[0] != '-' || cmdLine[2]) {
540             report (R_ERROR, "Not a single letter option: %s", cmdLine);
541             usage ();
542             exit (2);
543         }
544         switch (cmdLine[1]) {
545         case 'c':
546             report (R_TEXTMODE);
547             break;
548         case 'e':
549             reset_env = 0;
550             break;
551         case 'h':
552             usage ();
553             exit (0);
554         case 'q':
555             report (R_QUIET);
556             break;
557         case 's':
558             submit = strtok (NULL, whitespace);
559             if (tag)
560                 report (R_WARNING, "ignoring tag for submission");
561             send_file (submit);
562             break;
563         case 'o':
564             logname = strtok (NULL, whitespace);
565             break;
566         case 't':
567             tag = strtok (NULL, whitespace);
568             cp = badtagchar (tag);
569             if (cp) {
570                 report (R_ERROR, "invalid char in tag: %c", *cp);
571                 usage ();
572                 exit (2);
573             }
574             break;
575         default:
576             report (R_ERROR, "invalid option: -%c", cmdLine[1]);
577             usage ();
578             exit (2);
579         }
580         cmdLine = strtok (NULL, whitespace);
581     }
582     if (!submit) {
583         if (reset_env && (putenv ("WINETEST_PLATFORM=windows") ||
584                           putenv ("WINETEST_DEBUG=1") || 
585                           putenv ("WINETEST_INTERACTIVE=0") ||
586                           putenv ("WINETEST_REPORT_SUCCESS=0")))
587             report (R_FATAL, "Could not reset environment: %d", errno);
588
589         report (R_STATUS, "Starting up");
590         if (!logname) {
591             logname = run_tests (NULL, tag);
592             if (report (R_ASK, MB_YESNO, "Do you want to submit the "
593                         "test results?") == IDYES)
594                 if (!send_file (logname) && remove (logname))
595                     report (R_WARNING, "Can't remove logfile: %d.", errno);
596             free (logname);
597         } else run_tests (logname, tag);
598         report (R_STATUS, "Finished");
599     }
600     exit (0);
601 }