shell32/tests: SHELL_ArgifyW(%2|%*|%~3, ...) tests.
[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
61
62 /***
63  *
64  * ShellExecute wrappers
65  *
66  ***/
67 static void dump_child(void);
68
69 static HANDLE hEvent;
70 static void init_event(const char* child_file)
71 {
72     char* event_name;
73     event_name=strrchr(child_file, '\\')+1;
74     hEvent=CreateEvent(NULL, FALSE, FALSE, event_name);
75 }
76
77 static void strcat_param(char* str, const char* param)
78 {
79     if (param!=NULL)
80     {
81         strcat(str, "\"");
82         strcat(str, param);
83         strcat(str, "\"");
84     }
85     else
86     {
87         strcat(str, "null");
88     }
89 }
90
91 static char shell_call[2048]="";
92 static int shell_execute(LPCSTR operation, LPCSTR file, LPCSTR parameters, LPCSTR directory)
93 {
94     INT_PTR rc;
95
96     strcpy(shell_call, "ShellExecute(");
97     strcat_param(shell_call, operation);
98     strcat(shell_call, ", ");
99     strcat_param(shell_call, file);
100     strcat(shell_call, ", ");
101     strcat_param(shell_call, parameters);
102     strcat(shell_call, ", ");
103     strcat_param(shell_call, directory);
104     strcat(shell_call, ")");
105     if (winetest_debug > 1)
106         trace("%s\n", shell_call);
107
108     DeleteFile(child_file);
109     SetLastError(0xcafebabe);
110
111     /* FIXME: We cannot use ShellExecuteEx() here because if there is no
112      * association it displays the 'Open With' dialog and I could not find
113      * a flag to prevent this.
114      */
115     rc=(INT_PTR)ShellExecute(NULL, operation, file, parameters, directory, SW_SHOWNORMAL);
116
117     if (rc > 32)
118     {
119         int wait_rc;
120         wait_rc=WaitForSingleObject(hEvent, 5000);
121         if (wait_rc == WAIT_TIMEOUT)
122         {
123             HWND wnd = FindWindowA("#32770", "Windows");
124             if (wnd != NULL)
125             {
126                 SendMessage(wnd, WM_CLOSE, 0, 0);
127                 win_skip("Skipping shellexecute of file with unassociated extension\n");
128                 skip_noassoc_tests = TRUE;
129                 rc = SE_ERR_NOASSOC;
130             }
131         }
132         ok(wait_rc==WAIT_OBJECT_0 || rc <= 32, "WaitForSingleObject returned %d\n", wait_rc);
133     }
134     /* The child process may have changed the result file, so let profile
135      * functions know about it
136      */
137     WritePrivateProfileStringA(NULL, NULL, NULL, child_file);
138     if (rc > 32)
139         dump_child();
140
141     return rc;
142 }
143
144 static int shell_execute_ex(DWORD mask, LPCSTR operation, LPCSTR file,
145                             LPCSTR parameters, LPCSTR directory)
146 {
147     SHELLEXECUTEINFO sei;
148     BOOL success;
149     INT_PTR rc;
150
151     strcpy(shell_call, "ShellExecuteEx(");
152     strcat_param(shell_call, operation);
153     strcat(shell_call, ", ");
154     strcat_param(shell_call, file);
155     strcat(shell_call, ", ");
156     strcat_param(shell_call, parameters);
157     strcat(shell_call, ", ");
158     strcat_param(shell_call, directory);
159     strcat(shell_call, ")");
160     if (winetest_debug > 1)
161         trace("%s\n", shell_call);
162
163     sei.cbSize=sizeof(sei);
164     sei.fMask=SEE_MASK_NOCLOSEPROCESS | mask;
165     sei.hwnd=NULL;
166     sei.lpVerb=operation;
167     sei.lpFile=file;
168     sei.lpParameters=parameters;
169     sei.lpDirectory=directory;
170     sei.nShow=SW_SHOWNORMAL;
171     sei.hInstApp=NULL; /* Out */
172     sei.lpIDList=NULL;
173     sei.lpClass=NULL;
174     sei.hkeyClass=NULL;
175     sei.dwHotKey=0;
176     U(sei).hIcon=NULL;
177     sei.hProcess=NULL; /* Out */
178
179     DeleteFile(child_file);
180     SetLastError(0xcafebabe);
181     success=ShellExecuteEx(&sei);
182     rc=(INT_PTR)sei.hInstApp;
183     ok((success && rc > 32) || (!success && rc <= 32),
184        "%s rc=%d and hInstApp=%ld is not allowed\n", shell_call, success, rc);
185
186     if (rc > 32)
187     {
188         int wait_rc;
189         if (sei.hProcess!=NULL)
190         {
191             wait_rc=WaitForSingleObject(sei.hProcess, 5000);
192             ok(wait_rc==WAIT_OBJECT_0, "WaitForSingleObject(hProcess) returned %d\n", wait_rc);
193         }
194         wait_rc=WaitForSingleObject(hEvent, 5000);
195         ok(wait_rc==WAIT_OBJECT_0, "WaitForSingleObject returned %d\n", wait_rc);
196     }
197     /* The child process may have changed the result file, so let profile
198      * functions know about it
199      */
200     WritePrivateProfileStringA(NULL, NULL, NULL, child_file);
201     if (rc > 32)
202         dump_child();
203
204     return rc;
205 }
206
207
208
209 /***
210  *
211  * Functions to create / delete associations wrappers
212  *
213  ***/
214
215 static BOOL create_test_association(const char* extension)
216 {
217     HKEY hkey, hkey_shell;
218     char class[MAX_PATH];
219     LONG rc;
220
221     sprintf(class, "shlexec%s", extension);
222     rc=RegCreateKeyEx(HKEY_CLASSES_ROOT, extension, 0, NULL, 0, KEY_SET_VALUE,
223                       NULL, &hkey, NULL);
224     if (rc != ERROR_SUCCESS)
225         return FALSE;
226
227     rc=RegSetValueEx(hkey, NULL, 0, REG_SZ, (LPBYTE) class, strlen(class)+1);
228     ok(rc==ERROR_SUCCESS, "RegSetValueEx '%s' failed, expected ERROR_SUCCESS, got %d\n", class, rc);
229     CloseHandle(hkey);
230
231     rc=RegCreateKeyEx(HKEY_CLASSES_ROOT, class, 0, NULL, 0,
232                       KEY_CREATE_SUB_KEY | KEY_ENUMERATE_SUB_KEYS, NULL, &hkey, NULL);
233     ok(rc==ERROR_SUCCESS, "RegCreateKeyEx '%s' failed, expected ERROR_SUCCESS, got %d\n", class, rc);
234
235     rc=RegCreateKeyEx(hkey, "shell", 0, NULL, 0,
236                       KEY_CREATE_SUB_KEY, NULL, &hkey_shell, NULL);
237     ok(rc==ERROR_SUCCESS, "RegCreateKeyEx 'shell' failed, expected ERROR_SUCCESS, got %d\n", rc);
238
239     CloseHandle(hkey);
240     CloseHandle(hkey_shell);
241
242     return TRUE;
243 }
244
245 /* Based on RegDeleteTreeW from dlls/advapi32/registry.c */
246 static LSTATUS myRegDeleteTreeA(HKEY hKey, LPCSTR lpszSubKey)
247 {
248     LONG ret;
249     DWORD dwMaxSubkeyLen, dwMaxValueLen;
250     DWORD dwMaxLen, dwSize;
251     CHAR szNameBuf[MAX_PATH], *lpszName = szNameBuf;
252     HKEY hSubKey = hKey;
253
254     if(lpszSubKey)
255     {
256         ret = RegOpenKeyExA(hKey, lpszSubKey, 0, KEY_READ, &hSubKey);
257         if (ret) return ret;
258     }
259
260     /* Get highest length for keys, values */
261     ret = RegQueryInfoKeyA(hSubKey, NULL, NULL, NULL, NULL,
262             &dwMaxSubkeyLen, NULL, NULL, &dwMaxValueLen, NULL, NULL, NULL);
263     if (ret) goto cleanup;
264
265     dwMaxSubkeyLen++;
266     dwMaxValueLen++;
267     dwMaxLen = max(dwMaxSubkeyLen, dwMaxValueLen);
268     if (dwMaxLen > sizeof(szNameBuf)/sizeof(CHAR))
269     {
270         /* Name too big: alloc a buffer for it */
271         if (!(lpszName = HeapAlloc( GetProcessHeap(), 0, dwMaxLen*sizeof(CHAR))))
272         {
273             ret = ERROR_NOT_ENOUGH_MEMORY;
274             goto cleanup;
275         }
276     }
277
278
279     /* Recursively delete all the subkeys */
280     while (TRUE)
281     {
282         dwSize = dwMaxLen;
283         if (RegEnumKeyExA(hSubKey, 0, lpszName, &dwSize, NULL,
284                           NULL, NULL, NULL)) break;
285
286         ret = myRegDeleteTreeA(hSubKey, lpszName);
287         if (ret) goto cleanup;
288     }
289
290     if (lpszSubKey)
291         ret = RegDeleteKeyA(hKey, lpszSubKey);
292     else
293         while (TRUE)
294         {
295             dwSize = dwMaxLen;
296             if (RegEnumValueA(hKey, 0, lpszName, &dwSize,
297                   NULL, NULL, NULL, NULL)) break;
298
299             ret = RegDeleteValueA(hKey, lpszName);
300             if (ret) goto cleanup;
301         }
302
303 cleanup:
304     /* Free buffer if allocated */
305     if (lpszName != szNameBuf)
306         HeapFree( GetProcessHeap(), 0, lpszName);
307     if(lpszSubKey)
308         RegCloseKey(hSubKey);
309     return ret;
310 }
311
312 static void delete_test_association(const char* extension)
313 {
314     char class[MAX_PATH];
315
316     sprintf(class, "shlexec%s", extension);
317     myRegDeleteTreeA(HKEY_CLASSES_ROOT, class);
318     myRegDeleteTreeA(HKEY_CLASSES_ROOT, extension);
319 }
320
321 static void create_test_verb_dde(const char* extension, const char* verb,
322                                  int rawcmd, const char* cmdtail, const char *ddeexec,
323                                  const char *application, const char *topic,
324                                  const char *ifexec)
325 {
326     HKEY hkey_shell, hkey_verb, hkey_cmd;
327     char shell[MAX_PATH];
328     char* cmd;
329     LONG rc;
330
331     sprintf(shell, "shlexec%s\\shell", extension);
332     rc=RegOpenKeyEx(HKEY_CLASSES_ROOT, shell, 0,
333                     KEY_CREATE_SUB_KEY, &hkey_shell);
334     assert(rc==ERROR_SUCCESS);
335     rc=RegCreateKeyEx(hkey_shell, verb, 0, NULL, 0, KEY_CREATE_SUB_KEY,
336                       NULL, &hkey_verb, NULL);
337     assert(rc==ERROR_SUCCESS);
338     rc=RegCreateKeyEx(hkey_verb, "command", 0, NULL, 0, KEY_SET_VALUE,
339                       NULL, &hkey_cmd, NULL);
340     assert(rc==ERROR_SUCCESS);
341
342     if (rawcmd)
343     {
344         rc=RegSetValueEx(hkey_cmd, NULL, 0, REG_SZ, (LPBYTE)cmdtail, strlen(cmdtail)+1);
345     }
346     else
347     {
348         cmd=HeapAlloc(GetProcessHeap(), 0, strlen(argv0)+10+strlen(child_file)+2+strlen(cmdtail)+1);
349         sprintf(cmd,"%s shlexec \"%s\" %s", argv0, child_file, cmdtail);
350         rc=RegSetValueEx(hkey_cmd, NULL, 0, REG_SZ, (LPBYTE)cmd, strlen(cmd)+1);
351         assert(rc==ERROR_SUCCESS);
352         HeapFree(GetProcessHeap(), 0, cmd);
353     }
354
355     if (ddeexec)
356     {
357         HKEY hkey_ddeexec, hkey_application, hkey_topic, hkey_ifexec;
358
359         rc=RegCreateKeyEx(hkey_verb, "ddeexec", 0, NULL, 0, KEY_SET_VALUE |
360                           KEY_CREATE_SUB_KEY, NULL, &hkey_ddeexec, NULL);
361         assert(rc==ERROR_SUCCESS);
362         rc=RegSetValueEx(hkey_ddeexec, NULL, 0, REG_SZ, (LPBYTE)ddeexec,
363                          strlen(ddeexec)+1);
364         assert(rc==ERROR_SUCCESS);
365         if (application)
366         {
367             rc=RegCreateKeyEx(hkey_ddeexec, "application", 0, NULL, 0, KEY_SET_VALUE,
368                               NULL, &hkey_application, NULL);
369             assert(rc==ERROR_SUCCESS);
370             rc=RegSetValueEx(hkey_application, NULL, 0, REG_SZ, (LPBYTE)application,
371                              strlen(application)+1);
372             assert(rc==ERROR_SUCCESS);
373             CloseHandle(hkey_application);
374         }
375         if (topic)
376         {
377             rc=RegCreateKeyEx(hkey_ddeexec, "topic", 0, NULL, 0, KEY_SET_VALUE,
378                               NULL, &hkey_topic, NULL);
379             assert(rc==ERROR_SUCCESS);
380             rc=RegSetValueEx(hkey_topic, NULL, 0, REG_SZ, (LPBYTE)topic,
381                              strlen(topic)+1);
382             assert(rc==ERROR_SUCCESS);
383             CloseHandle(hkey_topic);
384         }
385         if (ifexec)
386         {
387             rc=RegCreateKeyEx(hkey_ddeexec, "ifexec", 0, NULL, 0, KEY_SET_VALUE,
388                               NULL, &hkey_ifexec, NULL);
389             assert(rc==ERROR_SUCCESS);
390             rc=RegSetValueEx(hkey_ifexec, NULL, 0, REG_SZ, (LPBYTE)ifexec,
391                              strlen(ifexec)+1);
392             assert(rc==ERROR_SUCCESS);
393             CloseHandle(hkey_ifexec);
394         }
395         CloseHandle(hkey_ddeexec);
396     }
397
398     CloseHandle(hkey_shell);
399     CloseHandle(hkey_verb);
400     CloseHandle(hkey_cmd);
401 }
402
403 static void create_test_verb(const char* extension, const char* verb,
404                              int rawcmd, const char* cmdtail)
405 {
406     create_test_verb_dde(extension, verb, rawcmd, cmdtail, NULL, NULL,
407                          NULL, NULL);
408 }
409
410 /***
411  *
412  * Functions to check that the child process was started just right
413  * (borrowed from dlls/kernel32/tests/process.c)
414  *
415  ***/
416
417 static const char* encodeA(const char* str)
418 {
419     static char encoded[2*1024+1];
420     char*       ptr;
421     size_t      len,i;
422
423     if (!str) return "";
424     len = strlen(str) + 1;
425     if (len >= sizeof(encoded)/2)
426     {
427         fprintf(stderr, "string is too long!\n");
428         assert(0);
429     }
430     ptr = encoded;
431     for (i = 0; i < len; i++)
432         sprintf(&ptr[i * 2], "%02x", (unsigned char)str[i]);
433     ptr[2 * len] = '\0';
434     return ptr;
435 }
436
437 static unsigned decode_char(char c)
438 {
439     if (c >= '0' && c <= '9') return c - '0';
440     if (c >= 'a' && c <= 'f') return c - 'a' + 10;
441     assert(c >= 'A' && c <= 'F');
442     return c - 'A' + 10;
443 }
444
445 static char* decodeA(const char* str)
446 {
447     static char decoded[1024];
448     char*       ptr;
449     size_t      len,i;
450
451     len = strlen(str) / 2;
452     if (!len--) return NULL;
453     if (len >= sizeof(decoded))
454     {
455         fprintf(stderr, "string is too long!\n");
456         assert(0);
457     }
458     ptr = decoded;
459     for (i = 0; i < len; i++)
460         ptr[i] = (decode_char(str[2 * i]) << 4) | decode_char(str[2 * i + 1]);
461     ptr[len] = '\0';
462     return ptr;
463 }
464
465 static void     childPrintf(HANDLE h, const char* fmt, ...)
466 {
467     va_list     valist;
468     char        buffer[1024];
469     DWORD       w;
470
471     va_start(valist, fmt);
472     vsprintf(buffer, fmt, valist);
473     va_end(valist);
474     WriteFile(h, buffer, strlen(buffer), &w, NULL);
475 }
476
477 static DWORD ddeInst;
478 static HSZ hszTopic;
479 static char ddeExec[MAX_PATH], ddeApplication[MAX_PATH];
480 static BOOL post_quit_on_execute;
481
482 static HDDEDATA CALLBACK ddeCb(UINT uType, UINT uFmt, HCONV hConv,
483                                HSZ hsz1, HSZ hsz2, HDDEDATA hData,
484                                ULONG_PTR dwData1, ULONG_PTR dwData2)
485 {
486     DWORD size = 0;
487
488     if (winetest_debug > 2)
489         trace("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
490               uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
491
492     switch (uType)
493     {
494         case XTYP_CONNECT:
495             if (!DdeCmpStringHandles(hsz1, hszTopic))
496             {
497                 size = DdeQueryString(ddeInst, hsz2, ddeApplication, MAX_PATH, CP_WINANSI);
498                 assert(size < MAX_PATH);
499                 return (HDDEDATA)TRUE;
500             }
501             return (HDDEDATA)FALSE;
502
503         case XTYP_EXECUTE:
504             size = DdeGetData(hData, (LPBYTE)ddeExec, MAX_PATH, 0L);
505             assert(size < MAX_PATH);
506             DdeFreeDataHandle(hData);
507             if (post_quit_on_execute)
508                 PostQuitMessage(0);
509             return (HDDEDATA)DDE_FACK;
510
511         default:
512             return NULL;
513     }
514 }
515
516 /*
517  * This is just to make sure the child won't run forever stuck in a GetMessage()
518  * loop when DDE fails for some reason.
519  */
520 static void CALLBACK childTimeout(HWND wnd, UINT msg, UINT_PTR timer, DWORD time)
521 {
522     trace("childTimeout called\n");
523
524     PostQuitMessage(0);
525 }
526
527 static void doChild(int argc, char** argv)
528 {
529     char* filename;
530     HANDLE hFile, map;
531     int i;
532     int rc;
533     HSZ hszApplication;
534     UINT_PTR timer;
535     HANDLE dde_ready;
536     MSG msg;
537     char *shared_block;
538
539     filename=argv[2];
540     hFile=CreateFileA(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
541     if (hFile == INVALID_HANDLE_VALUE)
542         return;
543
544     /* Arguments */
545     childPrintf(hFile, "[Arguments]\r\n");
546     if (winetest_debug > 2)
547         trace("argcA=%d\n", argc);
548     childPrintf(hFile, "argcA=%d\r\n", argc);
549     for (i = 0; i < argc; i++)
550     {
551         if (winetest_debug > 2)
552             trace("argvA%d=%s\n", i, argv[i]);
553         childPrintf(hFile, "argvA%d=%s\r\n", i, encodeA(argv[i]));
554     }
555
556     map = OpenFileMappingA(FILE_MAP_READ, FALSE, "winetest_shlexec_dde_map");
557     if (map != NULL)
558     {
559         shared_block = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 4096);
560         CloseHandle(map);
561         if (shared_block[0] != '\0' || shared_block[1] != '\0')
562         {
563             post_quit_on_execute = TRUE;
564             ddeInst = 0;
565             rc = DdeInitializeA(&ddeInst, ddeCb, CBF_SKIP_ALLNOTIFICATIONS | CBF_FAIL_ADVISES |
566                                 CBF_FAIL_POKES | CBF_FAIL_REQUESTS, 0L);
567             assert(rc == DMLERR_NO_ERROR);
568             hszApplication = DdeCreateStringHandleA(ddeInst, shared_block, CP_WINANSI);
569             hszTopic = DdeCreateStringHandleA(ddeInst, shared_block + strlen(shared_block) + 1, CP_WINANSI);
570             assert(hszApplication && hszTopic);
571             assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_REGISTER | DNS_FILTEROFF));
572
573             timer = SetTimer(NULL, 0, 2500, childTimeout);
574
575             dde_ready = CreateEvent(NULL, FALSE, FALSE, "winetest_shlexec_dde_ready");
576             SetEvent(dde_ready);
577             CloseHandle(dde_ready);
578
579             while (GetMessage(&msg, NULL, 0, 0))
580                 DispatchMessage(&msg);
581
582             KillTimer(NULL, timer);
583             assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_UNREGISTER));
584             assert(DdeFreeStringHandle(ddeInst, hszTopic));
585             assert(DdeFreeStringHandle(ddeInst, hszApplication));
586             assert(DdeUninitialize(ddeInst));
587         }
588         else
589         {
590             dde_ready = CreateEvent(NULL, FALSE, FALSE, "winetest_shlexec_dde_ready");
591             SetEvent(dde_ready);
592             CloseHandle(dde_ready);
593         }
594
595         UnmapViewOfFile(shared_block);
596
597         childPrintf(hFile, "ddeExec=%s\r\n", encodeA(ddeExec));
598     }
599
600     CloseHandle(hFile);
601
602     init_event(filename);
603     SetEvent(hEvent);
604     CloseHandle(hEvent);
605 }
606
607 static char* getChildString(const char* sect, const char* key)
608 {
609     char        buf[1024];
610     char*       ret;
611
612     GetPrivateProfileStringA(sect, key, "-", buf, sizeof(buf), child_file);
613     if (buf[0] == '\0' || (buf[0] == '-' && buf[1] == '\0')) return NULL;
614     assert(!(strlen(buf) & 1));
615     ret = decodeA(buf);
616     return ret;
617 }
618
619 static void dump_child(void)
620 {
621     if (winetest_debug > 1)
622     {
623         char key[18];
624         char* str;
625         int i, c;
626
627         c=GetPrivateProfileIntA("Arguments", "argcA", -1, child_file);
628         trace("argcA=%d\n",c);
629         for (i=0;i<c;i++)
630         {
631             sprintf(key, "argvA%d", i);
632             str=getChildString("Arguments", key);
633             trace("%s=%s\n", key, str);
634         }
635     }
636 }
637
638 static int StrCmpPath(const char* s1, const char* s2)
639 {
640     if (!s1 && !s2) return 0;
641     if (!s2) return 1;
642     if (!s1) return -1;
643     while (*s1)
644     {
645         if (!*s2)
646         {
647             if (*s1=='.')
648                 s1++;
649             return (*s1-*s2);
650         }
651         if ((*s1=='/' || *s1=='\\') && (*s2=='/' || *s2=='\\'))
652         {
653             while (*s1=='/' || *s1=='\\')
654                 s1++;
655             while (*s2=='/' || *s2=='\\')
656                 s2++;
657         }
658         else if (toupper(*s1)==toupper(*s2))
659         {
660             s1++;
661             s2++;
662         }
663         else
664         {
665             return (*s1-*s2);
666         }
667     }
668     if (*s2=='.')
669         s2++;
670     if (*s2)
671         return -1;
672     return 0;
673 }
674
675 static void _okChildString(const char* file, int line, const char* key, const char* expected)
676 {
677     char* result;
678     result=getChildString("Arguments", key);
679     ok_(file, line)(lstrcmpiA(result, expected) == 0,
680                     "%s expected '%s', got '%s'\n", key, expected, result);
681 }
682
683 static void _okChildPath(const char* file, int line, const char* key, const char* expected)
684 {
685     char* result;
686     result=getChildString("Arguments", key);
687     ok_(file, line)(StrCmpPath(result, expected) == 0,
688                     "%s expected '%s', got '%s'\n", key, expected, result);
689 }
690
691 static void _okChildInt(const char* file, int line, const char* key, int expected)
692 {
693     INT result;
694     result=GetPrivateProfileIntA("Arguments", key, expected, child_file);
695     ok_(file, line)(result == expected,
696                     "%s expected %d, but got %d\n", key, expected, result);
697 }
698
699 #define okChildString(key, expected) _okChildString(__FILE__, __LINE__, (key), (expected))
700 #define okChildPath(key, expected) _okChildPath(__FILE__, __LINE__, (key), (expected))
701 #define okChildInt(key, expected)    _okChildInt(__FILE__, __LINE__, (key), (expected))
702
703 /***
704  *
705  * GetLongPathNameA equivalent that supports Win95 and WinNT
706  *
707  ***/
708
709 static DWORD get_long_path_name(const char* shortpath, char* longpath, DWORD longlen)
710 {
711     char tmplongpath[MAX_PATH];
712     const char* p;
713     DWORD sp = 0, lp = 0;
714     DWORD tmplen;
715     WIN32_FIND_DATAA wfd;
716     HANDLE goit;
717
718     if (!shortpath || !shortpath[0])
719         return 0;
720
721     if (shortpath[1] == ':')
722     {
723         tmplongpath[0] = shortpath[0];
724         tmplongpath[1] = ':';
725         lp = sp = 2;
726     }
727
728     while (shortpath[sp])
729     {
730         /* check for path delimiters and reproduce them */
731         if (shortpath[sp] == '\\' || shortpath[sp] == '/')
732         {
733             if (!lp || tmplongpath[lp-1] != '\\')
734             {
735                 /* strip double "\\" */
736                 tmplongpath[lp++] = '\\';
737             }
738             tmplongpath[lp] = 0; /* terminate string */
739             sp++;
740             continue;
741         }
742
743         p = shortpath + sp;
744         if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
745         {
746             tmplongpath[lp++] = *p++;
747             tmplongpath[lp++] = *p++;
748         }
749         for (; *p && *p != '/' && *p != '\\'; p++);
750         tmplen = p - (shortpath + sp);
751         lstrcpyn(tmplongpath + lp, shortpath + sp, tmplen + 1);
752         /* Check if the file exists and use the existing file name */
753         goit = FindFirstFileA(tmplongpath, &wfd);
754         if (goit == INVALID_HANDLE_VALUE)
755             return 0;
756         FindClose(goit);
757         strcpy(tmplongpath + lp, wfd.cFileName);
758         lp += strlen(tmplongpath + lp);
759         sp += tmplen;
760     }
761     tmplen = strlen(shortpath) - 1;
762     if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
763         (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
764         tmplongpath[lp++] = shortpath[tmplen];
765     tmplongpath[lp] = 0;
766
767     tmplen = strlen(tmplongpath) + 1;
768     if (tmplen <= longlen)
769     {
770         strcpy(longpath, tmplongpath);
771         tmplen--; /* length without 0 */
772     }
773
774     return tmplen;
775 }
776
777 /***
778  *
779  * Tests
780  *
781  ***/
782
783 static const char* testfiles[]=
784 {
785     "%s\\test file.shlexec",
786     "%s\\%%nasty%% $file.shlexec",
787     "%s\\test file.noassoc",
788     "%s\\test file.noassoc.shlexec",
789     "%s\\test file.shlexec.noassoc",
790     "%s\\test_shortcut_shlexec.lnk",
791     "%s\\test_shortcut_exe.lnk",
792     "%s\\test file.shl",
793     "%s\\test file.shlfoo",
794     "%s\\test file.sfe",
795     "%s\\masked file.shlexec",
796     "%s\\masked",
797     "%s\\test file.sde",
798     "%s\\test file.exe",
799     "%s\\test2.exe",
800     "%s\\simple.shlexec",
801     "%s\\drawback_file.noassoc",
802     "%s\\drawback_file.noassoc foo.shlexec",
803     "%s\\drawback_nonexist.noassoc foo.shlexec",
804     NULL
805 };
806
807 typedef struct
808 {
809     const char* verb;
810     const char* basename;
811     int todo;
812     int rc;
813 } filename_tests_t;
814
815 static filename_tests_t filename_tests[]=
816 {
817     /* Test bad / nonexistent filenames */
818     {NULL,           "%s\\nonexistent.shlexec", 0x0, SE_ERR_FNF},
819     {NULL,           "%s\\nonexistent.noassoc", 0x0, SE_ERR_FNF},
820
821     /* Standard tests */
822     {NULL,           "%s\\test file.shlexec",   0x0, 33},
823     {NULL,           "%s\\test file.shlexec.",  0x0, 33},
824     {NULL,           "%s\\%%nasty%% $file.shlexec", 0x0, 33},
825     {NULL,           "%s/test file.shlexec",    0x0, 33},
826
827     /* Test filenames with no association */
828     {NULL,           "%s\\test file.noassoc",   0x0,  SE_ERR_NOASSOC},
829
830     /* Test double extensions */
831     {NULL,           "%s\\test file.noassoc.shlexec", 0x0, 33},
832     {NULL,           "%s\\test file.shlexec.noassoc", 0x0, SE_ERR_NOASSOC},
833
834     /* Test alternate verbs */
835     {"LowerL",       "%s\\nonexistent.shlexec", 0x0, SE_ERR_FNF},
836     {"LowerL",       "%s\\test file.noassoc",   0x0,  SE_ERR_NOASSOC},
837
838     {"QuotedLowerL", "%s\\test file.shlexec",   0x0, 33},
839     {"QuotedUpperL", "%s\\test file.shlexec",   0x0, 33},
840
841     /* Test file masked due to space */
842     {NULL,           "%s\\masked file.shlexec",   0x1, 33},
843     /* Test if quoting prevents the masking */
844     {NULL,           "%s\\masked file.shlexec",   0x40, 33},
845
846     {NULL, NULL, 0}
847 };
848
849 static filename_tests_t noquotes_tests[]=
850 {
851     /* Test unquoted '%1' thingies */
852     {"NoQuotes",     "%s\\test file.shlexec",   0xa, 33},
853     {"LowerL",       "%s\\test file.shlexec",   0xa, 33},
854     {"UpperL",       "%s\\test file.shlexec",   0xa, 33},
855
856     {NULL, NULL, 0}
857 };
858
859 static void test_lpFile_parsed(void)
860 {
861     /* basename tmpdir */
862     const char* shorttmpdir;
863
864     const char *testfile;
865     char fileA[MAX_PATH];
866
867     int rc;
868
869     GetTempPathA(sizeof(fileA), fileA);
870     shorttmpdir = tmpdir + strlen(fileA);
871
872     /* ensure tmpdir is in %TEMP%: GetTempPath() can succeed even if TEMP is undefined */
873     SetEnvironmentVariableA("TEMP", fileA);
874
875     /* existing "drawback_file.noassoc" prevents finding "drawback_file.noassoc foo.shlexec" on wine */
876     testfile = "%s\\drawback_file.noassoc foo.shlexec";
877     sprintf(fileA, testfile, tmpdir);
878     rc=shell_execute(NULL, fileA, NULL, NULL);
879     todo_wine {
880         ok(rc>32,
881             "expected success (33), got %s (%d), lpFile: %s\n",
882             rc > 32 ? "success" : "failure", rc, fileA
883             );
884     }
885
886     /* if quoted, existing "drawback_file.noassoc" not prevents finding "drawback_file.noassoc foo.shlexec" on wine */
887     testfile = "\"%s\\drawback_file.noassoc foo.shlexec\"";
888     sprintf(fileA, testfile, tmpdir);
889     rc=shell_execute(NULL, fileA, NULL, NULL);
890     ok(rc>32 || broken(rc == 2) /* Win95/NT4 */,
891         "expected success (33), got %s (%d), lpFile: %s\n",
892         rc > 32 ? "success" : "failure", rc, fileA
893         );
894
895     /* error should be 2, not 31 */
896     testfile = "\"%s\\drawback_file.noassoc\" foo.shlexec";
897     sprintf(fileA, testfile, tmpdir);
898     rc=shell_execute(NULL, fileA, NULL, NULL);
899     ok(rc==2,
900         "expected failure (2), got %s (%d), lpFile: %s\n",
901         rc > 32 ? "success" : "failure", rc, fileA
902         );
903
904     /* ""command"" not works on wine (and real win9x and w2k) */
905     testfile = "\"\"%s\\simple.shlexec\"\"";
906     sprintf(fileA, testfile, tmpdir);
907     rc=shell_execute(NULL, fileA, NULL, NULL);
908     todo_wine {
909         ok(rc>32 || broken(rc == 2) /* Win9x/2000 */,
910             "expected success (33), got %s (%d), lpFile: %s\n",
911             rc > 32 ? "success" : "failure", rc, fileA
912             );
913     }
914
915     /* nonexisting "drawback_nonexist.noassoc" not prevents finding "drawback_nonexist.noassoc foo.shlexec" on wine */
916     testfile = "%s\\drawback_nonexist.noassoc foo.shlexec";
917     sprintf(fileA, testfile, tmpdir);
918     rc=shell_execute(NULL, fileA, NULL, NULL);
919     ok(rc>32,
920         "expected success (33), got %s (%d), lpFile: %s\n",
921         rc > 32 ? "success" : "failure", rc, fileA
922         );
923
924     /* is SEE_MASK_DOENVSUBST default flag? Should only be when XP emulates 9x (XP bug or real 95 or ME behavior ?) */
925     testfile = "%%TEMP%%\\%s\\simple.shlexec";
926     sprintf(fileA, testfile, shorttmpdir);
927     rc=shell_execute(NULL, fileA, NULL, NULL);
928     todo_wine {
929         ok(rc==2,
930             "expected failure (2), got %s (%d), lpFile: %s\n",
931             rc > 32 ? "success" : "failure", rc, fileA
932             );
933     }
934
935     /* quoted */
936     testfile = "\"%%TEMP%%\\%s\\simple.shlexec\"";
937     sprintf(fileA, testfile, shorttmpdir);
938     rc=shell_execute(NULL, fileA, NULL, NULL);
939     todo_wine {
940         ok(rc==2,
941             "expected failure (2), got %s (%d), lpFile: %s\n",
942             rc > 32 ? "success" : "failure", rc, fileA
943             );
944     }
945
946     /* test SEE_MASK_DOENVSUBST works */
947     testfile = "%%TEMP%%\\%s\\simple.shlexec";
948     sprintf(fileA, testfile, shorttmpdir);
949     rc=shell_execute_ex(SEE_MASK_DOENVSUBST | SEE_MASK_FLAG_NO_UI, NULL, fileA, NULL, NULL);
950     ok(rc>32,
951         "expected success (33), got %s (%d), lpFile: %s\n",
952         rc > 32 ? "success" : "failure", rc, fileA
953         );
954
955     /* quoted lpFile not works only on real win95 and nt4 */
956     testfile = "\"%%TEMP%%\\%s\\simple.shlexec\"";
957     sprintf(fileA, testfile, shorttmpdir);
958     rc=shell_execute_ex(SEE_MASK_DOENVSUBST | SEE_MASK_FLAG_NO_UI, NULL, fileA, NULL, NULL);
959     ok(rc>32 || broken(rc == 2) /* Win95/NT4 */,
960         "expected success (33), got %s (%d), lpFile: %s\n",
961         rc > 32 ? "success" : "failure", rc, fileA
962         );
963
964 }
965
966 static void test_argify(void)
967 {
968     char fileA[MAX_PATH];
969
970     int rc;
971
972     sprintf(fileA, "%s\\test file.shlexec", tmpdir);
973
974     /* %2 */
975     rc=shell_execute("NoQuotesParam2", fileA, "a b", NULL);
976     ok(rc>32,
977         "expected success (33), got %s (%d), lpFile: %s\n",
978         rc > 32 ? "success" : "failure", rc, fileA
979         );
980     if (rc>32)
981     {
982         okChildInt("argcA", 5);
983         okChildString("argvA4", "a");
984     }
985
986     /* %2 */
987     /* '"a"""'   -> 'a"' */
988     rc=shell_execute("NoQuotesParam2", fileA, "\"a:\"\"some string\"\"\"", NULL);
989     ok(rc>32,
990         "expected success (33), got %s (%d), lpFile: %s\n",
991         rc > 32 ? "success" : "failure", rc, fileA
992         );
993     if (rc>32)
994     {
995         okChildInt("argcA", 5);
996         todo_wine {
997             okChildString("argvA4", "a:some string");
998         }
999     }
1000
1001     /* %2 */
1002     /* backslash isn't escape char
1003      * '"a\""'   -> '"a\""' */
1004     rc=shell_execute("NoQuotesParam2", fileA, "\"a:\\\"some string\\\"\"", NULL);
1005     ok(rc>32,
1006         "expected success (33), got %s (%d), lpFile: %s\n",
1007         rc > 32 ? "success" : "failure", rc, fileA
1008         );
1009     if (rc>32)
1010     {
1011         okChildInt("argcA", 5);
1012         todo_wine {
1013             okChildString("argvA4", "a:\\");
1014         }
1015     }
1016
1017     /* "%2" */
1018     /* \t isn't whitespace */
1019     rc=shell_execute("QuotedParam2", fileA, "a\tb c", NULL);
1020     ok(rc>32,
1021         "expected success (33), got %s (%d), lpFile: %s\n",
1022         rc > 32 ? "success" : "failure", rc, fileA
1023         );
1024     if (rc>32)
1025     {
1026         okChildInt("argcA", 5);
1027         todo_wine {
1028             okChildString("argvA4", "a\tb");
1029         }
1030     }
1031
1032     /* %* */
1033     rc=shell_execute("NoQuotesAllParams", fileA, "a b c d e f g h", NULL);
1034     ok(rc>32,
1035         "expected success (33), got %s (%d), lpFile: %s\n",
1036         rc > 32 ? "success" : "failure", rc, fileA
1037         );
1038     if (rc>32)
1039     {
1040         todo_wine {
1041             okChildInt("argcA", 12);
1042             okChildString("argvA4", "a");
1043             okChildString("argvA11", "h");
1044         }
1045     }
1046
1047     /* %* can sometimes contain only whitespaces and no args */
1048     rc=shell_execute("QuotedAllParams", fileA, "   ", NULL);
1049     ok(rc>32,
1050         "expected success (33), got %s (%d), lpFile: %s\n",
1051         rc > 32 ? "success" : "failure", rc, fileA
1052         );
1053     if (rc>32)
1054     {
1055         todo_wine {
1056             okChildInt("argcA", 5);
1057             okChildString("argvA4", "   ");
1058         }
1059     }
1060
1061     /* %~3 */
1062     rc=shell_execute("NoQuotesParams345etc", fileA, "a b c d e f g h", NULL);
1063     ok(rc>32,
1064         "expected success (33), got %s (%d), lpFile: %s\n",
1065         rc > 32 ? "success" : "failure", rc, fileA
1066         );
1067     if (rc>32)
1068     {
1069         todo_wine {
1070             okChildInt("argcA", 11);
1071             okChildString("argvA4", "b");
1072             okChildString("argvA10", "h");
1073         }
1074     }
1075
1076     /* %~3 is rest of command line starting with whitespaces after 2nd arg */
1077     rc=shell_execute("QuotedParams345etc", fileA, "a    ", NULL);
1078     ok(rc>32,
1079         "expected success (33), got %s (%d), lpFile: %s\n",
1080         rc > 32 ? "success" : "failure", rc, fileA
1081         );
1082     if (rc>32)
1083     {
1084         okChildInt("argcA", 5);
1085         todo_wine {
1086             okChildString("argvA4", "    ");
1087         }
1088     }
1089
1090 }
1091
1092 static void test_filename(void)
1093 {
1094     char filename[MAX_PATH];
1095     const filename_tests_t* test;
1096     char* c;
1097     int rc;
1098
1099     test=filename_tests;
1100     while (test->basename)
1101     {
1102         BOOL quotedfile = FALSE;
1103
1104         if (skip_noassoc_tests && test->rc == SE_ERR_NOASSOC)
1105         {
1106             win_skip("Skipping shellexecute of file with unassociated extension\n");
1107             test++;
1108             continue;
1109         }
1110
1111         sprintf(filename, test->basename, tmpdir);
1112         if (strchr(filename, '/'))
1113         {
1114             c=filename;
1115             while (*c)
1116             {
1117                 if (*c=='\\')
1118                     *c='/';
1119                 c++;
1120             }
1121         }
1122         if ((test->todo & 0x40)==0)
1123         {
1124             rc=shell_execute(test->verb, filename, NULL, NULL);
1125         }
1126         else
1127         {
1128             char quoted[MAX_PATH + 2];
1129
1130             quotedfile = TRUE;
1131             sprintf(quoted, "\"%s\"", filename);
1132             rc=shell_execute(test->verb, quoted, NULL, NULL);
1133         }
1134         if (rc > 32)
1135             rc=33;
1136         if ((test->todo & 0x1)==0)
1137         {
1138             ok(rc==test->rc ||
1139                broken(quotedfile && rc == 2), /* NT4 */
1140                "%s failed: rc=%d err=%d\n", shell_call,
1141                rc, GetLastError());
1142         }
1143         else todo_wine
1144         {
1145             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1146                rc, GetLastError());
1147         }
1148         if (rc == 33)
1149         {
1150             const char* verb;
1151             if ((test->todo & 0x2)==0)
1152             {
1153                 okChildInt("argcA", 5);
1154             }
1155             else todo_wine
1156             {
1157                 okChildInt("argcA", 5);
1158             }
1159             verb=(test->verb ? test->verb : "Open");
1160             if ((test->todo & 0x4)==0)
1161             {
1162                 okChildString("argvA3", verb);
1163             }
1164             else todo_wine
1165             {
1166                 okChildString("argvA3", verb);
1167             }
1168             if ((test->todo & 0x8)==0)
1169             {
1170                 okChildPath("argvA4", filename);
1171             }
1172             else todo_wine
1173             {
1174                 okChildPath("argvA4", filename);
1175             }
1176         }
1177         test++;
1178     }
1179
1180     test=noquotes_tests;
1181     while (test->basename)
1182     {
1183         sprintf(filename, test->basename, tmpdir);
1184         rc=shell_execute(test->verb, filename, NULL, NULL);
1185         if (rc > 32)
1186             rc=33;
1187         if ((test->todo & 0x1)==0)
1188         {
1189             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1190                rc, GetLastError());
1191         }
1192         else todo_wine
1193         {
1194             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1195                rc, GetLastError());
1196         }
1197         if (rc==0)
1198         {
1199             int count;
1200             const char* verb;
1201             char* str;
1202
1203             verb=(test->verb ? test->verb : "Open");
1204             if ((test->todo & 0x4)==0)
1205             {
1206                 okChildString("argvA3", verb);
1207             }
1208             else todo_wine
1209             {
1210                 okChildString("argvA3", verb);
1211             }
1212
1213             count=4;
1214             str=filename;
1215             while (1)
1216             {
1217                 char attrib[18];
1218                 char* space;
1219                 space=strchr(str, ' ');
1220                 if (space)
1221                     *space='\0';
1222                 sprintf(attrib, "argvA%d", count);
1223                 if ((test->todo & 0x8)==0)
1224                 {
1225                     okChildPath(attrib, str);
1226                 }
1227                 else todo_wine
1228                 {
1229                     okChildPath(attrib, str);
1230                 }
1231                 count++;
1232                 if (!space)
1233                     break;
1234                 str=space+1;
1235             }
1236             if ((test->todo & 0x2)==0)
1237             {
1238                 okChildInt("argcA", count);
1239             }
1240             else todo_wine
1241             {
1242                 okChildInt("argcA", count);
1243             }
1244         }
1245         test++;
1246     }
1247
1248     if (dllver.dwMajorVersion != 0)
1249     {
1250         /* The more recent versions of shell32.dll accept quoted filenames
1251          * while older ones (e.g. 4.00) don't. Still we want to test this
1252          * because IE 6 depends on the new behavior.
1253          * One day we may need to check the exact version of the dll but for
1254          * now making sure DllGetVersion() is present is sufficient.
1255          */
1256         sprintf(filename, "\"%s\\test file.shlexec\"", tmpdir);
1257         rc=shell_execute(NULL, filename, NULL, NULL);
1258         ok(rc > 32, "%s failed: rc=%d err=%d\n", shell_call, rc,
1259            GetLastError());
1260         okChildInt("argcA", 5);
1261         okChildString("argvA3", "Open");
1262         sprintf(filename, "%s\\test file.shlexec", tmpdir);
1263         okChildPath("argvA4", filename);
1264     }
1265 }
1266
1267 static void test_find_executable(void)
1268 {
1269     char filename[MAX_PATH];
1270     char command[MAX_PATH];
1271     const filename_tests_t* test;
1272     INT_PTR rc;
1273
1274     if (!create_test_association(".sfe"))
1275     {
1276         skip("Unable to create association for '.sfe'\n");
1277         return;
1278     }
1279     create_test_verb(".sfe", "Open", 1, "%1");
1280
1281     /* Don't test FindExecutable(..., NULL), it always crashes */
1282
1283     strcpy(command, "your word");
1284     if (0) /* Can crash on Vista! */
1285     {
1286     rc=(INT_PTR)FindExecutableA(NULL, NULL, command);
1287     ok(rc == SE_ERR_FNF || rc > 32 /* nt4 */, "FindExecutable(NULL) returned %ld\n", rc);
1288     ok(strcmp(command, "your word") != 0, "FindExecutable(NULL) returned command=[%s]\n", command);
1289     }
1290
1291     strcpy(command, "your word");
1292     rc=(INT_PTR)FindExecutableA(tmpdir, NULL, command);
1293     ok(rc == SE_ERR_NOASSOC /* >= win2000 */ || rc > 32 /* win98, nt4 */, "FindExecutable(NULL) returned %ld\n", rc);
1294     ok(strcmp(command, "your word") != 0, "FindExecutable(NULL) returned command=[%s]\n", command);
1295
1296     sprintf(filename, "%s\\test file.sfe", tmpdir);
1297     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1298     ok(rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1299     /* Depending on the platform, command could be '%1' or 'test file.sfe' */
1300
1301     rc=(INT_PTR)FindExecutableA("test file.sfe", tmpdir, command);
1302     ok(rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1303
1304     rc=(INT_PTR)FindExecutableA("test file.sfe", NULL, command);
1305     ok(rc == SE_ERR_FNF, "FindExecutable(%s) returned %ld\n", filename, rc);
1306
1307     delete_test_association(".sfe");
1308
1309     if (!create_test_association(".shl"))
1310     {
1311         skip("Unable to create association for '.shl'\n");
1312         return;
1313     }
1314     create_test_verb(".shl", "Open", 0, "Open");
1315
1316     sprintf(filename, "%s\\test file.shl", tmpdir);
1317     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1318     ok(rc == SE_ERR_FNF /* NT4 */ || rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1319
1320     sprintf(filename, "%s\\test file.shlfoo", tmpdir);
1321     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1322
1323     delete_test_association(".shl");
1324
1325     if (rc > 32)
1326     {
1327         /* On Windows XP and 2003 FindExecutable() is completely broken.
1328          * Probably what it does is convert the filename to 8.3 format,
1329          * which as a side effect converts the '.shlfoo' extension to '.shl',
1330          * and then tries to find an association for '.shl'. This means it
1331          * will normally fail on most extensions with more than 3 characters,
1332          * like '.mpeg', etc.
1333          * Also it means we cannot do any other test.
1334          */
1335         win_skip("FindExecutable() is broken -> not running 4+ character extension tests\n");
1336         return;
1337     }
1338
1339     test=filename_tests;
1340     while (test->basename)
1341     {
1342         sprintf(filename, test->basename, tmpdir);
1343         if (strchr(filename, '/'))
1344         {
1345             char* c;
1346             c=filename;
1347             while (*c)
1348             {
1349                 if (*c=='\\')
1350                     *c='/';
1351                 c++;
1352             }
1353         }
1354         /* Win98 does not '\0'-terminate command! */
1355         memset(command, '\0', sizeof(command));
1356         rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1357         if (rc > 32)
1358             rc=33;
1359         if ((test->todo & 0x10)==0)
1360         {
1361             ok(rc==test->rc, "FindExecutable(%s) failed: rc=%ld\n", filename, rc);
1362         }
1363         else todo_wine
1364         {
1365             ok(rc==test->rc, "FindExecutable(%s) failed: rc=%ld\n", filename, rc);
1366         }
1367         if (rc > 32)
1368         {
1369             int equal;
1370             equal=strcmp(command, argv0) == 0 ||
1371                 /* NT4 returns an extra 0x8 character! */
1372                 (strlen(command) == strlen(argv0)+1 && strncmp(command, argv0, strlen(argv0)) == 0);
1373             if ((test->todo & 0x20)==0)
1374             {
1375                 ok(equal, "FindExecutable(%s) returned command='%s' instead of '%s'\n",
1376                    filename, command, argv0);
1377             }
1378             else todo_wine
1379             {
1380                 ok(equal, "FindExecutable(%s) returned command='%s' instead of '%s'\n",
1381                    filename, command, argv0);
1382             }
1383         }
1384         test++;
1385     }
1386 }
1387
1388
1389 static filename_tests_t lnk_tests[]=
1390 {
1391     /* Pass bad / nonexistent filenames as a parameter */
1392     {NULL, "%s\\nonexistent.shlexec",    0xa, 33},
1393     {NULL, "%s\\nonexistent.noassoc",    0xa, 33},
1394
1395     /* Pass regular paths as a parameter */
1396     {NULL, "%s\\test file.shlexec",      0xa, 33},
1397     {NULL, "%s/%%nasty%% $file.shlexec", 0xa, 33},
1398
1399     /* Pass filenames with no association as a parameter */
1400     {NULL, "%s\\test file.noassoc",      0xa, 33},
1401
1402     {NULL, NULL, 0}
1403 };
1404
1405 static void test_lnks(void)
1406 {
1407     char filename[MAX_PATH];
1408     char params[MAX_PATH];
1409     const filename_tests_t* test;
1410     int rc;
1411
1412     sprintf(filename, "%s\\test_shortcut_shlexec.lnk", tmpdir);
1413     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL);
1414     ok(rc > 32, "%s failed: rc=%d err=%d\n", shell_call, rc,
1415        GetLastError());
1416     okChildInt("argcA", 5);
1417     okChildString("argvA3", "Open");
1418     sprintf(params, "%s\\test file.shlexec", tmpdir);
1419     get_long_path_name(params, filename, sizeof(filename));
1420     okChildPath("argvA4", filename);
1421
1422     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1423     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL);
1424     ok(rc > 32, "%s failed: rc=%d err=%d\n", shell_call, rc,
1425        GetLastError());
1426     okChildInt("argcA", 4);
1427     okChildString("argvA3", "Lnk");
1428
1429     if (dllver.dwMajorVersion>=6)
1430     {
1431         char* c;
1432        /* Recent versions of shell32.dll accept '/'s in shortcut paths.
1433          * Older versions don't or are quite buggy in this regard.
1434          */
1435         sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1436         c=filename;
1437         while (*c)
1438         {
1439             if (*c=='\\')
1440                 *c='/';
1441             c++;
1442         }
1443         rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL);
1444         ok(rc > 32, "%s failed: rc=%d err=%d\n", shell_call, rc,
1445            GetLastError());
1446         okChildInt("argcA", 4);
1447         okChildString("argvA3", "Lnk");
1448     }
1449
1450     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1451     test=lnk_tests;
1452     while (test->basename)
1453     {
1454         params[0]='\"';
1455         sprintf(params+1, test->basename, tmpdir);
1456         strcat(params,"\"");
1457         rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, params,
1458                             NULL);
1459         if (rc > 32)
1460             rc=33;
1461         if ((test->todo & 0x1)==0)
1462         {
1463             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1464                rc, GetLastError());
1465         }
1466         else todo_wine
1467         {
1468             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1469                rc, GetLastError());
1470         }
1471         if (rc==0)
1472         {
1473             if ((test->todo & 0x2)==0)
1474             {
1475                 okChildInt("argcA", 5);
1476             }
1477             else
1478             {
1479                 okChildInt("argcA", 5);
1480             }
1481             if ((test->todo & 0x4)==0)
1482             {
1483                 okChildString("argvA3", "Lnk");
1484             }
1485             else todo_wine
1486             {
1487                 okChildString("argvA3", "Lnk");
1488             }
1489             sprintf(params, test->basename, tmpdir);
1490             if ((test->todo & 0x8)==0)
1491             {
1492                 okChildPath("argvA4", params);
1493             }
1494             else
1495             {
1496                 okChildPath("argvA4", params);
1497             }
1498         }
1499         test++;
1500     }
1501 }
1502
1503
1504 static void test_exes(void)
1505 {
1506     char filename[MAX_PATH];
1507     char params[1024];
1508     int rc;
1509
1510     sprintf(params, "shlexec \"%s\" Exec", child_file);
1511
1512     /* We need NOZONECHECKS on Win2003 to block a dialog */
1513     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, argv0, params,
1514                         NULL);
1515     ok(rc > 32, "%s returned %d\n", shell_call, rc);
1516     okChildInt("argcA", 4);
1517     okChildString("argvA3", "Exec");
1518
1519     if (! skip_noassoc_tests)
1520     {
1521         sprintf(filename, "%s\\test file.noassoc", tmpdir);
1522         if (CopyFile(argv0, filename, FALSE))
1523         {
1524             rc=shell_execute(NULL, filename, params, NULL);
1525             todo_wine {
1526                 ok(rc==SE_ERR_NOASSOC, "%s succeeded: rc=%d\n", shell_call, rc);
1527             }
1528         }
1529     }
1530     else
1531     {
1532         win_skip("Skipping shellexecute of file with unassociated extension\n");
1533     }
1534 }
1535
1536 static void test_exes_long(void)
1537 {
1538     char filename[MAX_PATH];
1539     char params[2024];
1540     char longparam[MAX_PATH];
1541     int rc;
1542
1543     for (rc = 0; rc < MAX_PATH; rc++)
1544         longparam[rc]='a'+rc%26;
1545     longparam[MAX_PATH-1]=0;
1546
1547
1548     sprintf(params, "shlexec \"%s\" %s", child_file,longparam);
1549
1550     /* We need NOZONECHECKS on Win2003 to block a dialog */
1551     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, argv0, params,
1552                         NULL);
1553     ok(rc > 32, "%s returned %d\n", shell_call, rc);
1554     okChildInt("argcA", 4);
1555     okChildString("argvA3", longparam);
1556
1557     if (! skip_noassoc_tests)
1558     {
1559         sprintf(filename, "%s\\test file.noassoc", tmpdir);
1560         if (CopyFile(argv0, filename, FALSE))
1561         {
1562             rc=shell_execute(NULL, filename, params, NULL);
1563             todo_wine {
1564                 ok(rc==SE_ERR_NOASSOC, "%s succeeded: rc=%d\n", shell_call, rc);
1565             }
1566         }
1567     }
1568     else
1569     {
1570         win_skip("Skipping shellexecute of file with unassociated extension\n");
1571     }
1572 }
1573
1574 typedef struct
1575 {
1576     const char* command;
1577     const char* ddeexec;
1578     const char* application;
1579     const char* topic;
1580     const char* ifexec;
1581     int expectedArgs;
1582     const char* expectedDdeExec;
1583     int todo;
1584 } dde_tests_t;
1585
1586 static dde_tests_t dde_tests[] =
1587 {
1588     /* Test passing and not passing command-line
1589      * argument, no DDE */
1590     {"", NULL, NULL, NULL, NULL, FALSE, "", 0x0},
1591     {"\"%1\"", NULL, NULL, NULL, NULL, TRUE, "", 0x0},
1592
1593     /* Test passing and not passing command-line
1594      * argument, with DDE */
1595     {"", "[open(\"%1\")]", "shlexec", "dde", NULL, FALSE, "[open(\"%s\")]", 0x0},
1596     {"\"%1\"", "[open(\"%1\")]", "shlexec", "dde", NULL, TRUE, "[open(\"%s\")]", 0x0},
1597
1598     /* Test unquoted %1 in command and ddeexec
1599      * (test filename has space) */
1600     {"%1", "[open(%1)]", "shlexec", "dde", NULL, 2, "[open(%s)]", 0x0},
1601
1602     /* Test ifexec precedence over ddeexec */
1603     {"", "[open(\"%1\")]", "shlexec", "dde", "[ifexec(\"%1\")]", FALSE, "[ifexec(\"%s\")]", 0x0},
1604
1605     /* Test default DDE topic */
1606     {"", "[open(\"%1\")]", "shlexec", NULL, NULL, FALSE, "[open(\"%s\")]", 0x0},
1607
1608     /* Test default DDE application */
1609     {"", "[open(\"%1\")]", NULL, "dde", NULL, FALSE, "[open(\"%s\")]", 0x0},
1610
1611     {NULL, NULL, NULL, NULL, NULL, 0, 0x0}
1612 };
1613
1614 static DWORD WINAPI hooked_WaitForInputIdle(HANDLE process, DWORD timeout)
1615 {
1616     HANDLE dde_ready;
1617     DWORD wait_result;
1618
1619     dde_ready = CreateEventA(NULL, FALSE, FALSE, "winetest_shlexec_dde_ready");
1620     wait_result = WaitForSingleObject(dde_ready, timeout);
1621     CloseHandle(dde_ready);
1622
1623     return wait_result;
1624 }
1625
1626 /*
1627  * WaitForInputIdle() will normally return immediately for console apps. That's
1628  * a problem for us because ShellExecute will assume that an app is ready to
1629  * receive DDE messages after it has called WaitForInputIdle() on that app.
1630  * To work around that we install our own version of WaitForInputIdle() that
1631  * will wait for the child to explicitly tell us that it is ready. We do that
1632  * by changing the entry for WaitForInputIdle() in the shell32 import address
1633  * table.
1634  */
1635 static void hook_WaitForInputIdle(void *new_func)
1636 {
1637     char *base;
1638     PIMAGE_NT_HEADERS nt_headers;
1639     DWORD import_directory_rva;
1640     PIMAGE_IMPORT_DESCRIPTOR import_descriptor;
1641
1642     base = (char *) GetModuleHandleA("shell32.dll");
1643     nt_headers = (PIMAGE_NT_HEADERS)(base + ((PIMAGE_DOS_HEADER) base)->e_lfanew);
1644     import_directory_rva = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
1645
1646     /* Search for the correct imported module by walking the import descriptors */
1647     import_descriptor = (PIMAGE_IMPORT_DESCRIPTOR)(base + import_directory_rva);
1648     while (U(*import_descriptor).OriginalFirstThunk != 0)
1649     {
1650         char *import_module_name;
1651
1652         import_module_name = base + import_descriptor->Name;
1653         if (lstrcmpiA(import_module_name, "user32.dll") == 0 ||
1654             lstrcmpiA(import_module_name, "user32") == 0)
1655         {
1656             PIMAGE_THUNK_DATA int_entry;
1657             PIMAGE_THUNK_DATA iat_entry;
1658
1659             /* The import name table and import address table are two parallel
1660              * arrays. We need the import name table to find the imported
1661              * routine and the import address table to patch the address, so
1662              * walk them side by side */
1663             int_entry = (PIMAGE_THUNK_DATA)(base + U(*import_descriptor).OriginalFirstThunk);
1664             iat_entry = (PIMAGE_THUNK_DATA)(base + import_descriptor->FirstThunk);
1665             while (int_entry->u1.Ordinal != 0)
1666             {
1667                 if (! IMAGE_SNAP_BY_ORDINAL(int_entry->u1.Ordinal))
1668                 {
1669                     PIMAGE_IMPORT_BY_NAME import_by_name;
1670                     import_by_name = (PIMAGE_IMPORT_BY_NAME)(base + int_entry->u1.AddressOfData);
1671                     if (lstrcmpA((char *) import_by_name->Name, "WaitForInputIdle") == 0)
1672                     {
1673                         /* Found the correct routine in the correct imported module. Patch it. */
1674                         DWORD old_prot;
1675                         VirtualProtect(&iat_entry->u1.Function, sizeof(ULONG_PTR), PAGE_READWRITE, &old_prot);
1676                         iat_entry->u1.Function = (ULONG_PTR) new_func;
1677                         VirtualProtect(&iat_entry->u1.Function, sizeof(ULONG_PTR), old_prot, &old_prot);
1678                         break;
1679                     }
1680                 }
1681                 int_entry++;
1682                 iat_entry++;
1683             }
1684             break;
1685         }
1686
1687         import_descriptor++;
1688     }
1689 }
1690
1691 static void test_dde(void)
1692 {
1693     char filename[MAX_PATH], defApplication[MAX_PATH];
1694     const dde_tests_t* test;
1695     char params[1024];
1696     int rc;
1697     HANDLE map;
1698     char *shared_block;
1699
1700     hook_WaitForInputIdle((void *) hooked_WaitForInputIdle);
1701
1702     sprintf(filename, "%s\\test file.sde", tmpdir);
1703
1704     /* Default service is application name minus path and extension */
1705     strcpy(defApplication, strrchr(argv0, '\\')+1);
1706     *strchr(defApplication, '.') = 0;
1707
1708     map = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
1709                              4096, "winetest_shlexec_dde_map");
1710     shared_block = MapViewOfFile(map, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 4096);
1711
1712     test = dde_tests;
1713     while (test->command)
1714     {
1715         if (!create_test_association(".sde"))
1716         {
1717             skip("Unable to create association for '.sfe'\n");
1718             return;
1719         }
1720         create_test_verb_dde(".sde", "Open", 0, test->command, test->ddeexec,
1721                              test->application, test->topic, test->ifexec);
1722
1723         if (test->application != NULL || test->topic != NULL)
1724         {
1725             strcpy(shared_block, test->application ? test->application : defApplication);
1726             strcpy(shared_block + strlen(shared_block) + 1, test->topic ? test->topic : SZDDESYS_TOPIC);
1727         }
1728         else
1729         {
1730             shared_block[0] = '\0';
1731             shared_block[1] = '\0';
1732         }
1733         ddeExec[0] = 0;
1734
1735         rc = shell_execute_ex(SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI, NULL, filename, NULL, NULL);
1736         if ((test->todo & 0x1)==0)
1737         {
1738             ok(32 < rc, "%s failed: rc=%d err=%d\n", shell_call,
1739                rc, GetLastError());
1740         }
1741         else todo_wine
1742         {
1743             ok(32 < rc, "%s failed: rc=%d err=%d\n", shell_call,
1744                rc, GetLastError());
1745         }
1746         if (32 < rc)
1747         {
1748             if ((test->todo & 0x2)==0)
1749             {
1750                 okChildInt("argcA", test->expectedArgs + 3);
1751             }
1752             else todo_wine
1753             {
1754                 okChildInt("argcA", test->expectedArgs + 3);
1755             }
1756             if (test->expectedArgs == 1)
1757             {
1758                 if ((test->todo & 0x4) == 0)
1759                 {
1760                     okChildPath("argvA3", filename);
1761                 }
1762                 else todo_wine
1763                 {
1764                     okChildPath("argvA3", filename);
1765                 }
1766             }
1767             if ((test->todo & 0x8) == 0)
1768             {
1769                 sprintf(params, test->expectedDdeExec, filename);
1770                 okChildPath("ddeExec", params);
1771             }
1772             else todo_wine
1773             {
1774                 sprintf(params, test->expectedDdeExec, filename);
1775                 okChildPath("ddeExec", params);
1776             }
1777         }
1778
1779         delete_test_association(".sde");
1780         test++;
1781     }
1782
1783     UnmapViewOfFile(shared_block);
1784     CloseHandle(map);
1785     hook_WaitForInputIdle((void *) WaitForInputIdle);
1786 }
1787
1788 #define DDE_DEFAULT_APP_VARIANTS 2
1789 typedef struct
1790 {
1791     const char* command;
1792     const char* expectedDdeApplication[DDE_DEFAULT_APP_VARIANTS];
1793     int todo;
1794     int rc[DDE_DEFAULT_APP_VARIANTS];
1795 } dde_default_app_tests_t;
1796
1797 static dde_default_app_tests_t dde_default_app_tests[] =
1798 {
1799     /* Windows XP and 98 handle default DDE app names in different ways.
1800      * The application name we see in the first test determines the pattern
1801      * of application names and return codes we will look for. */
1802
1803     /* Test unquoted existing filename with a space */
1804     {"%s\\test file.exe", {"test file", "test"}, 0x0, {33, 33}},
1805     {"%s\\test file.exe param", {"test file", "test"}, 0x0, {33, 33}},
1806
1807     /* Test quoted existing filename with a space */
1808     {"\"%s\\test file.exe\"", {"test file", "test file"}, 0x0, {33, 33}},
1809     {"\"%s\\test file.exe\" param", {"test file", "test file"}, 0x0, {33, 33}},
1810
1811     /* Test unquoted filename with a space that doesn't exist, but
1812      * test2.exe does */
1813     {"%s\\test2 file.exe", {"test2", "test2"}, 0x0, {33, 33}},
1814     {"%s\\test2 file.exe param", {"test2", "test2"}, 0x0, {33, 33}},
1815
1816     /* Test quoted filename with a space that does not exist */
1817     {"\"%s\\test2 file.exe\"", {"", "test2 file"}, 0x0, {5, 33}},
1818     {"\"%s\\test2 file.exe\" param", {"", "test2 file"}, 0x0, {5, 33}},
1819
1820     /* Test filename supplied without the extension */
1821     {"%s\\test2", {"test2", "test2"}, 0x0, {33, 33}},
1822     {"%s\\test2 param", {"test2", "test2"}, 0x0, {33, 33}},
1823
1824     /* Test an unquoted nonexistent filename */
1825     {"%s\\notexist.exe", {"", "notexist"}, 0x0, {5, 33}},
1826     {"%s\\notexist.exe param", {"", "notexist"}, 0x0, {5, 33}},
1827
1828     /* Test an application that will be found on the path */
1829     {"cmd", {"cmd", "cmd"}, 0x0, {33, 33}},
1830     {"cmd param", {"cmd", "cmd"}, 0x0, {33, 33}},
1831
1832     /* Test an application that will not be found on the path */
1833     {"xyzwxyzwxyz", {"", "xyzwxyzwxyz"}, 0x0, {5, 33}},
1834     {"xyzwxyzwxyz param", {"", "xyzwxyzwxyz"}, 0x0, {5, 33}},
1835
1836     {NULL, {NULL}, 0, {0}}
1837 };
1838
1839 typedef struct
1840 {
1841     char *filename;
1842     DWORD threadIdParent;
1843 } dde_thread_info_t;
1844
1845 static DWORD CALLBACK ddeThread(LPVOID arg)
1846 {
1847     dde_thread_info_t *info = arg;
1848     assert(info && info->filename);
1849     PostThreadMessage(info->threadIdParent,
1850                       WM_QUIT,
1851                       shell_execute_ex(SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI, NULL, info->filename, NULL, NULL),
1852                       0L);
1853     ExitThread(0);
1854 }
1855
1856 static void test_dde_default_app(void)
1857 {
1858     char filename[MAX_PATH];
1859     HSZ hszApplication;
1860     dde_thread_info_t info = { filename, GetCurrentThreadId() };
1861     const dde_default_app_tests_t* test;
1862     char params[1024];
1863     DWORD threadId;
1864     MSG msg;
1865     int rc, which = 0;
1866
1867     post_quit_on_execute = FALSE;
1868     ddeInst = 0;
1869     rc = DdeInitializeA(&ddeInst, ddeCb, CBF_SKIP_ALLNOTIFICATIONS | CBF_FAIL_ADVISES |
1870                         CBF_FAIL_POKES | CBF_FAIL_REQUESTS, 0L);
1871     assert(rc == DMLERR_NO_ERROR);
1872
1873     sprintf(filename, "%s\\test file.sde", tmpdir);
1874
1875     /* It is strictly not necessary to register an application name here, but wine's
1876      * DdeNameService implementation complains if 0L is passed instead of
1877      * hszApplication with DNS_FILTEROFF */
1878     hszApplication = DdeCreateStringHandleA(ddeInst, "shlexec", CP_WINANSI);
1879     hszTopic = DdeCreateStringHandleA(ddeInst, "shlexec", CP_WINANSI);
1880     assert(hszApplication && hszTopic);
1881     assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_REGISTER | DNS_FILTEROFF));
1882
1883     test = dde_default_app_tests;
1884     while (test->command)
1885     {
1886         if (!create_test_association(".sde"))
1887         {
1888             skip("Unable to create association for '.sde'\n");
1889             return;
1890         }
1891         sprintf(params, test->command, tmpdir);
1892         create_test_verb_dde(".sde", "Open", 1, params, "[test]", NULL,
1893                              "shlexec", NULL);
1894         ddeApplication[0] = 0;
1895
1896         /* No application will be run as we will respond to the first DDE event,
1897          * so don't wait for it */
1898         SetEvent(hEvent);
1899
1900         assert(CreateThread(NULL, 0, ddeThread, &info, 0, &threadId));
1901         while (GetMessage(&msg, NULL, 0, 0)) DispatchMessage(&msg);
1902         rc = msg.wParam > 32 ? 33 : msg.wParam;
1903
1904         /* First test, find which set of test data we expect to see */
1905         if (test == dde_default_app_tests)
1906         {
1907             int i;
1908             for (i=0; i<DDE_DEFAULT_APP_VARIANTS; i++)
1909             {
1910                 if (!strcmp(ddeApplication, test->expectedDdeApplication[i]))
1911                 {
1912                     which = i;
1913                     break;
1914                 }
1915             }
1916             if (i == DDE_DEFAULT_APP_VARIANTS)
1917                 skip("Default DDE application test does not match any available results, using first expected data set.\n");
1918         }
1919
1920         if ((test->todo & 0x1)==0)
1921         {
1922             ok(rc==test->rc[which], "%s failed: rc=%d err=%d\n", shell_call,
1923                rc, GetLastError());
1924         }
1925         else todo_wine
1926         {
1927             ok(rc==test->rc[which], "%s failed: rc=%d err=%d\n", shell_call,
1928                rc, GetLastError());
1929         }
1930         if (rc == 33)
1931         {
1932             if ((test->todo & 0x2)==0)
1933             {
1934                 ok(!strcmp(ddeApplication, test->expectedDdeApplication[which]),
1935                    "Expected application '%s', got '%s'\n",
1936                    test->expectedDdeApplication[which], ddeApplication);
1937             }
1938             else todo_wine
1939             {
1940                 ok(!strcmp(ddeApplication, test->expectedDdeApplication[which]),
1941                    "Expected application '%s', got '%s'\n",
1942                    test->expectedDdeApplication[which], ddeApplication);
1943             }
1944         }
1945
1946         delete_test_association(".sde");
1947         test++;
1948     }
1949
1950     assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_UNREGISTER));
1951     assert(DdeFreeStringHandle(ddeInst, hszTopic));
1952     assert(DdeFreeStringHandle(ddeInst, hszApplication));
1953     assert(DdeUninitialize(ddeInst));
1954 }
1955
1956 static void init_test(void)
1957 {
1958     HMODULE hdll;
1959     HRESULT (WINAPI *pDllGetVersion)(DLLVERSIONINFO*);
1960     char filename[MAX_PATH];
1961     WCHAR lnkfile[MAX_PATH];
1962     char params[1024];
1963     const char* const * testfile;
1964     lnk_desc_t desc;
1965     DWORD rc;
1966     HRESULT r;
1967
1968     hdll=GetModuleHandleA("shell32.dll");
1969     pDllGetVersion=(void*)GetProcAddress(hdll, "DllGetVersion");
1970     if (pDllGetVersion)
1971     {
1972         dllver.cbSize=sizeof(dllver);
1973         pDllGetVersion(&dllver);
1974         trace("major=%d minor=%d build=%d platform=%d\n",
1975               dllver.dwMajorVersion, dllver.dwMinorVersion,
1976               dllver.dwBuildNumber, dllver.dwPlatformID);
1977     }
1978     else
1979     {
1980         memset(&dllver, 0, sizeof(dllver));
1981     }
1982
1983     r = CoInitialize(NULL);
1984     ok(r == S_OK, "CoInitialize failed (0x%08x)\n", r);
1985     if (FAILED(r))
1986         exit(1);
1987
1988     rc=GetModuleFileName(NULL, argv0, sizeof(argv0));
1989     assert(rc!=0 && rc<sizeof(argv0));
1990     if (GetFileAttributes(argv0)==INVALID_FILE_ATTRIBUTES)
1991     {
1992         strcat(argv0, ".so");
1993         ok(GetFileAttributes(argv0)!=INVALID_FILE_ATTRIBUTES,
1994            "unable to find argv0!\n");
1995     }
1996
1997     GetTempPathA(sizeof(filename), filename);
1998     GetTempFileNameA(filename, "wt", 0, tmpdir);
1999     DeleteFileA( tmpdir );
2000     rc = CreateDirectoryA( tmpdir, NULL );
2001     ok( rc, "failed to create %s err %u\n", tmpdir, GetLastError() );
2002     rc = GetTempFileNameA(tmpdir, "wt", 0, child_file);
2003     assert(rc != 0);
2004     init_event(child_file);
2005
2006     /* Set up the test files */
2007     testfile=testfiles;
2008     while (*testfile)
2009     {
2010         HANDLE hfile;
2011
2012         sprintf(filename, *testfile, tmpdir);
2013         hfile=CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
2014                      FILE_ATTRIBUTE_NORMAL, NULL);
2015         if (hfile==INVALID_HANDLE_VALUE)
2016         {
2017             trace("unable to create '%s': err=%d\n", filename, GetLastError());
2018             assert(0);
2019         }
2020         CloseHandle(hfile);
2021         testfile++;
2022     }
2023
2024     /* Setup the test shortcuts */
2025     sprintf(filename, "%s\\test_shortcut_shlexec.lnk", tmpdir);
2026     MultiByteToWideChar(CP_ACP, 0, filename, -1, lnkfile, sizeof(lnkfile)/sizeof(*lnkfile));
2027     desc.description=NULL;
2028     desc.workdir=NULL;
2029     sprintf(filename, "%s\\test file.shlexec", tmpdir);
2030     desc.path=filename;
2031     desc.pidl=NULL;
2032     desc.arguments="ignored";
2033     desc.showcmd=0;
2034     desc.icon=NULL;
2035     desc.icon_id=0;
2036     desc.hotkey=0;
2037     create_lnk(lnkfile, &desc, 0);
2038
2039     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
2040     MultiByteToWideChar(CP_ACP, 0, filename, -1, lnkfile, sizeof(lnkfile)/sizeof(*lnkfile));
2041     desc.description=NULL;
2042     desc.workdir=NULL;
2043     desc.path=argv0;
2044     desc.pidl=NULL;
2045     sprintf(params, "shlexec \"%s\" Lnk", child_file);
2046     desc.arguments=params;
2047     desc.showcmd=0;
2048     desc.icon=NULL;
2049     desc.icon_id=0;
2050     desc.hotkey=0;
2051     create_lnk(lnkfile, &desc, 0);
2052
2053     /* Create a basic association suitable for most tests */
2054     if (!create_test_association(".shlexec"))
2055     {
2056         skip("Unable to create association for '.shlexec'\n");
2057         return;
2058     }
2059     create_test_verb(".shlexec", "Open", 0, "Open \"%1\"");
2060     create_test_verb(".shlexec", "NoQuotes", 0, "NoQuotes %1");
2061     create_test_verb(".shlexec", "LowerL", 0, "LowerL %l");
2062     create_test_verb(".shlexec", "QuotedLowerL", 0, "QuotedLowerL \"%l\"");
2063     create_test_verb(".shlexec", "UpperL", 0, "UpperL %L");
2064     create_test_verb(".shlexec", "QuotedUpperL", 0, "QuotedUpperL \"%L\"");
2065
2066     create_test_verb(".shlexec", "NoQuotesParam2", 0, "NoQuotesParam2 %2");
2067     create_test_verb(".shlexec", "QuotedParam2", 0, "QuotedParam2 \"%2\"");
2068
2069     create_test_verb(".shlexec", "NoQuotesAllParams", 0, "NoQuotesAllParams %*");
2070     create_test_verb(".shlexec", "QuotedAllParams", 0, "QuotedAllParams \"%*\"");
2071
2072     create_test_verb(".shlexec", "NoQuotesParams345etc", 0, "NoQuotesParams345etc %~3");
2073     create_test_verb(".shlexec", "QuotedParams345etc", 0, "QuotedParams345etc \"%~3\"");
2074 }
2075
2076 static void cleanup_test(void)
2077 {
2078     char filename[MAX_PATH];
2079     const char* const * testfile;
2080
2081     /* Delete the test files */
2082     testfile=testfiles;
2083     while (*testfile)
2084     {
2085         sprintf(filename, *testfile, tmpdir);
2086         /* Make sure we can delete the files ('test file.noassoc' is read-only now) */
2087         SetFileAttributes(filename, FILE_ATTRIBUTE_NORMAL);
2088         DeleteFile(filename);
2089         testfile++;
2090     }
2091     DeleteFile(child_file);
2092     RemoveDirectoryA(tmpdir);
2093
2094     /* Delete the test association */
2095     delete_test_association(".shlexec");
2096
2097     CloseHandle(hEvent);
2098
2099     CoUninitialize();
2100 }
2101
2102 static void test_commandline(void)
2103 {
2104     static const WCHAR one[] = {'o','n','e',0};
2105     static const WCHAR two[] = {'t','w','o',0};
2106     static const WCHAR three[] = {'t','h','r','e','e',0};
2107     static const WCHAR four[] = {'f','o','u','r',0};
2108
2109     static const WCHAR fmt1[] = {'%','s',' ','%','s',' ','%','s',' ','%','s',0};
2110     static const WCHAR fmt2[] = {' ','%','s',' ','%','s',' ','%','s',' ','%','s',0};
2111     static const WCHAR fmt3[] = {'%','s','=','%','s',' ','%','s','=','\"','%','s','\"',0};
2112     static const WCHAR fmt4[] = {'\"','%','s','\"',' ','\"','%','s',' ','%','s','\"',' ','%','s',0};
2113     static const WCHAR fmt5[] = {'\\','\"','%','s','\"',' ','%','s','=','\"','%','s','\\','\"',' ','\"','%','s','\\','\"',0};
2114     static const WCHAR fmt6[] = {0};
2115
2116     static const WCHAR chkfmt1[] = {'%','s','=','%','s',0};
2117     static const WCHAR chkfmt2[] = {'%','s',' ','%','s',0};
2118     static const WCHAR chkfmt3[] = {'\\','\"','%','s','\"',0};
2119     static const WCHAR chkfmt4[] = {'%','s','=','%','s','\"',' ','%','s','\"',0};
2120     WCHAR cmdline[255];
2121     LPWSTR *args = (LPWSTR*)0xdeadcafe;
2122     INT numargs = -1;
2123
2124     wsprintfW(cmdline,fmt1,one,two,three,four);
2125     args=CommandLineToArgvW(cmdline,&numargs);
2126     if (args == NULL && numargs == -1)
2127     {
2128         win_skip("CommandLineToArgvW not implemented, skipping\n");
2129         return;
2130     }
2131     ok(numargs == 4, "expected 4 args, got %i\n",numargs);
2132     ok(lstrcmpW(args[0],one)==0,"arg0 is not as expected\n");
2133     ok(lstrcmpW(args[1],two)==0,"arg1 is not as expected\n");
2134     ok(lstrcmpW(args[2],three)==0,"arg2 is not as expected\n");
2135     ok(lstrcmpW(args[3],four)==0,"arg3 is not as expected\n");
2136
2137     wsprintfW(cmdline,fmt2,one,two,three,four);
2138     args=CommandLineToArgvW(cmdline,&numargs);
2139     ok(numargs == 5, "expected 5 args, got %i\n",numargs);
2140     ok(args[0][0]==0,"arg0 is not as expected\n");
2141     ok(lstrcmpW(args[1],one)==0,"arg1 is not as expected\n");
2142     ok(lstrcmpW(args[2],two)==0,"arg2 is not as expected\n");
2143     ok(lstrcmpW(args[3],three)==0,"arg3 is not as expected\n");
2144     ok(lstrcmpW(args[4],four)==0,"arg4 is not as expected\n");
2145
2146     wsprintfW(cmdline,fmt3,one,two,three,four);
2147     args=CommandLineToArgvW(cmdline,&numargs);
2148     ok(numargs == 2, "expected 2 args, got %i\n",numargs);
2149     wsprintfW(cmdline,chkfmt1,one,two);
2150     ok(lstrcmpW(args[0],cmdline)==0,"arg0 is not as expected\n");
2151     wsprintfW(cmdline,chkfmt1,three,four);
2152     ok(lstrcmpW(args[1],cmdline)==0,"arg1 is not as expected\n");
2153
2154     wsprintfW(cmdline,fmt4,one,two,three,four);
2155     args=CommandLineToArgvW(cmdline,&numargs);
2156     ok(numargs == 3, "expected 3 args, got %i\n",numargs);
2157     ok(lstrcmpW(args[0],one)==0,"arg0 is not as expected\n");
2158     wsprintfW(cmdline,chkfmt2,two,three);
2159     ok(lstrcmpW(args[1],cmdline)==0,"arg1 is not as expected\n");
2160     ok(lstrcmpW(args[2],four)==0,"arg2 is not as expected\n");
2161
2162     wsprintfW(cmdline,fmt5,one,two,three,four);
2163     args=CommandLineToArgvW(cmdline,&numargs);
2164     ok(numargs == 2, "expected 2 args, got %i\n",numargs);
2165     wsprintfW(cmdline,chkfmt3,one);
2166     todo_wine ok(lstrcmpW(args[0],cmdline)==0,"arg0 is not as expected\n");
2167     wsprintfW(cmdline,chkfmt4,two,three,four);
2168     todo_wine ok(lstrcmpW(args[1],cmdline)==0,"arg1 is not as expected\n");
2169
2170     wsprintfW(cmdline,fmt6);
2171     args=CommandLineToArgvW(cmdline,&numargs);
2172     ok(numargs == 1, "expected 1 args, got %i\n",numargs);
2173 }
2174
2175 START_TEST(shlexec)
2176 {
2177
2178     myARGC = winetest_get_mainargs(&myARGV);
2179     if (myARGC >= 3)
2180     {
2181         doChild(myARGC, myARGV);
2182         exit(0);
2183     }
2184
2185     init_test();
2186
2187     test_argify();
2188     test_lpFile_parsed();
2189     test_filename();
2190     test_find_executable();
2191     test_lnks();
2192     test_exes();
2193     test_exes_long();
2194     test_dde();
2195     test_dde_default_app();
2196     test_commandline();
2197
2198     cleanup_test();
2199 }