kernel32: Make CopyFile() call CopyFileEx() instead of the other way around.
[wine] / dlls / shell32 / tests / shlexec.c
1 /*
2  * Unit test of the ShellExecute function.
3  *
4  * Copyright 2005 Francois Gouget for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /* TODO:
22  * - test the default verb selection
23  * - test selection of an alternate class
24  * - try running executables in more ways
25  * - try passing arguments to executables
26  * - ShellExecute("foo.shlexec") with no path should work if foo.shlexec is
27  *   in the PATH
28  * - test associations that use %l, %L or "%1" instead of %1
29  * - we may want to test ShellExecuteEx() instead of ShellExecute()
30  *   and then we could also check its return value
31  * - ShellExecuteEx() also calls SetLastError() with meaningful values which
32  *   we could check
33  */
34
35 /* Needed to get SEE_MASK_NOZONECHECKS with the PSDK */
36 #define NTDDI_WINXPSP1 0x05010100
37 #define NTDDI_VERSION NTDDI_WINXPSP1
38 #define _WIN32_WINNT 0x0501
39
40 #include <stdio.h>
41 #include <assert.h>
42
43 #include "wtypes.h"
44 #include "winbase.h"
45 #include "windef.h"
46 #include "shellapi.h"
47 #include "shlwapi.h"
48 #include "wine/test.h"
49
50 #include "shell32_test.h"
51
52
53 static char argv0[MAX_PATH];
54 static int myARGC;
55 static char** myARGV;
56 static char tmpdir[MAX_PATH];
57 static char child_file[MAX_PATH];
58 static DLLVERSIONINFO dllver;
59 static BOOL skip_noassoc_tests = FALSE;
60 static HANDLE dde_ready_event;
61
62
63 /***
64  *
65  * ShellExecute wrappers
66  *
67  ***/
68 static void dump_child(void);
69
70 static HANDLE hEvent;
71 static void init_event(const char* child_file)
72 {
73     char* event_name;
74     event_name=strrchr(child_file, '\\')+1;
75     hEvent=CreateEvent(NULL, FALSE, FALSE, event_name);
76 }
77
78 static void strcat_param(char* str, const char* name, const char* param)
79 {
80     if (param)
81     {
82         if (str[strlen(str)-1] == '"')
83             strcat(str, ", ");
84         strcat(str, name);
85         strcat(str, "=\"");
86         strcat(str, param);
87         strcat(str, "\"");
88     }
89 }
90
91 static int _todo_wait = 0;
92 #define todo_wait for (_todo_wait = 1; _todo_wait; _todo_wait = 0)
93
94 static char shell_call[2048]="";
95 static int bad_shellexecute = 0;
96 static INT_PTR shell_execute(LPCSTR verb, LPCSTR file, LPCSTR parameters, LPCSTR directory)
97 {
98     INT_PTR rc, rcEmpty = 0;
99
100     if(!verb)
101         rcEmpty = shell_execute("", file, parameters, directory);
102
103     strcpy(shell_call, "ShellExecute(");
104     strcat_param(shell_call, "verb", verb);
105     strcat_param(shell_call, "file", file);
106     strcat_param(shell_call, "params", parameters);
107     strcat_param(shell_call, "dir", directory);
108     strcat(shell_call, ")");
109     if (winetest_debug > 1)
110         trace("%s\n", shell_call);
111
112     DeleteFile(child_file);
113     SetLastError(0xcafebabe);
114
115     /* FIXME: We cannot use ShellExecuteEx() here because if there is no
116      * association it displays the 'Open With' dialog and I could not find
117      * a flag to prevent this.
118      */
119     rc=(INT_PTR)ShellExecute(NULL, verb, file, parameters, directory, SW_SHOWNORMAL);
120
121     if (rc > 32)
122     {
123         int wait_rc;
124         wait_rc=WaitForSingleObject(hEvent, 5000);
125         if (wait_rc == WAIT_TIMEOUT)
126         {
127             HWND wnd = FindWindowA("#32770", "Windows");
128             if (wnd != NULL)
129             {
130                 SendMessage(wnd, WM_CLOSE, 0, 0);
131                 win_skip("Skipping shellexecute of file with unassociated extension\n");
132                 skip_noassoc_tests = TRUE;
133                 rc = SE_ERR_NOASSOC;
134             }
135         }
136         if (!_todo_wait)
137             ok(wait_rc==WAIT_OBJECT_0 || rc <= 32, "%s WaitForSingleObject returned %d\n", shell_call, wait_rc);
138         else todo_wine
139             ok(wait_rc==WAIT_OBJECT_0 || rc <= 32, "%s WaitForSingleObject returned %d\n", shell_call, wait_rc);
140     }
141     /* The child process may have changed the result file, so let profile
142      * functions know about it
143      */
144     WritePrivateProfileStringA(NULL, NULL, NULL, child_file);
145     if (rc > 32)
146         dump_child();
147
148     if(!verb)
149     {
150         if (rc != rcEmpty && rcEmpty == SE_ERR_NOASSOC) /* NT4 */
151             bad_shellexecute = 1;
152         ok(rc == rcEmpty || broken(rc != rcEmpty && rcEmpty == SE_ERR_NOASSOC) /* NT4 */,
153            "%s Got different return value with empty string: %lu %lu\n", shell_call, rc, rcEmpty);
154     }
155
156     return rc;
157 }
158
159 static INT_PTR shell_execute_ex(DWORD mask, LPCSTR verb, LPCSTR file,
160                                 LPCSTR parameters, LPCSTR directory,
161                                 LPCSTR class)
162 {
163     SHELLEXECUTEINFO sei;
164     BOOL success;
165     INT_PTR rc;
166
167     strcpy(shell_call, "ShellExecuteEx(");
168     if (mask)
169     {
170         char smask[11];
171         sprintf(smask, "0x%x", mask);
172         strcat_param(shell_call, "mask", smask);
173     }
174     strcat_param(shell_call, "verb", verb);
175     strcat_param(shell_call, "file", file);
176     strcat_param(shell_call, "params", parameters);
177     strcat_param(shell_call, "dir", directory);
178     strcat_param(shell_call, "class", class);
179     strcat(shell_call, ")");
180     if (winetest_debug > 1)
181         trace("%s\n", shell_call);
182
183     sei.cbSize=sizeof(sei);
184     sei.fMask=SEE_MASK_NOCLOSEPROCESS | mask;
185     sei.hwnd=NULL;
186     sei.lpVerb=verb;
187     sei.lpFile=file;
188     sei.lpParameters=parameters;
189     sei.lpDirectory=directory;
190     sei.nShow=SW_SHOWNORMAL;
191     sei.hInstApp=NULL; /* Out */
192     sei.lpIDList=NULL;
193     sei.lpClass=class;
194     sei.hkeyClass=NULL;
195     sei.dwHotKey=0;
196     U(sei).hIcon=NULL;
197     sei.hProcess=NULL; /* Out */
198
199     DeleteFile(child_file);
200     SetLastError(0xcafebabe);
201     success=ShellExecuteEx(&sei);
202     rc=(INT_PTR)sei.hInstApp;
203     ok((success && rc > 32) || (!success && rc <= 32),
204        "%s rc=%d and hInstApp=%ld is not allowed\n", shell_call, success, rc);
205
206     if (rc > 32)
207     {
208         int wait_rc;
209         if (sei.hProcess!=NULL)
210         {
211             wait_rc=WaitForSingleObject(sei.hProcess, 5000);
212             ok(wait_rc==WAIT_OBJECT_0, "WaitForSingleObject(hProcess) returned %d\n", wait_rc);
213         }
214         wait_rc=WaitForSingleObject(hEvent, 5000);
215         if (!_todo_wait)
216             ok(wait_rc==WAIT_OBJECT_0, "WaitForSingleObject returned %d\n", wait_rc);
217         else todo_wine
218             ok(wait_rc==WAIT_OBJECT_0, "WaitForSingleObject returned %d\n", wait_rc);
219     }
220     /* The child process may have changed the result file, so let profile
221      * functions know about it
222      */
223     WritePrivateProfileStringA(NULL, NULL, NULL, child_file);
224     if (rc > 32)
225         dump_child();
226
227     return rc;
228 }
229
230
231
232 /***
233  *
234  * Functions to create / delete associations wrappers
235  *
236  ***/
237
238 static BOOL create_test_association(const char* extension)
239 {
240     HKEY hkey, hkey_shell;
241     char class[MAX_PATH];
242     LONG rc;
243
244     sprintf(class, "shlexec%s", extension);
245     rc=RegCreateKeyEx(HKEY_CLASSES_ROOT, extension, 0, NULL, 0, KEY_SET_VALUE,
246                       NULL, &hkey, NULL);
247     if (rc != ERROR_SUCCESS)
248         return FALSE;
249
250     rc=RegSetValueEx(hkey, NULL, 0, REG_SZ, (LPBYTE) class, strlen(class)+1);
251     ok(rc==ERROR_SUCCESS, "RegSetValueEx '%s' failed, expected ERROR_SUCCESS, got %d\n", class, rc);
252     CloseHandle(hkey);
253
254     rc=RegCreateKeyEx(HKEY_CLASSES_ROOT, class, 0, NULL, 0,
255                       KEY_CREATE_SUB_KEY | KEY_ENUMERATE_SUB_KEYS, NULL, &hkey, NULL);
256     ok(rc==ERROR_SUCCESS, "RegCreateKeyEx '%s' failed, expected ERROR_SUCCESS, got %d\n", class, rc);
257
258     rc=RegCreateKeyEx(hkey, "shell", 0, NULL, 0,
259                       KEY_CREATE_SUB_KEY, NULL, &hkey_shell, NULL);
260     ok(rc==ERROR_SUCCESS, "RegCreateKeyEx 'shell' failed, expected ERROR_SUCCESS, got %d\n", rc);
261
262     CloseHandle(hkey);
263     CloseHandle(hkey_shell);
264
265     return TRUE;
266 }
267
268 /* Based on RegDeleteTreeW from dlls/advapi32/registry.c */
269 static LSTATUS myRegDeleteTreeA(HKEY hKey, LPCSTR lpszSubKey)
270 {
271     LONG ret;
272     DWORD dwMaxSubkeyLen, dwMaxValueLen;
273     DWORD dwMaxLen, dwSize;
274     CHAR szNameBuf[MAX_PATH], *lpszName = szNameBuf;
275     HKEY hSubKey = hKey;
276
277     if(lpszSubKey)
278     {
279         ret = RegOpenKeyExA(hKey, lpszSubKey, 0, KEY_READ, &hSubKey);
280         if (ret) return ret;
281     }
282
283     /* Get highest length for keys, values */
284     ret = RegQueryInfoKeyA(hSubKey, NULL, NULL, NULL, NULL,
285             &dwMaxSubkeyLen, NULL, NULL, &dwMaxValueLen, NULL, NULL, NULL);
286     if (ret) goto cleanup;
287
288     dwMaxSubkeyLen++;
289     dwMaxValueLen++;
290     dwMaxLen = max(dwMaxSubkeyLen, dwMaxValueLen);
291     if (dwMaxLen > sizeof(szNameBuf)/sizeof(CHAR))
292     {
293         /* Name too big: alloc a buffer for it */
294         if (!(lpszName = HeapAlloc( GetProcessHeap(), 0, dwMaxLen*sizeof(CHAR))))
295         {
296             ret = ERROR_NOT_ENOUGH_MEMORY;
297             goto cleanup;
298         }
299     }
300
301
302     /* Recursively delete all the subkeys */
303     while (TRUE)
304     {
305         dwSize = dwMaxLen;
306         if (RegEnumKeyExA(hSubKey, 0, lpszName, &dwSize, NULL,
307                           NULL, NULL, NULL)) break;
308
309         ret = myRegDeleteTreeA(hSubKey, lpszName);
310         if (ret) goto cleanup;
311     }
312
313     if (lpszSubKey)
314         ret = RegDeleteKeyA(hKey, lpszSubKey);
315     else
316         while (TRUE)
317         {
318             dwSize = dwMaxLen;
319             if (RegEnumValueA(hKey, 0, lpszName, &dwSize,
320                   NULL, NULL, NULL, NULL)) break;
321
322             ret = RegDeleteValueA(hKey, lpszName);
323             if (ret) goto cleanup;
324         }
325
326 cleanup:
327     /* Free buffer if allocated */
328     if (lpszName != szNameBuf)
329         HeapFree( GetProcessHeap(), 0, lpszName);
330     if(lpszSubKey)
331         RegCloseKey(hSubKey);
332     return ret;
333 }
334
335 static void delete_test_association(const char* extension)
336 {
337     char class[MAX_PATH];
338
339     sprintf(class, "shlexec%s", extension);
340     myRegDeleteTreeA(HKEY_CLASSES_ROOT, class);
341     myRegDeleteTreeA(HKEY_CLASSES_ROOT, extension);
342 }
343
344 static void create_test_verb_dde(const char* extension, const char* verb,
345                                  int rawcmd, const char* cmdtail, const char *ddeexec,
346                                  const char *application, const char *topic,
347                                  const char *ifexec)
348 {
349     HKEY hkey_shell, hkey_verb, hkey_cmd;
350     char shell[MAX_PATH];
351     char* cmd;
352     LONG rc;
353
354     sprintf(shell, "shlexec%s\\shell", extension);
355     rc=RegOpenKeyEx(HKEY_CLASSES_ROOT, shell, 0,
356                     KEY_CREATE_SUB_KEY, &hkey_shell);
357     assert(rc==ERROR_SUCCESS);
358     rc=RegCreateKeyEx(hkey_shell, verb, 0, NULL, 0, KEY_CREATE_SUB_KEY,
359                       NULL, &hkey_verb, NULL);
360     assert(rc==ERROR_SUCCESS);
361     rc=RegCreateKeyEx(hkey_verb, "command", 0, NULL, 0, KEY_SET_VALUE,
362                       NULL, &hkey_cmd, NULL);
363     assert(rc==ERROR_SUCCESS);
364
365     if (rawcmd)
366     {
367         rc=RegSetValueEx(hkey_cmd, NULL, 0, REG_SZ, (LPBYTE)cmdtail, strlen(cmdtail)+1);
368     }
369     else
370     {
371         cmd=HeapAlloc(GetProcessHeap(), 0, strlen(argv0)+10+strlen(child_file)+2+strlen(cmdtail)+1);
372         sprintf(cmd,"%s shlexec \"%s\" %s", argv0, child_file, cmdtail);
373         rc=RegSetValueEx(hkey_cmd, NULL, 0, REG_SZ, (LPBYTE)cmd, strlen(cmd)+1);
374         assert(rc==ERROR_SUCCESS);
375         HeapFree(GetProcessHeap(), 0, cmd);
376     }
377
378     if (ddeexec)
379     {
380         HKEY hkey_ddeexec, hkey_application, hkey_topic, hkey_ifexec;
381
382         rc=RegCreateKeyEx(hkey_verb, "ddeexec", 0, NULL, 0, KEY_SET_VALUE |
383                           KEY_CREATE_SUB_KEY, NULL, &hkey_ddeexec, NULL);
384         assert(rc==ERROR_SUCCESS);
385         rc=RegSetValueEx(hkey_ddeexec, NULL, 0, REG_SZ, (LPBYTE)ddeexec,
386                          strlen(ddeexec)+1);
387         assert(rc==ERROR_SUCCESS);
388         if (application)
389         {
390             rc=RegCreateKeyEx(hkey_ddeexec, "application", 0, NULL, 0, KEY_SET_VALUE,
391                               NULL, &hkey_application, NULL);
392             assert(rc==ERROR_SUCCESS);
393             rc=RegSetValueEx(hkey_application, NULL, 0, REG_SZ, (LPBYTE)application,
394                              strlen(application)+1);
395             assert(rc==ERROR_SUCCESS);
396             CloseHandle(hkey_application);
397         }
398         if (topic)
399         {
400             rc=RegCreateKeyEx(hkey_ddeexec, "topic", 0, NULL, 0, KEY_SET_VALUE,
401                               NULL, &hkey_topic, NULL);
402             assert(rc==ERROR_SUCCESS);
403             rc=RegSetValueEx(hkey_topic, NULL, 0, REG_SZ, (LPBYTE)topic,
404                              strlen(topic)+1);
405             assert(rc==ERROR_SUCCESS);
406             CloseHandle(hkey_topic);
407         }
408         if (ifexec)
409         {
410             rc=RegCreateKeyEx(hkey_ddeexec, "ifexec", 0, NULL, 0, KEY_SET_VALUE,
411                               NULL, &hkey_ifexec, NULL);
412             assert(rc==ERROR_SUCCESS);
413             rc=RegSetValueEx(hkey_ifexec, NULL, 0, REG_SZ, (LPBYTE)ifexec,
414                              strlen(ifexec)+1);
415             assert(rc==ERROR_SUCCESS);
416             CloseHandle(hkey_ifexec);
417         }
418         CloseHandle(hkey_ddeexec);
419     }
420
421     CloseHandle(hkey_shell);
422     CloseHandle(hkey_verb);
423     CloseHandle(hkey_cmd);
424 }
425
426 static void create_test_verb(const char* extension, const char* verb,
427                              int rawcmd, const char* cmdtail)
428 {
429     create_test_verb_dde(extension, verb, rawcmd, cmdtail, NULL, NULL,
430                          NULL, NULL);
431 }
432
433 /***
434  *
435  * Functions to check that the child process was started just right
436  * (borrowed from dlls/kernel32/tests/process.c)
437  *
438  ***/
439
440 static const char* encodeA(const char* str)
441 {
442     static char encoded[2*1024+1];
443     char*       ptr;
444     size_t      len,i;
445
446     if (!str) return "";
447     len = strlen(str) + 1;
448     if (len >= sizeof(encoded)/2)
449     {
450         fprintf(stderr, "string is too long!\n");
451         assert(0);
452     }
453     ptr = encoded;
454     for (i = 0; i < len; i++)
455         sprintf(&ptr[i * 2], "%02x", (unsigned char)str[i]);
456     ptr[2 * len] = '\0';
457     return ptr;
458 }
459
460 static unsigned decode_char(char c)
461 {
462     if (c >= '0' && c <= '9') return c - '0';
463     if (c >= 'a' && c <= 'f') return c - 'a' + 10;
464     assert(c >= 'A' && c <= 'F');
465     return c - 'A' + 10;
466 }
467
468 static char* decodeA(const char* str)
469 {
470     static char decoded[1024];
471     char*       ptr;
472     size_t      len,i;
473
474     len = strlen(str) / 2;
475     if (!len--) return NULL;
476     if (len >= sizeof(decoded))
477     {
478         fprintf(stderr, "string is too long!\n");
479         assert(0);
480     }
481     ptr = decoded;
482     for (i = 0; i < len; i++)
483         ptr[i] = (decode_char(str[2 * i]) << 4) | decode_char(str[2 * i + 1]);
484     ptr[len] = '\0';
485     return ptr;
486 }
487
488 static void     childPrintf(HANDLE h, const char* fmt, ...)
489 {
490     va_list     valist;
491     char        buffer[1024];
492     DWORD       w;
493
494     va_start(valist, fmt);
495     vsprintf(buffer, fmt, valist);
496     va_end(valist);
497     WriteFile(h, buffer, strlen(buffer), &w, NULL);
498 }
499
500 static DWORD ddeInst;
501 static HSZ hszTopic;
502 static char ddeExec[MAX_PATH], ddeApplication[MAX_PATH];
503 static BOOL post_quit_on_execute;
504
505 static HDDEDATA CALLBACK ddeCb(UINT uType, UINT uFmt, HCONV hConv,
506                                HSZ hsz1, HSZ hsz2, HDDEDATA hData,
507                                ULONG_PTR dwData1, ULONG_PTR dwData2)
508 {
509     DWORD size = 0;
510
511     if (winetest_debug > 2)
512         trace("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
513               uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
514
515     switch (uType)
516     {
517         case XTYP_CONNECT:
518             if (!DdeCmpStringHandles(hsz1, hszTopic))
519             {
520                 size = DdeQueryString(ddeInst, hsz2, ddeApplication, MAX_PATH, CP_WINANSI);
521                 assert(size < MAX_PATH);
522                 return (HDDEDATA)TRUE;
523             }
524             return (HDDEDATA)FALSE;
525
526         case XTYP_EXECUTE:
527             size = DdeGetData(hData, (LPBYTE)ddeExec, MAX_PATH, 0L);
528             assert(size < MAX_PATH);
529             DdeFreeDataHandle(hData);
530             if (post_quit_on_execute)
531                 PostQuitMessage(0);
532             return (HDDEDATA)DDE_FACK;
533
534         default:
535             return NULL;
536     }
537 }
538
539 /*
540  * This is just to make sure the child won't run forever stuck in a GetMessage()
541  * loop when DDE fails for some reason.
542  */
543 static void CALLBACK childTimeout(HWND wnd, UINT msg, UINT_PTR timer, DWORD time)
544 {
545     trace("childTimeout called\n");
546
547     PostQuitMessage(0);
548 }
549
550 static void doChild(int argc, char** argv)
551 {
552     char *filename, longpath[MAX_PATH] = "";
553     HANDLE hFile, map;
554     int i;
555     int rc;
556     HSZ hszApplication;
557     UINT_PTR timer;
558     HANDLE dde_ready;
559     MSG msg;
560     char *shared_block;
561
562     filename=argv[2];
563     hFile=CreateFileA(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
564     if (hFile == INVALID_HANDLE_VALUE)
565         return;
566
567     /* Arguments */
568     childPrintf(hFile, "[Arguments]\r\n");
569     if (winetest_debug > 2)
570     {
571         trace("cmdlineA='%s'\n", GetCommandLineA());
572         trace("argcA=%d\n", argc);
573     }
574     childPrintf(hFile, "cmdlineA=%s\r\n", encodeA(GetCommandLineA()));
575     childPrintf(hFile, "argcA=%d\r\n", argc);
576     for (i = 0; i < argc; i++)
577     {
578         if (winetest_debug > 2)
579             trace("argvA%d='%s'\n", i, argv[i]);
580         childPrintf(hFile, "argvA%d=%s\r\n", i, encodeA(argv[i]));
581     }
582     GetModuleFileNameA(GetModuleHandleA(NULL), longpath, MAX_PATH);
583     childPrintf(hFile, "longPath=%s\r\n", encodeA(longpath));
584
585     map = OpenFileMappingA(FILE_MAP_READ, FALSE, "winetest_shlexec_dde_map");
586     if (map != NULL)
587     {
588         shared_block = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 4096);
589         CloseHandle(map);
590         if (shared_block[0] != '\0' || shared_block[1] != '\0')
591         {
592             post_quit_on_execute = TRUE;
593             ddeInst = 0;
594             rc = DdeInitializeA(&ddeInst, ddeCb, CBF_SKIP_ALLNOTIFICATIONS | CBF_FAIL_ADVISES |
595                                 CBF_FAIL_POKES | CBF_FAIL_REQUESTS, 0L);
596             assert(rc == DMLERR_NO_ERROR);
597             hszApplication = DdeCreateStringHandleA(ddeInst, shared_block, CP_WINANSI);
598             hszTopic = DdeCreateStringHandleA(ddeInst, shared_block + strlen(shared_block) + 1, CP_WINANSI);
599             assert(hszApplication && hszTopic);
600             assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_REGISTER | DNS_FILTEROFF));
601
602             timer = SetTimer(NULL, 0, 2500, childTimeout);
603
604             dde_ready = OpenEvent(EVENT_MODIFY_STATE, FALSE, "winetest_shlexec_dde_ready");
605             SetEvent(dde_ready);
606             CloseHandle(dde_ready);
607
608             while (GetMessage(&msg, NULL, 0, 0))
609                 DispatchMessage(&msg);
610
611             Sleep(500);
612             KillTimer(NULL, timer);
613             assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_UNREGISTER));
614             assert(DdeFreeStringHandle(ddeInst, hszTopic));
615             assert(DdeFreeStringHandle(ddeInst, hszApplication));
616             assert(DdeUninitialize(ddeInst));
617         }
618         else
619         {
620             dde_ready = OpenEvent(EVENT_MODIFY_STATE, FALSE, "winetest_shlexec_dde_ready");
621             SetEvent(dde_ready);
622             CloseHandle(dde_ready);
623         }
624
625         UnmapViewOfFile(shared_block);
626
627         childPrintf(hFile, "ddeExec=%s\r\n", encodeA(ddeExec));
628     }
629
630     CloseHandle(hFile);
631
632     init_event(filename);
633     SetEvent(hEvent);
634     CloseHandle(hEvent);
635 }
636
637 static char* getChildString(const char* sect, const char* key)
638 {
639     char        buf[1024];
640     char*       ret;
641
642     GetPrivateProfileStringA(sect, key, "-", buf, sizeof(buf), child_file);
643     if (buf[0] == '\0' || (buf[0] == '-' && buf[1] == '\0')) return NULL;
644     assert(!(strlen(buf) & 1));
645     ret = decodeA(buf);
646     return ret;
647 }
648
649 static void dump_child(void)
650 {
651     if (winetest_debug > 1)
652     {
653         char key[18];
654         char* str;
655         int i, c;
656
657         str=getChildString("Arguments", "cmdlineA");
658         trace("cmdlineA='%s'\n", str);
659         c=GetPrivateProfileIntA("Arguments", "argcA", -1, child_file);
660         trace("argcA=%d\n",c);
661         for (i=0;i<c;i++)
662         {
663             sprintf(key, "argvA%d", i);
664             str=getChildString("Arguments", key);
665             trace("%s='%s'\n", key, str);
666         }
667     }
668 }
669
670 static int StrCmpPath(const char* s1, const char* s2)
671 {
672     if (!s1 && !s2) return 0;
673     if (!s2) return 1;
674     if (!s1) return -1;
675     while (*s1)
676     {
677         if (!*s2)
678         {
679             if (*s1=='.')
680                 s1++;
681             return (*s1-*s2);
682         }
683         if ((*s1=='/' || *s1=='\\') && (*s2=='/' || *s2=='\\'))
684         {
685             while (*s1=='/' || *s1=='\\')
686                 s1++;
687             while (*s2=='/' || *s2=='\\')
688                 s2++;
689         }
690         else if (toupper(*s1)==toupper(*s2))
691         {
692             s1++;
693             s2++;
694         }
695         else
696         {
697             return (*s1-*s2);
698         }
699     }
700     if (*s2=='.')
701         s2++;
702     if (*s2)
703         return -1;
704     return 0;
705 }
706
707 static void _okChildString(const char* file, int line, const char* key, const char* expected, const char* bad)
708 {
709     char* result;
710     result=getChildString("Arguments", key);
711     if (!result)
712     {
713         ok_(file, line)(FALSE, "%s expected '%s', but key not found or empty\n", key, expected);
714         return;
715     }
716     ok_(file, line)(lstrcmpiA(result, expected) == 0 ||
717                     broken(lstrcmpiA(result, bad) == 0),
718                     "%s expected '%s', got '%s'\n", key, expected, result);
719 }
720
721 static void _okChildPath(const char* file, int line, const char* key, const char* expected)
722 {
723     char* result;
724     result=getChildString("Arguments", key);
725     if (!result)
726     {
727         ok_(file, line)(FALSE, "%s expected '%s', but key not found or empty\n", key, expected);
728         return;
729     }
730     ok_(file, line)(StrCmpPath(result, expected) == 0,
731                     "%s expected '%s', got '%s'\n", key, expected, result);
732 }
733
734 static void _okChildInt(const char* file, int line, const char* key, int expected)
735 {
736     INT result;
737     result=GetPrivateProfileIntA("Arguments", key, expected, child_file);
738     ok_(file, line)(result == expected,
739                     "%s expected %d, but got %d\n", key, expected, result);
740 }
741
742 #define okChildString(key, expected) _okChildString(__FILE__, __LINE__, (key), (expected), (expected))
743 #define okChildStringBroken(key, expected, broken) _okChildString(__FILE__, __LINE__, (key), (expected), (broken))
744 #define okChildPath(key, expected) _okChildPath(__FILE__, __LINE__, (key), (expected))
745 #define okChildInt(key, expected)    _okChildInt(__FILE__, __LINE__, (key), (expected))
746
747 /***
748  *
749  * GetLongPathNameA equivalent that supports Win95 and WinNT
750  *
751  ***/
752
753 static DWORD get_long_path_name(const char* shortpath, char* longpath, DWORD longlen)
754 {
755     char tmplongpath[MAX_PATH];
756     const char* p;
757     DWORD sp = 0, lp = 0;
758     DWORD tmplen;
759     WIN32_FIND_DATAA wfd;
760     HANDLE goit;
761
762     if (!shortpath || !shortpath[0])
763         return 0;
764
765     if (shortpath[1] == ':')
766     {
767         tmplongpath[0] = shortpath[0];
768         tmplongpath[1] = ':';
769         lp = sp = 2;
770     }
771
772     while (shortpath[sp])
773     {
774         /* check for path delimiters and reproduce them */
775         if (shortpath[sp] == '\\' || shortpath[sp] == '/')
776         {
777             if (!lp || tmplongpath[lp-1] != '\\')
778             {
779                 /* strip double "\\" */
780                 tmplongpath[lp++] = '\\';
781             }
782             tmplongpath[lp] = 0; /* terminate string */
783             sp++;
784             continue;
785         }
786
787         p = shortpath + sp;
788         if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
789         {
790             tmplongpath[lp++] = *p++;
791             tmplongpath[lp++] = *p++;
792         }
793         for (; *p && *p != '/' && *p != '\\'; p++);
794         tmplen = p - (shortpath + sp);
795         lstrcpyn(tmplongpath + lp, shortpath + sp, tmplen + 1);
796         /* Check if the file exists and use the existing file name */
797         goit = FindFirstFileA(tmplongpath, &wfd);
798         if (goit == INVALID_HANDLE_VALUE)
799             return 0;
800         FindClose(goit);
801         strcpy(tmplongpath + lp, wfd.cFileName);
802         lp += strlen(tmplongpath + lp);
803         sp += tmplen;
804     }
805     tmplen = strlen(shortpath) - 1;
806     if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
807         (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
808         tmplongpath[lp++] = shortpath[tmplen];
809     tmplongpath[lp] = 0;
810
811     tmplen = strlen(tmplongpath) + 1;
812     if (tmplen <= longlen)
813     {
814         strcpy(longpath, tmplongpath);
815         tmplen--; /* length without 0 */
816     }
817
818     return tmplen;
819 }
820
821 /***
822  *
823  * Tests
824  *
825  ***/
826
827 static const char* testfiles[]=
828 {
829     "%s\\test file.shlexec",
830     "%s\\%%nasty%% $file.shlexec",
831     "%s\\test file.noassoc",
832     "%s\\test file.noassoc.shlexec",
833     "%s\\test file.shlexec.noassoc",
834     "%s\\test_shortcut_shlexec.lnk",
835     "%s\\test_shortcut_exe.lnk",
836     "%s\\test file.shl",
837     "%s\\test file.shlfoo",
838     "%s\\test file.sfe",
839     "%s\\masked file.shlexec",
840     "%s\\masked",
841     "%s\\test file.sde",
842     "%s\\test file.exe",
843     "%s\\test2.exe",
844     "%s\\simple.shlexec",
845     "%s\\drawback_file.noassoc",
846     "%s\\drawback_file.noassoc foo.shlexec",
847     "%s\\drawback_nonexist.noassoc foo.shlexec",
848     NULL
849 };
850
851 typedef struct
852 {
853     const char* verb;
854     const char* basename;
855     int todo;
856     INT_PTR rc;
857 } filename_tests_t;
858
859 static filename_tests_t filename_tests[]=
860 {
861     /* Test bad / nonexistent filenames */
862     {NULL,           "%s\\nonexistent.shlexec", 0x0, SE_ERR_FNF},
863     {NULL,           "%s\\nonexistent.noassoc", 0x0, SE_ERR_FNF},
864
865     /* Standard tests */
866     {NULL,           "%s\\test file.shlexec",   0x0, 33},
867     {NULL,           "%s\\test file.shlexec.",  0x0, 33},
868     {NULL,           "%s\\%%nasty%% $file.shlexec", 0x0, 33},
869     {NULL,           "%s/test file.shlexec",    0x0, 33},
870
871     /* Test filenames with no association */
872     {NULL,           "%s\\test file.noassoc",   0x0,  SE_ERR_NOASSOC},
873
874     /* Test double extensions */
875     {NULL,           "%s\\test file.noassoc.shlexec", 0x0, 33},
876     {NULL,           "%s\\test file.shlexec.noassoc", 0x0, SE_ERR_NOASSOC},
877
878     /* Test alternate verbs */
879     {"LowerL",       "%s\\nonexistent.shlexec", 0x0, SE_ERR_FNF},
880     {"LowerL",       "%s\\test file.noassoc",   0x0,  SE_ERR_NOASSOC},
881
882     {"QuotedLowerL", "%s\\test file.shlexec",   0x0, 33},
883     {"QuotedUpperL", "%s\\test file.shlexec",   0x0, 33},
884
885     /* Test file masked due to space */
886     {NULL,           "%s\\masked file.shlexec",   0x1, 33},
887     /* Test if quoting prevents the masking */
888     {NULL,           "%s\\masked file.shlexec",   0x40, 33},
889
890     {NULL, NULL, 0}
891 };
892
893 static filename_tests_t noquotes_tests[]=
894 {
895     /* Test unquoted '%1' thingies */
896     {"NoQuotes",     "%s\\test file.shlexec",   0xa, 33},
897     {"LowerL",       "%s\\test file.shlexec",   0xa, 33},
898     {"UpperL",       "%s\\test file.shlexec",   0xa, 33},
899
900     {NULL, NULL, 0}
901 };
902
903 static void test_lpFile_parsed(void)
904 {
905     char fileA[MAX_PATH];
906     INT_PTR rc;
907
908     /* existing "drawback_file.noassoc" prevents finding "drawback_file.noassoc foo.shlexec" on wine */
909     sprintf(fileA, "%s\\drawback_file.noassoc foo.shlexec", tmpdir);
910     rc=shell_execute(NULL, fileA, NULL, NULL);
911     todo_wine ok(rc > 32, "%s failed: rc=%lu\n", shell_call, rc);
912
913     /* if quoted, existing "drawback_file.noassoc" not prevents finding "drawback_file.noassoc foo.shlexec" on wine */
914     sprintf(fileA, "\"%s\\drawback_file.noassoc foo.shlexec\"", tmpdir);
915     rc=shell_execute(NULL, fileA, NULL, NULL);
916     ok(rc > 32 || broken(rc == SE_ERR_FNF) /* Win95/NT4 */,
917        "%s failed: rc=%lu\n", shell_call, rc);
918
919     /* error should be SE_ERR_FNF, not SE_ERR_NOASSOC */
920     sprintf(fileA, "\"%s\\drawback_file.noassoc\" foo.shlexec", tmpdir);
921     rc=shell_execute(NULL, fileA, NULL, NULL);
922     ok(rc == SE_ERR_FNF, "%s succeeded: rc=%lu\n", shell_call, rc);
923
924     /* ""command"" not works on wine (and real win9x and w2k) */
925     sprintf(fileA, "\"\"%s\\simple.shlexec\"\"", tmpdir);
926     rc=shell_execute(NULL, fileA, NULL, NULL);
927     todo_wine ok(rc > 32 || broken(rc == SE_ERR_FNF) /* Win9x/2000 */,
928                  "%s failed: rc=%lu\n", shell_call, rc);
929
930     /* nonexisting "drawback_nonexist.noassoc" not prevents finding "drawback_nonexist.noassoc foo.shlexec" on wine */
931     sprintf(fileA, "%s\\drawback_nonexist.noassoc foo.shlexec", tmpdir);
932     rc=shell_execute(NULL, fileA, NULL, NULL);
933     ok(rc > 32, "%s failed: rc=%lu\n", shell_call, rc);
934
935     /* is SEE_MASK_DOENVSUBST default flag? Should only be when XP emulates 9x (XP bug or real 95 or ME behavior ?) */
936     rc=shell_execute(NULL, "%TMPDIR%\\simple.shlexec", NULL, NULL);
937     todo_wine ok(rc == SE_ERR_FNF, "%s succeeded: rc=%lu\n", shell_call, rc);
938
939     /* quoted */
940     rc=shell_execute(NULL, "\"%TMPDIR%\\simple.shlexec\"", NULL, NULL);
941     todo_wine ok(rc == SE_ERR_FNF, "%s succeeded: rc=%lu\n", shell_call, rc);
942
943     /* test SEE_MASK_DOENVSUBST works */
944     rc=shell_execute_ex(SEE_MASK_DOENVSUBST | SEE_MASK_FLAG_NO_UI,
945                         NULL, "%TMPDIR%\\simple.shlexec", NULL, NULL, NULL);
946     ok(rc > 32, "%s failed: rc=%lu\n", shell_call, rc);
947
948     /* quoted lpFile does not work on real win95 and nt4 */
949     rc=shell_execute_ex(SEE_MASK_DOENVSUBST | SEE_MASK_FLAG_NO_UI,
950                         NULL, "\"%TMPDIR%\\simple.shlexec\"", NULL, NULL, NULL);
951     ok(rc > 32 || broken(rc == SE_ERR_FNF) /* Win95/NT4 */,
952        "%s failed: rc=%lu\n", shell_call, rc);
953 }
954
955 typedef struct
956 {
957     const char* cmd;
958     const char* args[11];
959     int todo;
960 } cmdline_tests_t;
961
962 static const cmdline_tests_t cmdline_tests[] =
963 {
964     {"exe",
965      {"exe", NULL}, 0},
966
967     {"exe arg1 arg2 \"arg three\" 'four five` six\\ $even)",
968      {"exe", "arg1", "arg2", "arg three", "'four", "five`", "six\\", "$even)", NULL}, 0},
969
970     {"exe arg=1 arg-2 three\tfour\rfour\nfour ",
971      {"exe", "arg=1", "arg-2", "three", "four\rfour\nfour", NULL}, 0},
972
973     {"exe arg\"one\" \"second\"arg thirdarg ",
974      {"exe", "argone", "secondarg", "thirdarg", NULL}, 0},
975
976     /* Don't lose unclosed quoted arguments */
977     {"exe arg1 \"unclosed",
978      {"exe", "arg1", "unclosed", NULL}, 0},
979
980     {"exe arg1 \"",
981      {"exe", "arg1", "", NULL}, 0},
982
983     /* cmd's metacharacters have no special meaning */
984     {"exe \"one^\" \"arg\"&two three|four",
985      {"exe", "one^", "arg&two", "three|four", NULL}, 0},
986
987     /* Environment variables are not interpreted either */
988     {"exe %TMPDIR% %2",
989      {"exe", "%TMPDIR%", "%2", NULL}, 0},
990
991     /* If not followed by a quote, backslashes go through as is */
992     {"exe o\\ne t\\\\wo t\\\\\\ree f\\\\\\\\our ",
993      {"exe", "o\\ne", "t\\\\wo", "t\\\\\\ree", "f\\\\\\\\our", NULL}, 0},
994
995     {"exe \"o\\ne\" \"t\\\\wo\" \"t\\\\\\ree\" \"f\\\\\\\\our\" ",
996      {"exe", "o\\ne", "t\\\\wo", "t\\\\\\ree", "f\\\\\\\\our", NULL}, 0},
997
998     /* When followed by a quote their number is halved and the remainder
999      * escapes the quote
1000      */
1001     {"exe \\\"one \\\\\"two\" \\\\\\\"three \\\\\\\\\"four\" end",
1002      {"exe", "\"one", "\\two", "\\\"three", "\\\\four", "end", NULL}, 0},
1003
1004     {"exe \"one\\\" still\" \"two\\\\\" \"three\\\\\\\" still\" \"four\\\\\\\\\" end",
1005      {"exe", "one\" still", "two\\", "three\\\" still", "four\\\\", "end", NULL}, 0},
1006
1007     /* One can put a quote in an unquoted string by tripling it, that is in
1008      * effect quoting it like so """ -> ". The general rule is as follows:
1009      * 3n   quotes -> n quotes
1010      * 3n+1 quotes -> n quotes plus start of a quoted string
1011      * 3n+2 quotes -> n quotes (plus an empty string from the remaining pair)
1012      * Nicely, when n is 0 we get the standard rules back.
1013      */
1014     {"exe two\"\"quotes next",
1015      {"exe", "twoquotes", "next", NULL}, 0},
1016
1017     {"exe three\"\"\"quotes next",
1018      {"exe", "three\"quotes", "next", NULL}, 0},
1019
1020     {"exe four\"\"\"\" quotes\" next 4%3=1",
1021      {"exe", "four\" quotes", "next", "4%3=1", NULL}, 0},
1022
1023     {"exe five\"\"\"\"\"quotes next",
1024      {"exe", "five\"quotes", "next", NULL}, 0},
1025
1026     {"exe six\"\"\"\"\"\"quotes next",
1027      {"exe", "six\"\"quotes", "next", NULL}, 0},
1028
1029     {"exe seven\"\"\"\"\"\"\" quotes\" next 7%3=1",
1030      {"exe", "seven\"\" quotes", "next", "7%3=1", NULL}, 0},
1031
1032     {"exe twelve\"\"\"\"\"\"\"\"\"\"\"\"quotes next",
1033      {"exe", "twelve\"\"\"\"quotes", "next", NULL}, 0},
1034
1035     {"exe thirteen\"\"\"\"\"\"\"\"\"\"\"\"\" quotes\" next 13%3=1",
1036      {"exe", "thirteen\"\"\"\" quotes", "next", "13%3=1", NULL}, 0},
1037
1038     /* Inside a quoted string the opening quote is added to the set of
1039      * consecutive quotes to get the effective quotes count. This gives:
1040      * 1+3n   quotes -> n quotes
1041      * 1+3n+1 quotes -> n quotes plus closes the quoted string
1042      * 1+3n+2 quotes -> n+1 quotes plus closes the quoted string
1043      */
1044     {"exe \"two\"\"quotes next",
1045      {"exe", "two\"quotes", "next", NULL}, 0},
1046
1047     {"exe \"two\"\" next",
1048      {"exe", "two\"", "next", NULL}, 0},
1049
1050     {"exe \"three\"\"\" quotes\" next 4%3=1",
1051      {"exe", "three\" quotes", "next", "4%3=1", NULL}, 0},
1052
1053     {"exe \"four\"\"\"\"quotes next",
1054      {"exe", "four\"quotes", "next", NULL}, 0},
1055
1056     {"exe \"five\"\"\"\"\"quotes next",
1057      {"exe", "five\"\"quotes", "next", NULL}, 0},
1058
1059     {"exe \"six\"\"\"\"\"\" quotes\" next 7%3=1",
1060      {"exe", "six\"\" quotes", "next", "7%3=1", NULL}, 0},
1061
1062     {"exe \"eleven\"\"\"\"\"\"\"\"\"\"\"quotes next",
1063      {"exe", "eleven\"\"\"\"quotes", "next", NULL}, 0},
1064
1065     {"exe \"twelve\"\"\"\"\"\"\"\"\"\"\"\" quotes\" next 13%3=1",
1066      {"exe", "twelve\"\"\"\" quotes", "next", "13%3=1", NULL}, 0},
1067
1068     /* Escaped consecutive quotes are fun */
1069     {"exe \"the crazy \\\\\"\"\"\\\\\" quotes",
1070      {"exe", "the crazy \\\"\\", "quotes", NULL}, 0},
1071
1072     /* The executable path has its own rules!!!
1073      * - Backslashes have no special meaning.
1074      * - If the first character is a quote, then the second quote ends the
1075      *   executable path.
1076      * - The previous rule holds even if the next character is not a space!
1077      * - If the first character is not a quote, then quotes have no special
1078      *   meaning either and the executable path stops at the first space.
1079      * - The consecutive quotes rules don't apply either.
1080      * - Even if there is no space between the executable path and the first
1081      *   argument, the latter is parsed using the regular rules.
1082      */
1083     {"exe\"file\"path arg1",
1084      {"exe\"file\"path", "arg1", NULL}, 0},
1085
1086     {"exe\"file\"path\targ1",
1087      {"exe\"file\"path", "arg1", NULL}, 0},
1088
1089     {"exe\"path\\ arg1",
1090      {"exe\"path\\", "arg1", NULL}, 0},
1091
1092     {"\\\"exe \"arg one\"",
1093      {"\\\"exe", "arg one", NULL}, 0},
1094
1095     {"\"spaced exe\" \"next arg\"",
1096      {"spaced exe", "next arg", NULL}, 0},
1097
1098     {"\"spaced exe\"\t\"next arg\"",
1099      {"spaced exe", "next arg", NULL}, 0},
1100
1101     {"\"exe\"arg\" one\" argtwo",
1102      {"exe", "arg one", "argtwo", NULL}, 0},
1103
1104     {"\"spaced exe\\\"arg1 arg2",
1105      {"spaced exe\\", "arg1", "arg2", NULL}, 0},
1106
1107     {"\"two\"\" arg1 ",
1108      {"two", " arg1 ", NULL}, 0},
1109
1110     {"\"three\"\"\" arg2",
1111      {"three", "", "arg2", NULL}, 0},
1112
1113     {"\"four\"\"\"\"arg1",
1114      {"four", "\"arg1", NULL}, 0},
1115
1116     /* If the first character is a space then the executable path is empty */
1117     {" \"arg\"one argtwo",
1118      {"", "argone", "argtwo", NULL}, 0},
1119
1120     {NULL, {NULL}, 0}
1121 };
1122
1123 static BOOL test_one_cmdline(const cmdline_tests_t* test)
1124 {
1125     WCHAR cmdW[MAX_PATH], argW[MAX_PATH];
1126     LPWSTR *cl2a;
1127     int cl2a_count;
1128     LPWSTR *argsW;
1129     int i, count;
1130
1131     /* trace("----- cmd='%s'\n", test->cmd); */
1132     MultiByteToWideChar(CP_ACP, 0, test->cmd, -1, cmdW, sizeof(cmdW)/sizeof(*cmdW));
1133     argsW = cl2a = CommandLineToArgvW(cmdW, &cl2a_count);
1134     if (argsW == NULL && cl2a_count == -1)
1135     {
1136         win_skip("CommandLineToArgvW not implemented, skipping\n");
1137         return FALSE;
1138     }
1139
1140     count = 0;
1141     while (test->args[count])
1142         count++;
1143     if ((test->todo & 0x1) == 0)
1144         ok(cl2a_count == count, "%s: expected %d arguments, but got %d\n", test->cmd, count, cl2a_count);
1145     else todo_wine
1146         ok(cl2a_count == count, "%s: expected %d arguments, but got %d\n", test->cmd, count, cl2a_count);
1147
1148     for (i = 0; i < cl2a_count; i++)
1149     {
1150         if (i < count)
1151         {
1152             MultiByteToWideChar(CP_ACP, 0, test->args[i], -1, argW, sizeof(argW)/sizeof(*argW));
1153             if ((test->todo & (1 << (i+4))) == 0)
1154                 ok(!lstrcmpW(*argsW, argW), "%s: arg[%d] expected %s but got %s\n", test->cmd, i, wine_dbgstr_w(argW), wine_dbgstr_w(*argsW));
1155             else todo_wine
1156                 ok(!lstrcmpW(*argsW, argW), "%s: arg[%d] expected %s but got %s\n", test->cmd, i, wine_dbgstr_w(argW), wine_dbgstr_w(*argsW));
1157         }
1158         else if ((test->todo & 0x1) == 0)
1159             ok(0, "%s: got extra arg[%d]=%s\n", test->cmd, i, wine_dbgstr_w(*argsW));
1160         else todo_wine
1161             ok(0, "%s: got extra arg[%d]=%s\n", test->cmd, i, wine_dbgstr_w(*argsW));
1162         argsW++;
1163     }
1164     LocalFree(cl2a);
1165     return TRUE;
1166 }
1167
1168 static void test_commandline2argv(void)
1169 {
1170     static const WCHAR exeW[] = {'e','x','e',0};
1171     const cmdline_tests_t* test;
1172     WCHAR strW[MAX_PATH];
1173     LPWSTR *args;
1174     int numargs;
1175     DWORD le;
1176
1177     test = cmdline_tests;
1178     while (test->cmd)
1179     {
1180         if (!test_one_cmdline(test))
1181             return;
1182         test++;
1183     }
1184
1185     SetLastError(0xdeadbeef);
1186     args = CommandLineToArgvW(exeW, NULL);
1187     le = GetLastError();
1188     ok(args == NULL && le == ERROR_INVALID_PARAMETER, "expected NULL with ERROR_INVALID_PARAMETER got %p with %u\n", args, le);
1189
1190     SetLastError(0xdeadbeef);
1191     args = CommandLineToArgvW(NULL, NULL);
1192     le = GetLastError();
1193     ok(args == NULL && le == ERROR_INVALID_PARAMETER, "expected NULL with ERROR_INVALID_PARAMETER got %p with %u\n", args, le);
1194
1195     *strW = 0;
1196     args = CommandLineToArgvW(strW, &numargs);
1197     ok(numargs == 1, "expected 1 args, got %d\n", numargs);
1198     if (numargs == 1)
1199     {
1200         GetModuleFileNameW(NULL, strW, sizeof(strW)/sizeof(*strW));
1201         ok(!lstrcmpW(args[0], strW), "wrong path to the current executable: %s instead of %s\n", wine_dbgstr_w(args[0]), wine_dbgstr_w(strW));
1202     }
1203     if (args) LocalFree(args);
1204 }
1205
1206 /* The goal here is to analyze how ShellExecute() builds the command that
1207  * will be run. The tricky part is that there are three transformation
1208  * steps between the 'parameters' string we pass to ShellExecute() and the
1209  * argument list we observe in the child process:
1210  * - The parsing of 'parameters' string into individual arguments. The tests
1211  *   show this is done differently from both CreateProcess() and
1212  *   CommandLineToArgv()!
1213  * - The way the command 'formatting directives' such as %1, %2, etc are
1214  *   handled.
1215  * - And the way the resulting command line is then parsed to yield the
1216  *   argument list we check.
1217  */
1218 typedef struct
1219 {
1220     const char* verb;
1221     const char* params;
1222     int todo;
1223     cmdline_tests_t cmd;
1224     cmdline_tests_t broken;
1225 } argify_tests_t;
1226
1227 static const argify_tests_t argify_tests[] =
1228 {
1229     /* Start with three simple parameters. Notice that one can reorder and
1230      * duplicate the parameters. Also notice how %* take the raw input
1231      * parameters string, including the trailing spaces, no matter what
1232      * arguments have already been used.
1233      */
1234     {"Params232S", "p2 p3 p4 ", 0xc2,
1235      {" p2 p3 \"p2\" \"p2 p3 p4 \"",
1236       {"", "p2", "p3", "p2", "p2 p3 p4 ", NULL}, 0}},
1237
1238     /* Unquoted argument references like %2 don't automatically quote their
1239      * argument. Similarly, when they are quoted they don't escape the quotes
1240      * that their argument may contain.
1241      */
1242     {"Params232S", "\"p two\" p3 p4  ", 0x3f3,
1243      {" p two p3 \"p two\" \"\"p two\" p3 p4  \"",
1244       {"", "p", "two", "p3", "p two", "p", "two p3 p4  ", NULL}, 0}},
1245
1246     /* Only single digits are supported so only %1 to %9. Shown here with %20
1247      * because %10 is a pain.
1248      */
1249     {"Params20", "p", 0,
1250      {" \"p0\"",
1251       {"", "p0", NULL}, 0}},
1252
1253     /* Only (double-)quotes have a special meaning. */
1254     {"Params23456", "'p2 p3` p4\\ $even", 0x40,
1255      {" \"'p2\" \"p3`\" \"p4\\\" \"$even\" \"\"",
1256       {"", "'p2", "p3`", "p4\" $even \"", NULL}, 0}},
1257
1258     {"Params23456", "p=2 p-3 p4\tp4\rp4\np4", 0x1c2,
1259      {" \"p=2\" \"p-3\" \"p4\tp4\rp4\np4\" \"\" \"\"",
1260       {"", "p=2", "p-3", "p4\tp4\rp4\np4", "", "", NULL}, 0}},
1261
1262     /* In unquoted strings, quotes are treated are a parameter separator just
1263      * like spaces! However they can be doubled to get a literal quote.
1264      * Specifically:
1265      * 2n   quotes -> n quotes
1266      * 2n+1 quotes -> n quotes and a parameter separator
1267      */
1268     {"Params23456789", "one\"quote \"p four\" one\"quote p7", 0xff3,
1269      {" \"one\" \"quote\" \"p four\" \"one\" \"quote\" \"p7\" \"\" \"\"",
1270       {"", "one", "quote", "p four", "one", "quote", "p7", "", "", NULL}, 0}},
1271
1272     {"Params23456789", "two\"\"quotes \"p three\" two\"\"quotes p5", 0xf2,
1273      {" \"two\"quotes\" \"p three\" \"two\"quotes\" \"p5\" \"\" \"\" \"\" \"\"",
1274       {"", "twoquotes p", "three twoquotes", "p5", "", "", "", "", NULL}, 0}},
1275
1276     {"Params23456789", "three\"\"\"quotes \"p four\" three\"\"\"quotes p6", 0xff3,
1277      {" \"three\"\" \"quotes\" \"p four\" \"three\"\" \"quotes\" \"p6\" \"\" \"\"",
1278       {"", "three\"", "quotes", "p four", "three\"", "quotes", "p6", "", "", NULL}, 0}},
1279
1280     {"Params23456789", "four\"\"\"\"quotes \"p three\" four\"\"\"\"quotes p5", 0xf3,
1281      {" \"four\"\"quotes\" \"p three\" \"four\"\"quotes\" \"p5\" \"\" \"\" \"\" \"\"",
1282       {"", "four\"quotes p", "three fourquotes p5 \"", "", "", "", NULL}, 0}},
1283
1284     /* Quoted strings cannot be continued by tacking on a non space character
1285      * either.
1286      */
1287     {"Params23456", "\"p two\"p3 \"p four\"p5 p6", 0x1f3,
1288      {" \"p two\" \"p3\" \"p four\" \"p5\" \"p6\"",
1289       {"", "p two", "p3", "p four", "p5", "p6", NULL}, 0}},
1290
1291     /* In quoted strings, the quotes are halved and an odd number closes the
1292      * string. Specifically:
1293      * 2n   quotes -> n quotes
1294      * 2n+1 quotes -> n quotes and closes the string and hence the parameter
1295      */
1296     {"Params23456789", "\"one q\"uote \"p four\" \"one q\"uote p7", 0xff3,
1297      {" \"one q\" \"uote\" \"p four\" \"one q\" \"uote\" \"p7\" \"\" \"\"",
1298       {"", "one q", "uote", "p four", "one q", "uote", "p7", "", "", NULL}, 0}},
1299
1300     {"Params23456789", "\"two \"\" quotes\" \"p three\" \"two \"\" quotes\" p5", 0x1ff3,
1301      {" \"two \" quotes\" \"p three\" \"two \" quotes\" \"p5\" \"\" \"\" \"\" \"\"",
1302       {"", "two ", "quotes p", "three two", " quotes", "p5", "", "", "", "", NULL}, 0}},
1303
1304     {"Params23456789", "\"three q\"\"\"uotes \"p four\" \"three q\"\"\"uotes p7", 0xff3,
1305      {" \"three q\"\" \"uotes\" \"p four\" \"three q\"\" \"uotes\" \"p7\" \"\" \"\"",
1306       {"", "three q\"", "uotes", "p four", "three q\"", "uotes", "p7", "", "", NULL}, 0}},
1307
1308     {"Params23456789", "\"four \"\"\"\" quotes\" \"p three\" \"four \"\"\"\" quotes\" p5", 0xff3,
1309      {" \"four \"\" quotes\" \"p three\" \"four \"\" quotes\" \"p5\" \"\" \"\" \"\" \"\"",
1310       {"", "four \"", "quotes p", "three four", "", "quotes p5 \"", "", "", "", NULL}, 0}},
1311
1312     /* The quoted string rules also apply to consecutive quotes at the start
1313      * of a parameter but don't count the opening quote!
1314      */
1315     {"Params23456789", "\"\"twoquotes \"p four\" \"\"twoquotes p7", 0xbf3,
1316      {" \"\" \"twoquotes\" \"p four\" \"\" \"twoquotes\" \"p7\" \"\" \"\"",
1317       {"", "", "twoquotes", "p four", "", "twoquotes", "p7", "", "", NULL}, 0}},
1318
1319     {"Params23456789", "\"\"\"three quotes\" \"p three\" \"\"\"three quotes\" p5", 0x6f3,
1320      {" \"\"three quotes\" \"p three\" \"\"three quotes\" \"p5\" \"\" \"\" \"\" \"\"",
1321       {"", "three", "quotes p", "three \"three", "quotes p5 \"", "", "", "", NULL}, 0}},
1322
1323     {"Params23456789", "\"\"\"\"fourquotes \"p four\" \"\"\"\"fourquotes p7", 0xbf3,
1324      {" \"\"\" \"fourquotes\" \"p four\" \"\"\" \"fourquotes\" \"p7\" \"\" \"\"",
1325       {"", "\"", "fourquotes", "p four", "\"", "fourquotes", "p7", "", "", NULL}, 0}},
1326
1327     /* An unclosed quoted string gets lost! */
1328     {"Params23456", "p2 \"p3\" \"p4 is lost", 0x1c3,
1329      {" \"p2\" \"p3\" \"\" \"\" \"\"",
1330       {"", "p2", "p3", "", "", "", NULL}, 0},
1331      {" \"p2\" \"p3\" \"p3\" \"\" \"\"",
1332        {"", "p2", "p3", "p3", "", "", NULL}, 0}},
1333
1334     /* Backslashes have no special meaning even when preceding quotes. All
1335      * they do is start an unquoted string.
1336      */
1337     {"Params23456", "\\\"p\\three \"pfour\\\" pfive", 0x73,
1338      {" \"\\\" \"p\\three\" \"pfour\\\" \"pfive\" \"\"",
1339       {"", "\" p\\three pfour\"", "pfive", "", NULL}, 0}},
1340
1341     /* Environment variables are left untouched. */
1342     {"Params23456", "%TMPDIR% %t %c", 0,
1343      {" \"%TMPDIR%\" \"%t\" \"%c\" \"\" \"\"",
1344       {"", "%TMPDIR%", "%t", "%c", "", "", NULL}, 0}},
1345
1346     /* %~2 is equivalent to %*. However %~3 and higher include the spaces
1347      * before the parameter!
1348      * (but not the previous parameter's closing quote fortunately)
1349      */
1350     {"Params2345Etc", "p2  p3 \"p4\"  p5 p6 ", 0x3f3,
1351      {" ~2=\"p2  p3 \"p4\"  p5 p6 \" ~3=\"  p3 \"p4\"  p5 p6 \" ~4=\" \"p4\"  p5 p6 \" ~5=  p5 p6 ",
1352       {"", "~2=p2  p3 p4  p5 p6 ", "~3=  p3 p4  p5 p6 ", "~4= p4  p5 p6 ", "~5=", "p5", "p6", NULL}, 0}},
1353
1354     /* %~n works even if there is no nth parameter. */
1355     {"Params9Etc", "p2 p3 p4 p5 p6 p7 p8   ", 0x12,
1356      {" ~9=\"   \"",
1357       {"", "~9=   ", NULL}, 0}},
1358
1359     {"Params9Etc", "p2 p3 p4 p5 p6 p7   ", 0x12,
1360      {" ~9=\"\"",
1361       {"", "~9=", NULL}, 0}},
1362
1363     /* The %~n directives also transmit the tenth parameter and beyond. */
1364     {"Params9Etc", "p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 and beyond!", 0x12,
1365      {" ~9=\" p9 p10 p11 and beyond!\"",
1366       {"", "~9= p9 p10 p11 and beyond!", NULL}, 0}},
1367
1368     /* Bad formatting directives lose their % sign, except those followed by
1369      * a tilde! Environment variables are not expanded but lose their % sign.
1370      */
1371     {"ParamsBad", "p2 p3 p4 p5", 0x12,
1372      {" \"% - %~ %~0 %~1 %~a %~* a b c TMPDIR\"",
1373       {"", "% - %~ %~0 %~1 %~a %~* a b c TMPDIR", NULL}, 0}},
1374
1375     {NULL, NULL, 0, {NULL, {NULL}, 0}}
1376 };
1377
1378 static void test_argify(void)
1379 {
1380     BOOL has_cl2a = TRUE;
1381     char fileA[MAX_PATH], params[2*MAX_PATH+12];
1382     INT_PTR rc;
1383     const argify_tests_t* test;
1384     const cmdline_tests_t *bad;
1385     const char* cmd;
1386     unsigned i, count;
1387
1388     create_test_verb(".shlexec", "Params232S", 0, "Params232S %2 %3 \"%2\" \"%*\"");
1389     create_test_verb(".shlexec", "Params23456", 0, "Params23456 \"%2\" \"%3\" \"%4\" \"%5\" \"%6\"");
1390     create_test_verb(".shlexec", "Params23456789", 0, "Params23456789 \"%2\" \"%3\" \"%4\" \"%5\" \"%6\" \"%7\" \"%8\" \"%9\"");
1391     create_test_verb(".shlexec", "Params2345Etc", 0, "Params2345Etc ~2=\"%~2\" ~3=\"%~3\" ~4=\"%~4\" ~5=%~5");
1392     create_test_verb(".shlexec", "Params9Etc", 0, "Params9Etc ~9=\"%~9\"");
1393     create_test_verb(".shlexec", "Params20", 0, "Params20 \"%20\"");
1394     create_test_verb(".shlexec", "ParamsBad", 0, "ParamsBad \"%% %- %~ %~0 %~1 %~a %~* %a %b %c %TMPDIR%\"");
1395
1396     sprintf(fileA, "%s\\test file.shlexec", tmpdir);
1397
1398     test = argify_tests;
1399     while (test->params)
1400     {
1401         bad = test->broken.cmd ? &test->broken : &test->cmd;
1402
1403         /* trace("***** verb='%s' params='%s'\n", test->verb, test->params); */
1404         rc = shell_execute_ex(SEE_MASK_DOENVSUBST, test->verb, fileA, test->params, NULL, NULL);
1405         ok(rc > 32, "%s failed: rc=%lu\n", shell_call, rc);
1406
1407         count = 0;
1408         while (test->cmd.args[count])
1409             count++;
1410         if ((test->todo & 0x1) == 0)
1411             /* +4 for the shlexec arguments, -1 because of the added ""
1412              * argument for the CommandLineToArgvW() tests.
1413              */
1414             okChildInt("argcA", 4 + count - 1);
1415         else todo_wine
1416             okChildInt("argcA", 4 + count - 1);
1417
1418         cmd = getChildString("Arguments", "cmdlineA");
1419         /* Our commands are such that the verb immediately precedes the
1420          * part we are interested in.
1421          */
1422         if (cmd) cmd = strstr(cmd, test->verb);
1423         if (cmd) cmd += strlen(test->verb);
1424         if (!cmd) cmd = "(null)";
1425         if ((test->todo & 0x2) == 0)
1426             ok(!strcmp(cmd, test->cmd.cmd) || broken(!strcmp(cmd, bad->cmd)),
1427                "%s: the cmdline is '%s' instead of '%s'\n", shell_call, cmd, test->cmd.cmd);
1428         else todo_wine
1429             ok(!strcmp(cmd, test->cmd.cmd) || broken(!strcmp(cmd, bad->cmd)),
1430                "%s: the cmdline is '%s' instead of '%s'\n", shell_call, cmd, test->cmd.cmd);
1431
1432         for (i = 0; i < count - 1; i++)
1433         {
1434             char argname[18];
1435             sprintf(argname, "argvA%d", 4 + i);
1436             if ((test->todo & (1 << (i+4))) == 0)
1437                 okChildStringBroken(argname, test->cmd.args[i+1], bad->args[i+1]);
1438             else todo_wine
1439                 okChildStringBroken(argname, test->cmd.args[i+1], bad->args[i+1]);
1440         }
1441
1442         if (has_cl2a)
1443             has_cl2a = test_one_cmdline(&(test->cmd));
1444         test++;
1445     }
1446
1447     /* Test with a long parameter */
1448     for (rc = 0; rc < MAX_PATH; rc++)
1449         fileA[rc] = 'a' + rc % 26;
1450     fileA[MAX_PATH-1] = '\0';
1451     sprintf(params, "shlexec \"%s\" %s", child_file, fileA);
1452
1453     /* We need NOZONECHECKS on Win2003 to block a dialog */
1454     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, argv0, params, NULL, NULL);
1455     ok(rc > 32, "%s failed: rc=%lu\n", shell_call, rc);
1456     okChildInt("argcA", 4);
1457     okChildString("argvA3", fileA);
1458 }
1459
1460 static void test_filename(void)
1461 {
1462     char filename[MAX_PATH];
1463     const filename_tests_t* test;
1464     char* c;
1465     INT_PTR rc;
1466
1467     test=filename_tests;
1468     while (test->basename)
1469     {
1470         BOOL quotedfile = FALSE;
1471
1472         if (skip_noassoc_tests && test->rc == SE_ERR_NOASSOC)
1473         {
1474             win_skip("Skipping shellexecute of file with unassociated extension\n");
1475             test++;
1476             continue;
1477         }
1478
1479         sprintf(filename, test->basename, tmpdir);
1480         if (strchr(filename, '/'))
1481         {
1482             c=filename;
1483             while (*c)
1484             {
1485                 if (*c=='\\')
1486                     *c='/';
1487                 c++;
1488             }
1489         }
1490         if ((test->todo & 0x40)==0)
1491         {
1492             rc=shell_execute(test->verb, filename, NULL, NULL);
1493         }
1494         else
1495         {
1496             char quoted[MAX_PATH + 2];
1497
1498             quotedfile = TRUE;
1499             sprintf(quoted, "\"%s\"", filename);
1500             rc=shell_execute(test->verb, quoted, NULL, NULL);
1501         }
1502         if (rc > 32)
1503             rc=33;
1504         if ((test->todo & 0x1)==0)
1505         {
1506             ok(rc==test->rc ||
1507                broken(quotedfile && rc == SE_ERR_FNF), /* NT4 */
1508                "%s failed: rc=%ld err=%u\n", shell_call,
1509                rc, GetLastError());
1510         }
1511         else todo_wine
1512         {
1513             ok(rc==test->rc, "%s failed: rc=%ld err=%u\n", shell_call,
1514                rc, GetLastError());
1515         }
1516         if (rc == 33)
1517         {
1518             const char* verb;
1519             if ((test->todo & 0x2)==0)
1520             {
1521                 okChildInt("argcA", 5);
1522             }
1523             else todo_wine
1524             {
1525                 okChildInt("argcA", 5);
1526             }
1527             verb=(test->verb ? test->verb : "Open");
1528             if ((test->todo & 0x4)==0)
1529             {
1530                 okChildString("argvA3", verb);
1531             }
1532             else todo_wine
1533             {
1534                 okChildString("argvA3", verb);
1535             }
1536             if ((test->todo & 0x8)==0)
1537             {
1538                 okChildPath("argvA4", filename);
1539             }
1540             else todo_wine
1541             {
1542                 okChildPath("argvA4", filename);
1543             }
1544         }
1545         test++;
1546     }
1547
1548     test=noquotes_tests;
1549     while (test->basename)
1550     {
1551         sprintf(filename, test->basename, tmpdir);
1552         rc=shell_execute(test->verb, filename, NULL, NULL);
1553         if (rc > 32)
1554             rc=33;
1555         if ((test->todo & 0x1)==0)
1556         {
1557             ok(rc==test->rc, "%s failed: rc=%ld err=%u\n", shell_call,
1558                rc, GetLastError());
1559         }
1560         else todo_wine
1561         {
1562             ok(rc==test->rc, "%s failed: rc=%ld err=%u\n", shell_call,
1563                rc, GetLastError());
1564         }
1565         if (rc==0)
1566         {
1567             int count;
1568             const char* verb;
1569             char* str;
1570
1571             verb=(test->verb ? test->verb : "Open");
1572             if ((test->todo & 0x4)==0)
1573             {
1574                 okChildString("argvA3", verb);
1575             }
1576             else todo_wine
1577             {
1578                 okChildString("argvA3", verb);
1579             }
1580
1581             count=4;
1582             str=filename;
1583             while (1)
1584             {
1585                 char attrib[18];
1586                 char* space;
1587                 space=strchr(str, ' ');
1588                 if (space)
1589                     *space='\0';
1590                 sprintf(attrib, "argvA%d", count);
1591                 if ((test->todo & 0x8)==0)
1592                 {
1593                     okChildPath(attrib, str);
1594                 }
1595                 else todo_wine
1596                 {
1597                     okChildPath(attrib, str);
1598                 }
1599                 count++;
1600                 if (!space)
1601                     break;
1602                 str=space+1;
1603             }
1604             if ((test->todo & 0x2)==0)
1605             {
1606                 okChildInt("argcA", count);
1607             }
1608             else todo_wine
1609             {
1610                 okChildInt("argcA", count);
1611             }
1612         }
1613         test++;
1614     }
1615
1616     if (dllver.dwMajorVersion != 0)
1617     {
1618         /* The more recent versions of shell32.dll accept quoted filenames
1619          * while older ones (e.g. 4.00) don't. Still we want to test this
1620          * because IE 6 depends on the new behavior.
1621          * One day we may need to check the exact version of the dll but for
1622          * now making sure DllGetVersion() is present is sufficient.
1623          */
1624         sprintf(filename, "\"%s\\test file.shlexec\"", tmpdir);
1625         rc=shell_execute(NULL, filename, NULL, NULL);
1626         ok(rc > 32, "%s failed: rc=%ld err=%u\n", shell_call, rc,
1627            GetLastError());
1628         okChildInt("argcA", 5);
1629         okChildString("argvA3", "Open");
1630         sprintf(filename, "%s\\test file.shlexec", tmpdir);
1631         okChildPath("argvA4", filename);
1632     }
1633 }
1634
1635 typedef struct
1636 {
1637     const char* urlprefix;
1638     const char* basename;
1639     int flags;
1640     int todo;
1641 } fileurl_tests_t;
1642
1643 #define URL_SUCCESS  0x1
1644 #define USE_COLON    0x2
1645 #define USE_BSLASH   0x4
1646
1647 static fileurl_tests_t fileurl_tests[]=
1648 {
1649     /* How many slashes does it take... */
1650     {"file:", "%s\\test file.shlexec", URL_SUCCESS, 0},
1651     {"file:/", "%s\\test file.shlexec", URL_SUCCESS, 0},
1652     {"file://", "%s\\test file.shlexec", URL_SUCCESS, 0},
1653     {"file:///", "%s\\test file.shlexec", URL_SUCCESS, 0},
1654     {"File:///", "%s\\test file.shlexec", URL_SUCCESS, 0},
1655     {"file:////", "%s\\test file.shlexec", URL_SUCCESS, 0},
1656     {"file://///", "%s\\test file.shlexec", 0, 0},
1657
1658     /* Test with Windows-style paths */
1659     {"file:///", "%s\\test file.shlexec", URL_SUCCESS | USE_COLON, 0},
1660     {"file:///", "%s\\test file.shlexec", URL_SUCCESS | USE_BSLASH, 0},
1661
1662     /* Check handling of hostnames */
1663     {"file://localhost/", "%s\\test file.shlexec", URL_SUCCESS, 0},
1664     {"file://localhost:80/", "%s\\test file.shlexec", 0, 0},
1665     {"file://LocalHost/", "%s\\test file.shlexec", URL_SUCCESS, 0},
1666     {"file://127.0.0.1/", "%s\\test file.shlexec", 0, 0},
1667     {"file://::1/", "%s\\test file.shlexec", 0, 0},
1668     {"file://notahost/", "%s\\test file.shlexec", 0, 0},
1669
1670     /* Environment variables are not expanded in URLs */
1671     {"%urlprefix%", "%s\\test file.shlexec", 0, 0x1},
1672     {"file:///", "%%TMPDIR%%\\test file.shlexec", 0, 0},
1673
1674     /* Test shortcuts vs. URLs */
1675     {"file://///", "%s\\test_shortcut_shlexec.lnk", 0, 0x1d},
1676
1677     {NULL, NULL, 0, 0}
1678 };
1679
1680 static void test_fileurls(void)
1681 {
1682     char filename[MAX_PATH], fileurl[MAX_PATH], longtmpdir[MAX_PATH];
1683     char command[MAX_PATH];
1684     const fileurl_tests_t* test;
1685     char *s;
1686     INT_PTR rc;
1687
1688     rc = (INT_PTR)ShellExecute(NULL, NULL, "file:///nosuchfile.shlexec", NULL, NULL, SW_SHOWNORMAL);
1689     if (rc > 32)
1690     {
1691         win_skip("shell32 is too old (likely < 4.72). Skipping the file URL tests\n");
1692         return;
1693     }
1694
1695     get_long_path_name(tmpdir, longtmpdir, sizeof(longtmpdir)/sizeof(*longtmpdir));
1696     SetEnvironmentVariable("urlprefix", "file:///");
1697
1698     test=fileurl_tests;
1699     while (test->basename)
1700     {
1701         /* Build the file URL */
1702         sprintf(filename, test->basename, longtmpdir);
1703         strcpy(fileurl, test->urlprefix);
1704         strcat(fileurl, filename);
1705         s = fileurl + strlen(test->urlprefix);
1706         while (*s)
1707         {
1708             if (!(test->flags & USE_COLON) && *s == ':')
1709                 *s = '|';
1710             else if (!(test->flags & USE_BSLASH) && *s == '\\')
1711                 *s = '/';
1712             s++;
1713         }
1714
1715         /* Test it first with FindExecutable() */
1716         rc = (INT_PTR)FindExecutableA(fileurl, NULL, command);
1717         ok(rc == SE_ERR_FNF, "FindExecutable(%s) failed: bad rc=%lu\n", fileurl, rc);
1718
1719         /* Then ShellExecute() */
1720         if ((test->todo & 0x10) == 0)
1721             rc = shell_execute(NULL, fileurl, NULL, NULL);
1722         else todo_wait
1723             rc = shell_execute(NULL, fileurl, NULL, NULL);
1724         if (bad_shellexecute)
1725         {
1726             win_skip("shell32 is too old (likely 4.72). Skipping the file URL tests\n");
1727             break;
1728         }
1729         if (test->flags & URL_SUCCESS)
1730         {
1731             if ((test->todo & 0x1) == 0)
1732                 ok(rc > 32, "%s failed: bad rc=%lu\n", shell_call, rc);
1733             else todo_wine
1734                 ok(rc > 32, "%s failed: bad rc=%lu\n", shell_call, rc);
1735         }
1736         else
1737         {
1738             if ((test->todo & 0x1) == 0)
1739                 ok(rc == SE_ERR_FNF || rc == SE_ERR_PNF ||
1740                    broken(rc == SE_ERR_ACCESSDENIED) /* win2000 */,
1741                    "%s failed: bad rc=%lu\n", shell_call, rc);
1742             else todo_wine
1743                 ok(rc == SE_ERR_FNF || rc == SE_ERR_PNF ||
1744                    broken(rc == SE_ERR_ACCESSDENIED) /* win2000 */,
1745                    "%s failed: bad rc=%lu\n", shell_call, rc);
1746         }
1747         if (rc == 33)
1748         {
1749             if ((test->todo & 0x2) == 0)
1750                 okChildInt("argcA", 5);
1751             else todo_wine
1752                 okChildInt("argcA", 5);
1753
1754             if ((test->todo & 0x4) == 0)
1755                 okChildString("argvA3", "Open");
1756             else todo_wine
1757                 okChildString("argvA3", "Open");
1758
1759             if ((test->todo & 0x8) == 0)
1760                 okChildPath("argvA4", filename);
1761             else todo_wine
1762                 okChildPath("argvA4", filename);
1763         }
1764         test++;
1765     }
1766
1767     SetEnvironmentVariable("urlprefix", NULL);
1768 }
1769
1770 static void test_find_executable(void)
1771 {
1772     char notepad_path[MAX_PATH];
1773     char filename[MAX_PATH];
1774     char command[MAX_PATH];
1775     const filename_tests_t* test;
1776     INT_PTR rc;
1777
1778     if (!create_test_association(".sfe"))
1779     {
1780         skip("Unable to create association for '.sfe'\n");
1781         return;
1782     }
1783     create_test_verb(".sfe", "Open", 1, "%1");
1784
1785     /* Don't test FindExecutable(..., NULL), it always crashes */
1786
1787     strcpy(command, "your word");
1788     if (0) /* Can crash on Vista! */
1789     {
1790     rc=(INT_PTR)FindExecutableA(NULL, NULL, command);
1791     ok(rc == SE_ERR_FNF || rc > 32 /* nt4 */, "FindExecutable(NULL) returned %ld\n", rc);
1792     ok(strcmp(command, "your word") != 0, "FindExecutable(NULL) returned command=[%s]\n", command);
1793     }
1794
1795     GetSystemDirectoryA( notepad_path, MAX_PATH );
1796     strcat( notepad_path, "\\notepad.exe" );
1797
1798     /* Search for something that should be in the system-wide search path (no default directory) */
1799     strcpy(command, "your word");
1800     rc=(INT_PTR)FindExecutableA("notepad.exe", NULL, command);
1801     ok(rc > 32, "FindExecutable(%s) returned %ld\n", "notepad.exe", rc);
1802     ok(strcasecmp(command, notepad_path) == 0, "FindExecutable(%s) returned command=[%s]\n", "notepad.exe", command);
1803
1804     /* Search for something that should be in the system-wide search path (with default directory) */
1805     strcpy(command, "your word");
1806     rc=(INT_PTR)FindExecutableA("notepad.exe", tmpdir, command);
1807     ok(rc > 32, "FindExecutable(%s) returned %ld\n", "notepad.exe", rc);
1808     ok(strcasecmp(command, notepad_path) == 0, "FindExecutable(%s) returned command=[%s]\n", "notepad.exe", command);
1809
1810     strcpy(command, "your word");
1811     rc=(INT_PTR)FindExecutableA(tmpdir, NULL, command);
1812     ok(rc == SE_ERR_NOASSOC /* >= win2000 */ || rc > 32 /* win98, nt4 */, "FindExecutable(NULL) returned %ld\n", rc);
1813     ok(strcmp(command, "your word") != 0, "FindExecutable(NULL) returned command=[%s]\n", command);
1814
1815     sprintf(filename, "%s\\test file.sfe", tmpdir);
1816     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1817     ok(rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1818     /* Depending on the platform, command could be '%1' or 'test file.sfe' */
1819
1820     rc=(INT_PTR)FindExecutableA("test file.sfe", tmpdir, command);
1821     ok(rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1822
1823     rc=(INT_PTR)FindExecutableA("test file.sfe", NULL, command);
1824     ok(rc == SE_ERR_FNF, "FindExecutable(%s) returned %ld\n", filename, rc);
1825
1826     delete_test_association(".sfe");
1827
1828     if (!create_test_association(".shl"))
1829     {
1830         skip("Unable to create association for '.shl'\n");
1831         return;
1832     }
1833     create_test_verb(".shl", "Open", 0, "Open");
1834
1835     sprintf(filename, "%s\\test file.shl", tmpdir);
1836     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1837     ok(rc == SE_ERR_FNF /* NT4 */ || rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1838
1839     sprintf(filename, "%s\\test file.shlfoo", tmpdir);
1840     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1841
1842     delete_test_association(".shl");
1843
1844     if (rc > 32)
1845     {
1846         /* On Windows XP and 2003 FindExecutable() is completely broken.
1847          * Probably what it does is convert the filename to 8.3 format,
1848          * which as a side effect converts the '.shlfoo' extension to '.shl',
1849          * and then tries to find an association for '.shl'. This means it
1850          * will normally fail on most extensions with more than 3 characters,
1851          * like '.mpeg', etc.
1852          * Also it means we cannot do any other test.
1853          */
1854         win_skip("FindExecutable() is broken -> not running 4+ character extension tests\n");
1855         return;
1856     }
1857
1858     test=filename_tests;
1859     while (test->basename)
1860     {
1861         sprintf(filename, test->basename, tmpdir);
1862         if (strchr(filename, '/'))
1863         {
1864             char* c;
1865             c=filename;
1866             while (*c)
1867             {
1868                 if (*c=='\\')
1869                     *c='/';
1870                 c++;
1871             }
1872         }
1873         /* Win98 does not '\0'-terminate command! */
1874         memset(command, '\0', sizeof(command));
1875         rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1876         if (rc > 32)
1877             rc=33;
1878         if ((test->todo & 0x10)==0)
1879         {
1880             ok(rc==test->rc, "FindExecutable(%s) failed: rc=%ld\n", filename, rc);
1881         }
1882         else todo_wine
1883         {
1884             ok(rc==test->rc, "FindExecutable(%s) failed: rc=%ld\n", filename, rc);
1885         }
1886         if (rc > 32)
1887         {
1888             int equal;
1889             equal=strcmp(command, argv0) == 0 ||
1890                 /* NT4 returns an extra 0x8 character! */
1891                 (strlen(command) == strlen(argv0)+1 && strncmp(command, argv0, strlen(argv0)) == 0);
1892             if ((test->todo & 0x20)==0)
1893             {
1894                 ok(equal, "FindExecutable(%s) returned command='%s' instead of '%s'\n",
1895                    filename, command, argv0);
1896             }
1897             else todo_wine
1898             {
1899                 ok(equal, "FindExecutable(%s) returned command='%s' instead of '%s'\n",
1900                    filename, command, argv0);
1901             }
1902         }
1903         test++;
1904     }
1905 }
1906
1907
1908 static filename_tests_t lnk_tests[]=
1909 {
1910     /* Pass bad / nonexistent filenames as a parameter */
1911     {NULL, "%s\\nonexistent.shlexec",    0xa, 33},
1912     {NULL, "%s\\nonexistent.noassoc",    0xa, 33},
1913
1914     /* Pass regular paths as a parameter */
1915     {NULL, "%s\\test file.shlexec",      0xa, 33},
1916     {NULL, "%s/%%nasty%% $file.shlexec", 0xa, 33},
1917
1918     /* Pass filenames with no association as a parameter */
1919     {NULL, "%s\\test file.noassoc",      0xa, 33},
1920
1921     {NULL, NULL, 0}
1922 };
1923
1924 static void test_lnks(void)
1925 {
1926     char filename[MAX_PATH];
1927     char params[MAX_PATH];
1928     const filename_tests_t* test;
1929     INT_PTR rc;
1930
1931     /* Should open through our association */
1932     sprintf(filename, "%s\\test_shortcut_shlexec.lnk", tmpdir);
1933     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL, NULL);
1934     ok(rc > 32, "%s failed: rc=%lu err=%u\n", shell_call, rc, GetLastError());
1935     okChildInt("argcA", 5);
1936     okChildString("argvA3", "Open");
1937     sprintf(params, "%s\\test file.shlexec", tmpdir);
1938     get_long_path_name(params, filename, sizeof(filename));
1939     okChildPath("argvA4", filename);
1940
1941     todo_wait rc=shell_execute_ex(SEE_MASK_NOZONECHECKS|SEE_MASK_DOENVSUBST, NULL, "%TMPDIR%\\test_shortcut_shlexec.lnk", NULL, NULL, NULL);
1942     ok(rc > 32, "%s failed: rc=%lu err=%u\n", shell_call, rc, GetLastError());
1943     okChildInt("argcA", 5);
1944     todo_wine okChildString("argvA3", "Open");
1945     sprintf(params, "%s\\test file.shlexec", tmpdir);
1946     get_long_path_name(params, filename, sizeof(filename));
1947     todo_wine okChildPath("argvA4", filename);
1948
1949     /* Should just run our executable */
1950     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1951     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL, NULL);
1952     ok(rc > 32, "%s failed: rc=%lu err=%u\n", shell_call, rc, GetLastError());
1953     okChildInt("argcA", 4);
1954     okChildString("argvA3", "Lnk");
1955
1956     /* Lnk's ContextMenuHandler has priority over an explicit class */
1957     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL, "shlexec.shlexec");
1958     ok(rc > 32, "%s failed: rc=%lu err=%u\n", shell_call, rc, GetLastError());
1959     okChildInt("argcA", 4);
1960     okChildString("argvA3", "Lnk");
1961
1962     if (dllver.dwMajorVersion>=6)
1963     {
1964         char* c;
1965        /* Recent versions of shell32.dll accept '/'s in shortcut paths.
1966          * Older versions don't or are quite buggy in this regard.
1967          */
1968         sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1969         c=filename;
1970         while (*c)
1971         {
1972             if (*c=='\\')
1973                 *c='/';
1974             c++;
1975         }
1976         rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL, NULL);
1977         ok(rc > 32, "%s failed: rc=%lu err=%u\n", shell_call, rc,
1978            GetLastError());
1979         okChildInt("argcA", 4);
1980         okChildString("argvA3", "Lnk");
1981     }
1982
1983     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1984     test=lnk_tests;
1985     while (test->basename)
1986     {
1987         params[0]='\"';
1988         sprintf(params+1, test->basename, tmpdir);
1989         strcat(params,"\"");
1990         rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, params,
1991                             NULL, NULL);
1992         if (rc > 32)
1993             rc=33;
1994         if ((test->todo & 0x1)==0)
1995         {
1996             ok(rc==test->rc, "%s failed: rc=%lu err=%u\n", shell_call,
1997                rc, GetLastError());
1998         }
1999         else todo_wine
2000         {
2001             ok(rc==test->rc, "%s failed: rc=%lu err=%u\n", shell_call,
2002                rc, GetLastError());
2003         }
2004         if (rc==0)
2005         {
2006             if ((test->todo & 0x2)==0)
2007             {
2008                 okChildInt("argcA", 5);
2009             }
2010             else
2011             {
2012                 okChildInt("argcA", 5);
2013             }
2014             if ((test->todo & 0x4)==0)
2015             {
2016                 okChildString("argvA3", "Lnk");
2017             }
2018             else todo_wine
2019             {
2020                 okChildString("argvA3", "Lnk");
2021             }
2022             sprintf(params, test->basename, tmpdir);
2023             if ((test->todo & 0x8)==0)
2024             {
2025                 okChildPath("argvA4", params);
2026             }
2027             else
2028             {
2029                 okChildPath("argvA4", params);
2030             }
2031         }
2032         test++;
2033     }
2034 }
2035
2036
2037 static void test_exes(void)
2038 {
2039     char filename[MAX_PATH];
2040     char params[1024];
2041     INT_PTR rc;
2042
2043     sprintf(params, "shlexec \"%s\" Exec", child_file);
2044
2045     /* We need NOZONECHECKS on Win2003 to block a dialog */
2046     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, argv0, params,
2047                         NULL, NULL);
2048     ok(rc > 32, "%s returned %lu\n", shell_call, rc);
2049     okChildInt("argcA", 4);
2050     okChildString("argvA3", "Exec");
2051
2052     if (! skip_noassoc_tests)
2053     {
2054         sprintf(filename, "%s\\test file.noassoc", tmpdir);
2055         if (CopyFile(argv0, filename, FALSE))
2056         {
2057             rc=shell_execute(NULL, filename, params, NULL);
2058             todo_wine {
2059                 ok(rc==SE_ERR_NOASSOC, "%s succeeded: rc=%lu\n", shell_call, rc);
2060             }
2061         }
2062     }
2063     else
2064     {
2065         win_skip("Skipping shellexecute of file with unassociated extension\n");
2066     }
2067 }
2068
2069 typedef struct
2070 {
2071     const char* command;
2072     const char* ddeexec;
2073     const char* application;
2074     const char* topic;
2075     const char* ifexec;
2076     int expectedArgs;
2077     const char* expectedDdeExec;
2078     int todo;
2079 } dde_tests_t;
2080
2081 static dde_tests_t dde_tests[] =
2082 {
2083     /* Test passing and not passing command-line
2084      * argument, no DDE */
2085     {"", NULL, NULL, NULL, NULL, FALSE, "", 0x0},
2086     {"\"%1\"", NULL, NULL, NULL, NULL, TRUE, "", 0x0},
2087
2088     /* Test passing and not passing command-line
2089      * argument, with DDE */
2090     {"", "[open(\"%1\")]", "shlexec", "dde", NULL, FALSE, "[open(\"%s\")]", 0x0},
2091     {"\"%1\"", "[open(\"%1\")]", "shlexec", "dde", NULL, TRUE, "[open(\"%s\")]", 0x0},
2092
2093     /* Test unquoted %1 in command and ddeexec
2094      * (test filename has space) */
2095     {"%1", "[open(%1)]", "shlexec", "dde", NULL, 2, "[open(%s)]", 0x0},
2096
2097     /* Test ifexec precedence over ddeexec */
2098     {"", "[open(\"%1\")]", "shlexec", "dde", "[ifexec(\"%1\")]", FALSE, "[ifexec(\"%s\")]", 0x0},
2099
2100     /* Test default DDE topic */
2101     {"", "[open(\"%1\")]", "shlexec", NULL, NULL, FALSE, "[open(\"%s\")]", 0x0},
2102
2103     /* Test default DDE application */
2104     {"", "[open(\"%1\")]", NULL, "dde", NULL, FALSE, "[open(\"%s\")]", 0x0},
2105
2106     {NULL, NULL, NULL, NULL, NULL, 0, 0x0}
2107 };
2108
2109 static DWORD WINAPI hooked_WaitForInputIdle(HANDLE process, DWORD timeout)
2110 {
2111     return WaitForSingleObject(dde_ready_event, timeout);
2112 }
2113
2114 /*
2115  * WaitForInputIdle() will normally return immediately for console apps. That's
2116  * a problem for us because ShellExecute will assume that an app is ready to
2117  * receive DDE messages after it has called WaitForInputIdle() on that app.
2118  * To work around that we install our own version of WaitForInputIdle() that
2119  * will wait for the child to explicitly tell us that it is ready. We do that
2120  * by changing the entry for WaitForInputIdle() in the shell32 import address
2121  * table.
2122  */
2123 static void hook_WaitForInputIdle(DWORD (WINAPI *new_func)(HANDLE, DWORD))
2124 {
2125     char *base;
2126     PIMAGE_NT_HEADERS nt_headers;
2127     DWORD import_directory_rva;
2128     PIMAGE_IMPORT_DESCRIPTOR import_descriptor;
2129
2130     base = (char *) GetModuleHandleA("shell32.dll");
2131     nt_headers = (PIMAGE_NT_HEADERS)(base + ((PIMAGE_DOS_HEADER) base)->e_lfanew);
2132     import_directory_rva = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
2133
2134     /* Search for the correct imported module by walking the import descriptors */
2135     import_descriptor = (PIMAGE_IMPORT_DESCRIPTOR)(base + import_directory_rva);
2136     while (U(*import_descriptor).OriginalFirstThunk != 0)
2137     {
2138         char *import_module_name;
2139
2140         import_module_name = base + import_descriptor->Name;
2141         if (lstrcmpiA(import_module_name, "user32.dll") == 0 ||
2142             lstrcmpiA(import_module_name, "user32") == 0)
2143         {
2144             PIMAGE_THUNK_DATA int_entry;
2145             PIMAGE_THUNK_DATA iat_entry;
2146
2147             /* The import name table and import address table are two parallel
2148              * arrays. We need the import name table to find the imported
2149              * routine and the import address table to patch the address, so
2150              * walk them side by side */
2151             int_entry = (PIMAGE_THUNK_DATA)(base + U(*import_descriptor).OriginalFirstThunk);
2152             iat_entry = (PIMAGE_THUNK_DATA)(base + import_descriptor->FirstThunk);
2153             while (int_entry->u1.Ordinal != 0)
2154             {
2155                 if (! IMAGE_SNAP_BY_ORDINAL(int_entry->u1.Ordinal))
2156                 {
2157                     PIMAGE_IMPORT_BY_NAME import_by_name;
2158                     import_by_name = (PIMAGE_IMPORT_BY_NAME)(base + int_entry->u1.AddressOfData);
2159                     if (lstrcmpA((char *) import_by_name->Name, "WaitForInputIdle") == 0)
2160                     {
2161                         /* Found the correct routine in the correct imported module. Patch it. */
2162                         DWORD old_prot;
2163                         VirtualProtect(&iat_entry->u1.Function, sizeof(ULONG_PTR), PAGE_READWRITE, &old_prot);
2164                         iat_entry->u1.Function = (ULONG_PTR) new_func;
2165                         VirtualProtect(&iat_entry->u1.Function, sizeof(ULONG_PTR), old_prot, &old_prot);
2166                         break;
2167                     }
2168                 }
2169                 int_entry++;
2170                 iat_entry++;
2171             }
2172             break;
2173         }
2174
2175         import_descriptor++;
2176     }
2177 }
2178
2179 static void test_dde(void)
2180 {
2181     char filename[MAX_PATH], defApplication[MAX_PATH];
2182     const dde_tests_t* test;
2183     char params[1024];
2184     INT_PTR rc;
2185     HANDLE map;
2186     char *shared_block;
2187
2188     hook_WaitForInputIdle(hooked_WaitForInputIdle);
2189
2190     sprintf(filename, "%s\\test file.sde", tmpdir);
2191
2192     /* Default service is application name minus path and extension */
2193     strcpy(defApplication, strrchr(argv0, '\\')+1);
2194     *strchr(defApplication, '.') = 0;
2195
2196     map = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
2197                              4096, "winetest_shlexec_dde_map");
2198     shared_block = MapViewOfFile(map, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 4096);
2199
2200     test = dde_tests;
2201     while (test->command)
2202     {
2203         if (!create_test_association(".sde"))
2204         {
2205             skip("Unable to create association for '.sde'\n");
2206             return;
2207         }
2208         create_test_verb_dde(".sde", "Open", 0, test->command, test->ddeexec,
2209                              test->application, test->topic, test->ifexec);
2210
2211         if (test->application != NULL || test->topic != NULL)
2212         {
2213             strcpy(shared_block, test->application ? test->application : defApplication);
2214             strcpy(shared_block + strlen(shared_block) + 1, test->topic ? test->topic : SZDDESYS_TOPIC);
2215         }
2216         else
2217         {
2218             shared_block[0] = '\0';
2219             shared_block[1] = '\0';
2220         }
2221         ddeExec[0] = 0;
2222
2223         dde_ready_event = CreateEventA(NULL, FALSE, FALSE, "winetest_shlexec_dde_ready");
2224         rc = shell_execute_ex(SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI, NULL, filename, NULL, NULL, NULL);
2225         CloseHandle(dde_ready_event);
2226         if ((test->todo & 0x1)==0)
2227         {
2228             ok(32 < rc, "%s failed: rc=%lu err=%u\n", shell_call,
2229                rc, GetLastError());
2230         }
2231         else todo_wine
2232         {
2233             ok(32 < rc, "%s failed: rc=%lu err=%u\n", shell_call,
2234                rc, GetLastError());
2235         }
2236         if (32 < rc)
2237         {
2238             if ((test->todo & 0x2)==0)
2239             {
2240                 okChildInt("argcA", test->expectedArgs + 3);
2241             }
2242             else todo_wine
2243             {
2244                 okChildInt("argcA", test->expectedArgs + 3);
2245             }
2246             if (test->expectedArgs == 1)
2247             {
2248                 if ((test->todo & 0x4) == 0)
2249                 {
2250                     okChildPath("argvA3", filename);
2251                 }
2252                 else todo_wine
2253                 {
2254                     okChildPath("argvA3", filename);
2255                 }
2256             }
2257             if ((test->todo & 0x8) == 0)
2258             {
2259                 sprintf(params, test->expectedDdeExec, filename);
2260                 okChildPath("ddeExec", params);
2261             }
2262             else todo_wine
2263             {
2264                 sprintf(params, test->expectedDdeExec, filename);
2265                 okChildPath("ddeExec", params);
2266             }
2267         }
2268
2269         delete_test_association(".sde");
2270         test++;
2271     }
2272
2273     UnmapViewOfFile(shared_block);
2274     CloseHandle(map);
2275     hook_WaitForInputIdle((void *) WaitForInputIdle);
2276 }
2277
2278 #define DDE_DEFAULT_APP_VARIANTS 2
2279 typedef struct
2280 {
2281     const char* command;
2282     const char* expectedDdeApplication[DDE_DEFAULT_APP_VARIANTS];
2283     int todo;
2284     int rc[DDE_DEFAULT_APP_VARIANTS];
2285 } dde_default_app_tests_t;
2286
2287 static dde_default_app_tests_t dde_default_app_tests[] =
2288 {
2289     /* Windows XP and 98 handle default DDE app names in different ways.
2290      * The application name we see in the first test determines the pattern
2291      * of application names and return codes we will look for. */
2292
2293     /* Test unquoted existing filename with a space */
2294     {"%s\\test file.exe", {"test file", "test"}, 0x0, {33, 33}},
2295     {"%s\\test file.exe param", {"test file", "test"}, 0x0, {33, 33}},
2296
2297     /* Test quoted existing filename with a space */
2298     {"\"%s\\test file.exe\"", {"test file", "test file"}, 0x0, {33, 33}},
2299     {"\"%s\\test file.exe\" param", {"test file", "test file"}, 0x0, {33, 33}},
2300
2301     /* Test unquoted filename with a space that doesn't exist, but
2302      * test2.exe does */
2303     {"%s\\test2 file.exe", {"test2", "test2"}, 0x0, {33, 33}},
2304     {"%s\\test2 file.exe param", {"test2", "test2"}, 0x0, {33, 33}},
2305
2306     /* Test quoted filename with a space that does not exist */
2307     {"\"%s\\test2 file.exe\"", {"", "test2 file"}, 0x0, {5, 33}},
2308     {"\"%s\\test2 file.exe\" param", {"", "test2 file"}, 0x0, {5, 33}},
2309
2310     /* Test filename supplied without the extension */
2311     {"%s\\test2", {"test2", "test2"}, 0x0, {33, 33}},
2312     {"%s\\test2 param", {"test2", "test2"}, 0x0, {33, 33}},
2313
2314     /* Test an unquoted nonexistent filename */
2315     {"%s\\notexist.exe", {"", "notexist"}, 0x0, {5, 33}},
2316     {"%s\\notexist.exe param", {"", "notexist"}, 0x0, {5, 33}},
2317
2318     /* Test an application that will be found on the path */
2319     {"cmd", {"cmd", "cmd"}, 0x0, {33, 33}},
2320     {"cmd param", {"cmd", "cmd"}, 0x0, {33, 33}},
2321
2322     /* Test an application that will not be found on the path */
2323     {"xyzwxyzwxyz", {"", "xyzwxyzwxyz"}, 0x0, {5, 33}},
2324     {"xyzwxyzwxyz param", {"", "xyzwxyzwxyz"}, 0x0, {5, 33}},
2325
2326     {NULL, {NULL}, 0, {0}}
2327 };
2328
2329 typedef struct
2330 {
2331     char *filename;
2332     DWORD threadIdParent;
2333 } dde_thread_info_t;
2334
2335 static DWORD CALLBACK ddeThread(LPVOID arg)
2336 {
2337     dde_thread_info_t *info = arg;
2338     assert(info && info->filename);
2339     PostThreadMessage(info->threadIdParent,
2340                       WM_QUIT,
2341                       shell_execute_ex(SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI, NULL, info->filename, NULL, NULL, NULL),
2342                       0L);
2343     ExitThread(0);
2344 }
2345
2346 static void test_dde_default_app(void)
2347 {
2348     char filename[MAX_PATH];
2349     HSZ hszApplication;
2350     dde_thread_info_t info = { filename, GetCurrentThreadId() };
2351     const dde_default_app_tests_t* test;
2352     char params[1024];
2353     DWORD threadId;
2354     MSG msg;
2355     INT_PTR rc;
2356     int which = 0;
2357
2358     post_quit_on_execute = FALSE;
2359     ddeInst = 0;
2360     rc = DdeInitializeA(&ddeInst, ddeCb, CBF_SKIP_ALLNOTIFICATIONS | CBF_FAIL_ADVISES |
2361                         CBF_FAIL_POKES | CBF_FAIL_REQUESTS, 0L);
2362     assert(rc == DMLERR_NO_ERROR);
2363
2364     sprintf(filename, "%s\\test file.sde", tmpdir);
2365
2366     /* It is strictly not necessary to register an application name here, but wine's
2367      * DdeNameService implementation complains if 0L is passed instead of
2368      * hszApplication with DNS_FILTEROFF */
2369     hszApplication = DdeCreateStringHandleA(ddeInst, "shlexec", CP_WINANSI);
2370     hszTopic = DdeCreateStringHandleA(ddeInst, "shlexec", CP_WINANSI);
2371     assert(hszApplication && hszTopic);
2372     assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_REGISTER | DNS_FILTEROFF));
2373
2374     test = dde_default_app_tests;
2375     while (test->command)
2376     {
2377         if (!create_test_association(".sde"))
2378         {
2379             skip("Unable to create association for '.sde'\n");
2380             return;
2381         }
2382         sprintf(params, test->command, tmpdir);
2383         create_test_verb_dde(".sde", "Open", 1, params, "[test]", NULL,
2384                              "shlexec", NULL);
2385         ddeApplication[0] = 0;
2386
2387         /* No application will be run as we will respond to the first DDE event,
2388          * so don't wait for it */
2389         SetEvent(hEvent);
2390
2391         assert(CreateThread(NULL, 0, ddeThread, &info, 0, &threadId));
2392         while (GetMessage(&msg, NULL, 0, 0)) DispatchMessage(&msg);
2393         rc = msg.wParam > 32 ? 33 : msg.wParam;
2394
2395         /* First test, find which set of test data we expect to see */
2396         if (test == dde_default_app_tests)
2397         {
2398             int i;
2399             for (i=0; i<DDE_DEFAULT_APP_VARIANTS; i++)
2400             {
2401                 if (!strcmp(ddeApplication, test->expectedDdeApplication[i]))
2402                 {
2403                     which = i;
2404                     break;
2405                 }
2406             }
2407             if (i == DDE_DEFAULT_APP_VARIANTS)
2408                 skip("Default DDE application test does not match any available results, using first expected data set.\n");
2409         }
2410
2411         if ((test->todo & 0x1)==0)
2412         {
2413             ok(rc==test->rc[which], "%s failed: rc=%lu err=%u\n", shell_call,
2414                rc, GetLastError());
2415         }
2416         else todo_wine
2417         {
2418             ok(rc==test->rc[which], "%s failed: rc=%lu err=%u\n", shell_call,
2419                rc, GetLastError());
2420         }
2421         if (rc == 33)
2422         {
2423             if ((test->todo & 0x2)==0)
2424             {
2425                 ok(!strcmp(ddeApplication, test->expectedDdeApplication[which]),
2426                    "Expected application '%s', got '%s'\n",
2427                    test->expectedDdeApplication[which], ddeApplication);
2428             }
2429             else todo_wine
2430             {
2431                 ok(!strcmp(ddeApplication, test->expectedDdeApplication[which]),
2432                    "Expected application '%s', got '%s'\n",
2433                    test->expectedDdeApplication[which], ddeApplication);
2434             }
2435         }
2436
2437         delete_test_association(".sde");
2438         test++;
2439     }
2440
2441     assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_UNREGISTER));
2442     assert(DdeFreeStringHandle(ddeInst, hszTopic));
2443     assert(DdeFreeStringHandle(ddeInst, hszApplication));
2444     assert(DdeUninitialize(ddeInst));
2445 }
2446
2447 static void init_test(void)
2448 {
2449     HMODULE hdll;
2450     HRESULT (WINAPI *pDllGetVersion)(DLLVERSIONINFO*);
2451     char filename[MAX_PATH];
2452     WCHAR lnkfile[MAX_PATH];
2453     char params[1024];
2454     const char* const * testfile;
2455     lnk_desc_t desc;
2456     DWORD rc;
2457     HRESULT r;
2458
2459     hdll=GetModuleHandleA("shell32.dll");
2460     pDllGetVersion=(void*)GetProcAddress(hdll, "DllGetVersion");
2461     if (pDllGetVersion)
2462     {
2463         dllver.cbSize=sizeof(dllver);
2464         pDllGetVersion(&dllver);
2465         trace("major=%d minor=%d build=%d platform=%d\n",
2466               dllver.dwMajorVersion, dllver.dwMinorVersion,
2467               dllver.dwBuildNumber, dllver.dwPlatformID);
2468     }
2469     else
2470     {
2471         memset(&dllver, 0, sizeof(dllver));
2472     }
2473
2474     r = CoInitialize(NULL);
2475     ok(r == S_OK, "CoInitialize failed (0x%08x)\n", r);
2476     if (FAILED(r))
2477         exit(1);
2478
2479     rc=GetModuleFileName(NULL, argv0, sizeof(argv0));
2480     assert(rc!=0 && rc<sizeof(argv0));
2481     if (GetFileAttributes(argv0)==INVALID_FILE_ATTRIBUTES)
2482     {
2483         strcat(argv0, ".so");
2484         ok(GetFileAttributes(argv0)!=INVALID_FILE_ATTRIBUTES,
2485            "unable to find argv0!\n");
2486     }
2487
2488     GetTempPathA(sizeof(filename), filename);
2489     GetTempFileNameA(filename, "wt", 0, tmpdir);
2490     DeleteFileA( tmpdir );
2491     rc = CreateDirectoryA( tmpdir, NULL );
2492     ok( rc, "failed to create %s err %u\n", tmpdir, GetLastError() );
2493     /* Set %TMPDIR% for the tests */
2494     SetEnvironmentVariableA("TMPDIR", tmpdir);
2495
2496     rc = GetTempFileNameA(tmpdir, "wt", 0, child_file);
2497     assert(rc != 0);
2498     init_event(child_file);
2499
2500     /* Set up the test files */
2501     testfile=testfiles;
2502     while (*testfile)
2503     {
2504         HANDLE hfile;
2505
2506         sprintf(filename, *testfile, tmpdir);
2507         hfile=CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
2508                      FILE_ATTRIBUTE_NORMAL, NULL);
2509         if (hfile==INVALID_HANDLE_VALUE)
2510         {
2511             trace("unable to create '%s': err=%u\n", filename, GetLastError());
2512             assert(0);
2513         }
2514         CloseHandle(hfile);
2515         testfile++;
2516     }
2517
2518     /* Setup the test shortcuts */
2519     sprintf(filename, "%s\\test_shortcut_shlexec.lnk", tmpdir);
2520     MultiByteToWideChar(CP_ACP, 0, filename, -1, lnkfile, sizeof(lnkfile)/sizeof(*lnkfile));
2521     desc.description=NULL;
2522     desc.workdir=NULL;
2523     sprintf(filename, "%s\\test file.shlexec", tmpdir);
2524     desc.path=filename;
2525     desc.pidl=NULL;
2526     desc.arguments="ignored";
2527     desc.showcmd=0;
2528     desc.icon=NULL;
2529     desc.icon_id=0;
2530     desc.hotkey=0;
2531     create_lnk(lnkfile, &desc, 0);
2532
2533     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
2534     MultiByteToWideChar(CP_ACP, 0, filename, -1, lnkfile, sizeof(lnkfile)/sizeof(*lnkfile));
2535     desc.description=NULL;
2536     desc.workdir=NULL;
2537     desc.path=argv0;
2538     desc.pidl=NULL;
2539     sprintf(params, "shlexec \"%s\" Lnk", child_file);
2540     desc.arguments=params;
2541     desc.showcmd=0;
2542     desc.icon=NULL;
2543     desc.icon_id=0;
2544     desc.hotkey=0;
2545     create_lnk(lnkfile, &desc, 0);
2546
2547     /* Create a basic association suitable for most tests */
2548     if (!create_test_association(".shlexec"))
2549     {
2550         skip("Unable to create association for '.shlexec'\n");
2551         return;
2552     }
2553     create_test_verb(".shlexec", "Open", 0, "Open \"%1\"");
2554     create_test_verb(".shlexec", "NoQuotes", 0, "NoQuotes %1");
2555     create_test_verb(".shlexec", "LowerL", 0, "LowerL %l");
2556     create_test_verb(".shlexec", "QuotedLowerL", 0, "QuotedLowerL \"%l\"");
2557     create_test_verb(".shlexec", "UpperL", 0, "UpperL %L");
2558     create_test_verb(".shlexec", "QuotedUpperL", 0, "QuotedUpperL \"%L\"");
2559 }
2560
2561 static void cleanup_test(void)
2562 {
2563     char filename[MAX_PATH];
2564     const char* const * testfile;
2565
2566     /* Delete the test files */
2567     testfile=testfiles;
2568     while (*testfile)
2569     {
2570         sprintf(filename, *testfile, tmpdir);
2571         /* Make sure we can delete the files ('test file.noassoc' is read-only now) */
2572         SetFileAttributes(filename, FILE_ATTRIBUTE_NORMAL);
2573         DeleteFile(filename);
2574         testfile++;
2575     }
2576     DeleteFile(child_file);
2577     RemoveDirectoryA(tmpdir);
2578
2579     /* Delete the test association */
2580     delete_test_association(".shlexec");
2581
2582     CloseHandle(hEvent);
2583
2584     CoUninitialize();
2585 }
2586
2587 static void test_directory(void)
2588 {
2589     char path[MAX_PATH], curdir[MAX_PATH];
2590     char params[1024], dirpath[1024];
2591     INT_PTR rc;
2592
2593     sprintf(path, "%s\\test2.exe", tmpdir);
2594     CopyFileA(argv0, path, FALSE);
2595
2596     sprintf(params, "shlexec \"%s\" Exec", child_file);
2597
2598     /* Test with the current directory */
2599     GetCurrentDirectoryA(sizeof(curdir), curdir);
2600     SetCurrentDirectoryA(tmpdir);
2601     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS|SEE_MASK_FLAG_NO_UI,
2602                         NULL, "test2.exe", params, NULL, NULL);
2603     ok(rc > 32, "%s returned %lu\n", shell_call, rc);
2604     okChildInt("argcA", 4);
2605     okChildString("argvA3", "Exec");
2606     todo_wine okChildPath("longPath", path);
2607     SetCurrentDirectoryA(curdir);
2608
2609     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS|SEE_MASK_FLAG_NO_UI,
2610                         NULL, "test2.exe", params, NULL, NULL);
2611     ok(rc == SE_ERR_FNF, "%s returned %lu\n", shell_call, rc);
2612
2613     /* Explicitly specify the directory to use */
2614     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS|SEE_MASK_FLAG_NO_UI,
2615                         NULL, "test2.exe", params, tmpdir, NULL);
2616     ok(rc > 32, "%s returned %lu\n", shell_call, rc);
2617     okChildInt("argcA", 4);
2618     okChildString("argvA3", "Exec");
2619     todo_wine okChildPath("longPath", path);
2620
2621     /* Specify it through an environment variable */
2622     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS|SEE_MASK_FLAG_NO_UI,
2623                         NULL, "test2.exe", params, "%TMPDIR%", NULL);
2624     todo_wine ok(rc == SE_ERR_FNF, "%s returned %lu\n", shell_call, rc);
2625
2626     rc=shell_execute_ex(SEE_MASK_DOENVSUBST|SEE_MASK_NOZONECHECKS|SEE_MASK_FLAG_NO_UI,
2627                         NULL, "test2.exe", params, "%TMPDIR%", NULL);
2628     ok(rc > 32, "%s returned %lu\n", shell_call, rc);
2629     okChildInt("argcA", 4);
2630     okChildString("argvA3", "Exec");
2631     todo_wine okChildPath("longPath", path);
2632
2633     /* Not a colon-separated directory list */
2634     sprintf(dirpath, "%s:%s", curdir, tmpdir);
2635     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS|SEE_MASK_FLAG_NO_UI,
2636                         NULL, "test2.exe", params, dirpath, NULL);
2637     ok(rc == SE_ERR_FNF, "%s returned %lu\n", shell_call, rc);
2638 }
2639
2640 START_TEST(shlexec)
2641 {
2642
2643     myARGC = winetest_get_mainargs(&myARGV);
2644     if (myARGC >= 3)
2645     {
2646         doChild(myARGC, myARGV);
2647         exit(0);
2648     }
2649
2650     init_test();
2651
2652     test_commandline2argv();
2653     test_argify();
2654     test_lpFile_parsed();
2655     test_filename();
2656     test_fileurls();
2657     test_find_executable();
2658     test_lnks();
2659     test_exes();
2660     test_dde();
2661     test_dde_default_app();
2662     test_directory();
2663
2664     cleanup_test();
2665 }