samlib: Add stubbed samlib.dll.
[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 static void test_filename(void)
966 {
967     char filename[MAX_PATH];
968     const filename_tests_t* test;
969     char* c;
970     int rc;
971
972     test=filename_tests;
973     while (test->basename)
974     {
975         BOOL quotedfile = FALSE;
976
977         if (skip_noassoc_tests && test->rc == SE_ERR_NOASSOC)
978         {
979             win_skip("Skipping shellexecute of file with unassociated extension\n");
980             test++;
981             continue;
982         }
983
984         sprintf(filename, test->basename, tmpdir);
985         if (strchr(filename, '/'))
986         {
987             c=filename;
988             while (*c)
989             {
990                 if (*c=='\\')
991                     *c='/';
992                 c++;
993             }
994         }
995         if ((test->todo & 0x40)==0)
996         {
997             rc=shell_execute(test->verb, filename, NULL, NULL);
998         }
999         else
1000         {
1001             char quoted[MAX_PATH + 2];
1002
1003             quotedfile = TRUE;
1004             sprintf(quoted, "\"%s\"", filename);
1005             rc=shell_execute(test->verb, quoted, NULL, NULL);
1006         }
1007         if (rc > 32)
1008             rc=33;
1009         if ((test->todo & 0x1)==0)
1010         {
1011             ok(rc==test->rc ||
1012                broken(quotedfile && rc == 2), /* NT4 */
1013                "%s failed: rc=%d err=%d\n", shell_call,
1014                rc, GetLastError());
1015         }
1016         else todo_wine
1017         {
1018             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1019                rc, GetLastError());
1020         }
1021         if (rc == 33)
1022         {
1023             const char* verb;
1024             if ((test->todo & 0x2)==0)
1025             {
1026                 okChildInt("argcA", 5);
1027             }
1028             else todo_wine
1029             {
1030                 okChildInt("argcA", 5);
1031             }
1032             verb=(test->verb ? test->verb : "Open");
1033             if ((test->todo & 0x4)==0)
1034             {
1035                 okChildString("argvA3", verb);
1036             }
1037             else todo_wine
1038             {
1039                 okChildString("argvA3", verb);
1040             }
1041             if ((test->todo & 0x8)==0)
1042             {
1043                 okChildPath("argvA4", filename);
1044             }
1045             else todo_wine
1046             {
1047                 okChildPath("argvA4", filename);
1048             }
1049         }
1050         test++;
1051     }
1052
1053     test=noquotes_tests;
1054     while (test->basename)
1055     {
1056         sprintf(filename, test->basename, tmpdir);
1057         rc=shell_execute(test->verb, filename, NULL, NULL);
1058         if (rc > 32)
1059             rc=33;
1060         if ((test->todo & 0x1)==0)
1061         {
1062             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1063                rc, GetLastError());
1064         }
1065         else todo_wine
1066         {
1067             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1068                rc, GetLastError());
1069         }
1070         if (rc==0)
1071         {
1072             int count;
1073             const char* verb;
1074             char* str;
1075
1076             verb=(test->verb ? test->verb : "Open");
1077             if ((test->todo & 0x4)==0)
1078             {
1079                 okChildString("argvA3", verb);
1080             }
1081             else todo_wine
1082             {
1083                 okChildString("argvA3", verb);
1084             }
1085
1086             count=4;
1087             str=filename;
1088             while (1)
1089             {
1090                 char attrib[18];
1091                 char* space;
1092                 space=strchr(str, ' ');
1093                 if (space)
1094                     *space='\0';
1095                 sprintf(attrib, "argvA%d", count);
1096                 if ((test->todo & 0x8)==0)
1097                 {
1098                     okChildPath(attrib, str);
1099                 }
1100                 else todo_wine
1101                 {
1102                     okChildPath(attrib, str);
1103                 }
1104                 count++;
1105                 if (!space)
1106                     break;
1107                 str=space+1;
1108             }
1109             if ((test->todo & 0x2)==0)
1110             {
1111                 okChildInt("argcA", count);
1112             }
1113             else todo_wine
1114             {
1115                 okChildInt("argcA", count);
1116             }
1117         }
1118         test++;
1119     }
1120
1121     if (dllver.dwMajorVersion != 0)
1122     {
1123         /* The more recent versions of shell32.dll accept quoted filenames
1124          * while older ones (e.g. 4.00) don't. Still we want to test this
1125          * because IE 6 depends on the new behavior.
1126          * One day we may need to check the exact version of the dll but for
1127          * now making sure DllGetVersion() is present is sufficient.
1128          */
1129         sprintf(filename, "\"%s\\test file.shlexec\"", tmpdir);
1130         rc=shell_execute(NULL, filename, NULL, NULL);
1131         ok(rc > 32, "%s failed: rc=%d err=%d\n", shell_call, rc,
1132            GetLastError());
1133         okChildInt("argcA", 5);
1134         okChildString("argvA3", "Open");
1135         sprintf(filename, "%s\\test file.shlexec", tmpdir);
1136         okChildPath("argvA4", filename);
1137     }
1138 }
1139
1140 static void test_find_executable(void)
1141 {
1142     char filename[MAX_PATH];
1143     char command[MAX_PATH];
1144     const filename_tests_t* test;
1145     INT_PTR rc;
1146
1147     if (!create_test_association(".sfe"))
1148     {
1149         skip("Unable to create association for '.sfe'\n");
1150         return;
1151     }
1152     create_test_verb(".sfe", "Open", 1, "%1");
1153
1154     /* Don't test FindExecutable(..., NULL), it always crashes */
1155
1156     strcpy(command, "your word");
1157     if (0) /* Can crash on Vista! */
1158     {
1159     rc=(INT_PTR)FindExecutableA(NULL, NULL, command);
1160     ok(rc == SE_ERR_FNF || rc > 32 /* nt4 */, "FindExecutable(NULL) returned %ld\n", rc);
1161     ok(strcmp(command, "your word") != 0, "FindExecutable(NULL) returned command=[%s]\n", command);
1162     }
1163
1164     strcpy(command, "your word");
1165     rc=(INT_PTR)FindExecutableA(tmpdir, NULL, command);
1166     ok(rc == SE_ERR_NOASSOC /* >= win2000 */ || rc > 32 /* win98, nt4 */, "FindExecutable(NULL) returned %ld\n", rc);
1167     ok(strcmp(command, "your word") != 0, "FindExecutable(NULL) returned command=[%s]\n", command);
1168
1169     sprintf(filename, "%s\\test file.sfe", tmpdir);
1170     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1171     ok(rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1172     /* Depending on the platform, command could be '%1' or 'test file.sfe' */
1173
1174     rc=(INT_PTR)FindExecutableA("test file.sfe", tmpdir, command);
1175     ok(rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1176
1177     rc=(INT_PTR)FindExecutableA("test file.sfe", NULL, command);
1178     ok(rc == SE_ERR_FNF, "FindExecutable(%s) returned %ld\n", filename, rc);
1179
1180     delete_test_association(".sfe");
1181
1182     if (!create_test_association(".shl"))
1183     {
1184         skip("Unable to create association for '.shl'\n");
1185         return;
1186     }
1187     create_test_verb(".shl", "Open", 0, "Open");
1188
1189     sprintf(filename, "%s\\test file.shl", tmpdir);
1190     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1191     ok(rc == SE_ERR_FNF /* NT4 */ || rc > 32, "FindExecutable(%s) returned %ld\n", filename, rc);
1192
1193     sprintf(filename, "%s\\test file.shlfoo", tmpdir);
1194     rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1195
1196     delete_test_association(".shl");
1197
1198     if (rc > 32)
1199     {
1200         /* On Windows XP and 2003 FindExecutable() is completely broken.
1201          * Probably what it does is convert the filename to 8.3 format,
1202          * which as a side effect converts the '.shlfoo' extension to '.shl',
1203          * and then tries to find an association for '.shl'. This means it
1204          * will normally fail on most extensions with more than 3 characters,
1205          * like '.mpeg', etc.
1206          * Also it means we cannot do any other test.
1207          */
1208         win_skip("FindExecutable() is broken -> not running 4+ character extension tests\n");
1209         return;
1210     }
1211
1212     test=filename_tests;
1213     while (test->basename)
1214     {
1215         sprintf(filename, test->basename, tmpdir);
1216         if (strchr(filename, '/'))
1217         {
1218             char* c;
1219             c=filename;
1220             while (*c)
1221             {
1222                 if (*c=='\\')
1223                     *c='/';
1224                 c++;
1225             }
1226         }
1227         /* Win98 does not '\0'-terminate command! */
1228         memset(command, '\0', sizeof(command));
1229         rc=(INT_PTR)FindExecutableA(filename, NULL, command);
1230         if (rc > 32)
1231             rc=33;
1232         if ((test->todo & 0x10)==0)
1233         {
1234             ok(rc==test->rc, "FindExecutable(%s) failed: rc=%ld\n", filename, rc);
1235         }
1236         else todo_wine
1237         {
1238             ok(rc==test->rc, "FindExecutable(%s) failed: rc=%ld\n", filename, rc);
1239         }
1240         if (rc > 32)
1241         {
1242             int equal;
1243             equal=strcmp(command, argv0) == 0 ||
1244                 /* NT4 returns an extra 0x8 character! */
1245                 (strlen(command) == strlen(argv0)+1 && strncmp(command, argv0, strlen(argv0)) == 0);
1246             if ((test->todo & 0x20)==0)
1247             {
1248                 ok(equal, "FindExecutable(%s) returned command='%s' instead of '%s'\n",
1249                    filename, command, argv0);
1250             }
1251             else todo_wine
1252             {
1253                 ok(equal, "FindExecutable(%s) returned command='%s' instead of '%s'\n",
1254                    filename, command, argv0);
1255             }
1256         }
1257         test++;
1258     }
1259 }
1260
1261
1262 static filename_tests_t lnk_tests[]=
1263 {
1264     /* Pass bad / nonexistent filenames as a parameter */
1265     {NULL, "%s\\nonexistent.shlexec",    0xa, 33},
1266     {NULL, "%s\\nonexistent.noassoc",    0xa, 33},
1267
1268     /* Pass regular paths as a parameter */
1269     {NULL, "%s\\test file.shlexec",      0xa, 33},
1270     {NULL, "%s/%%nasty%% $file.shlexec", 0xa, 33},
1271
1272     /* Pass filenames with no association as a parameter */
1273     {NULL, "%s\\test file.noassoc",      0xa, 33},
1274
1275     {NULL, NULL, 0}
1276 };
1277
1278 static void test_lnks(void)
1279 {
1280     char filename[MAX_PATH];
1281     char params[MAX_PATH];
1282     const filename_tests_t* test;
1283     int rc;
1284
1285     sprintf(filename, "%s\\test_shortcut_shlexec.lnk", tmpdir);
1286     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL);
1287     ok(rc > 32, "%s failed: rc=%d err=%d\n", shell_call, rc,
1288        GetLastError());
1289     okChildInt("argcA", 5);
1290     okChildString("argvA3", "Open");
1291     sprintf(params, "%s\\test file.shlexec", tmpdir);
1292     get_long_path_name(params, filename, sizeof(filename));
1293     okChildPath("argvA4", filename);
1294
1295     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1296     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL);
1297     ok(rc > 32, "%s failed: rc=%d err=%d\n", shell_call, rc,
1298        GetLastError());
1299     okChildInt("argcA", 4);
1300     okChildString("argvA3", "Lnk");
1301
1302     if (dllver.dwMajorVersion>=6)
1303     {
1304         char* c;
1305        /* Recent versions of shell32.dll accept '/'s in shortcut paths.
1306          * Older versions don't or are quite buggy in this regard.
1307          */
1308         sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1309         c=filename;
1310         while (*c)
1311         {
1312             if (*c=='\\')
1313                 *c='/';
1314             c++;
1315         }
1316         rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, NULL, NULL);
1317         ok(rc > 32, "%s failed: rc=%d err=%d\n", shell_call, rc,
1318            GetLastError());
1319         okChildInt("argcA", 4);
1320         okChildString("argvA3", "Lnk");
1321     }
1322
1323     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1324     test=lnk_tests;
1325     while (test->basename)
1326     {
1327         params[0]='\"';
1328         sprintf(params+1, test->basename, tmpdir);
1329         strcat(params,"\"");
1330         rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, filename, params,
1331                             NULL);
1332         if (rc > 32)
1333             rc=33;
1334         if ((test->todo & 0x1)==0)
1335         {
1336             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1337                rc, GetLastError());
1338         }
1339         else todo_wine
1340         {
1341             ok(rc==test->rc, "%s failed: rc=%d err=%d\n", shell_call,
1342                rc, GetLastError());
1343         }
1344         if (rc==0)
1345         {
1346             if ((test->todo & 0x2)==0)
1347             {
1348                 okChildInt("argcA", 5);
1349             }
1350             else
1351             {
1352                 okChildInt("argcA", 5);
1353             }
1354             if ((test->todo & 0x4)==0)
1355             {
1356                 okChildString("argvA3", "Lnk");
1357             }
1358             else todo_wine
1359             {
1360                 okChildString("argvA3", "Lnk");
1361             }
1362             sprintf(params, test->basename, tmpdir);
1363             if ((test->todo & 0x8)==0)
1364             {
1365                 okChildPath("argvA4", params);
1366             }
1367             else
1368             {
1369                 okChildPath("argvA4", params);
1370             }
1371         }
1372         test++;
1373     }
1374 }
1375
1376
1377 static void test_exes(void)
1378 {
1379     char filename[MAX_PATH];
1380     char params[1024];
1381     int rc;
1382
1383     sprintf(params, "shlexec \"%s\" Exec", child_file);
1384
1385     /* We need NOZONECHECKS on Win2003 to block a dialog */
1386     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, argv0, params,
1387                         NULL);
1388     ok(rc > 32, "%s returned %d\n", shell_call, rc);
1389     okChildInt("argcA", 4);
1390     okChildString("argvA3", "Exec");
1391
1392     if (! skip_noassoc_tests)
1393     {
1394         sprintf(filename, "%s\\test file.noassoc", tmpdir);
1395         if (CopyFile(argv0, filename, FALSE))
1396         {
1397             rc=shell_execute(NULL, filename, params, NULL);
1398             todo_wine {
1399                 ok(rc==SE_ERR_NOASSOC, "%s succeeded: rc=%d\n", shell_call, rc);
1400             }
1401         }
1402     }
1403     else
1404     {
1405         win_skip("Skipping shellexecute of file with unassociated extension\n");
1406     }
1407 }
1408
1409 static void test_exes_long(void)
1410 {
1411     char filename[MAX_PATH];
1412     char params[2024];
1413     char longparam[MAX_PATH];
1414     int rc;
1415
1416     for (rc = 0; rc < MAX_PATH; rc++)
1417         longparam[rc]='a'+rc%26;
1418     longparam[MAX_PATH-1]=0;
1419
1420
1421     sprintf(params, "shlexec \"%s\" %s", child_file,longparam);
1422
1423     /* We need NOZONECHECKS on Win2003 to block a dialog */
1424     rc=shell_execute_ex(SEE_MASK_NOZONECHECKS, NULL, argv0, params,
1425                         NULL);
1426     ok(rc > 32, "%s returned %d\n", shell_call, rc);
1427     okChildInt("argcA", 4);
1428     okChildString("argvA3", longparam);
1429
1430     if (! skip_noassoc_tests)
1431     {
1432         sprintf(filename, "%s\\test file.noassoc", tmpdir);
1433         if (CopyFile(argv0, filename, FALSE))
1434         {
1435             rc=shell_execute(NULL, filename, params, NULL);
1436             todo_wine {
1437                 ok(rc==SE_ERR_NOASSOC, "%s succeeded: rc=%d\n", shell_call, rc);
1438             }
1439         }
1440     }
1441     else
1442     {
1443         win_skip("Skipping shellexecute of file with unassociated extension\n");
1444     }
1445 }
1446
1447 typedef struct
1448 {
1449     const char* command;
1450     const char* ddeexec;
1451     const char* application;
1452     const char* topic;
1453     const char* ifexec;
1454     int expectedArgs;
1455     const char* expectedDdeExec;
1456     int todo;
1457 } dde_tests_t;
1458
1459 static dde_tests_t dde_tests[] =
1460 {
1461     /* Test passing and not passing command-line
1462      * argument, no DDE */
1463     {"", NULL, NULL, NULL, NULL, FALSE, "", 0x0},
1464     {"\"%1\"", NULL, NULL, NULL, NULL, TRUE, "", 0x0},
1465
1466     /* Test passing and not passing command-line
1467      * argument, with DDE */
1468     {"", "[open(\"%1\")]", "shlexec", "dde", NULL, FALSE, "[open(\"%s\")]", 0x0},
1469     {"\"%1\"", "[open(\"%1\")]", "shlexec", "dde", NULL, TRUE, "[open(\"%s\")]", 0x0},
1470
1471     /* Test unquoted %1 in command and ddeexec
1472      * (test filename has space) */
1473     {"%1", "[open(%1)]", "shlexec", "dde", NULL, 2, "[open(%s)]", 0x0},
1474
1475     /* Test ifexec precedence over ddeexec */
1476     {"", "[open(\"%1\")]", "shlexec", "dde", "[ifexec(\"%1\")]", FALSE, "[ifexec(\"%s\")]", 0x0},
1477
1478     /* Test default DDE topic */
1479     {"", "[open(\"%1\")]", "shlexec", NULL, NULL, FALSE, "[open(\"%s\")]", 0x0},
1480
1481     /* Test default DDE application */
1482     {"", "[open(\"%1\")]", NULL, "dde", NULL, FALSE, "[open(\"%s\")]", 0x0},
1483
1484     {NULL, NULL, NULL, NULL, NULL, 0, 0x0}
1485 };
1486
1487 static DWORD WINAPI hooked_WaitForInputIdle(HANDLE process, DWORD timeout)
1488 {
1489     HANDLE dde_ready;
1490     DWORD wait_result;
1491
1492     dde_ready = CreateEventA(NULL, FALSE, FALSE, "winetest_shlexec_dde_ready");
1493     wait_result = WaitForSingleObject(dde_ready, timeout);
1494     CloseHandle(dde_ready);
1495
1496     return wait_result;
1497 }
1498
1499 /*
1500  * WaitForInputIdle() will normally return immediately for console apps. That's
1501  * a problem for us because ShellExecute will assume that an app is ready to
1502  * receive DDE messages after it has called WaitForInputIdle() on that app.
1503  * To work around that we install our own version of WaitForInputIdle() that
1504  * will wait for the child to explicitly tell us that it is ready. We do that
1505  * by changing the entry for WaitForInputIdle() in the shell32 import address
1506  * table.
1507  */
1508 static void hook_WaitForInputIdle(void *new_func)
1509 {
1510     char *base;
1511     PIMAGE_NT_HEADERS nt_headers;
1512     DWORD import_directory_rva;
1513     PIMAGE_IMPORT_DESCRIPTOR import_descriptor;
1514
1515     base = (char *) GetModuleHandleA("shell32.dll");
1516     nt_headers = (PIMAGE_NT_HEADERS)(base + ((PIMAGE_DOS_HEADER) base)->e_lfanew);
1517     import_directory_rva = nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
1518
1519     /* Search for the correct imported module by walking the import descriptors */
1520     import_descriptor = (PIMAGE_IMPORT_DESCRIPTOR)(base + import_directory_rva);
1521     while (U(*import_descriptor).OriginalFirstThunk != 0)
1522     {
1523         char *import_module_name;
1524
1525         import_module_name = base + import_descriptor->Name;
1526         if (lstrcmpiA(import_module_name, "user32.dll") == 0 ||
1527             lstrcmpiA(import_module_name, "user32") == 0)
1528         {
1529             PIMAGE_THUNK_DATA int_entry;
1530             PIMAGE_THUNK_DATA iat_entry;
1531
1532             /* The import name table and import address table are two parallel
1533              * arrays. We need the import name table to find the imported
1534              * routine and the import address table to patch the address, so
1535              * walk them side by side */
1536             int_entry = (PIMAGE_THUNK_DATA)(base + U(*import_descriptor).OriginalFirstThunk);
1537             iat_entry = (PIMAGE_THUNK_DATA)(base + import_descriptor->FirstThunk);
1538             while (int_entry->u1.Ordinal != 0)
1539             {
1540                 if (! IMAGE_SNAP_BY_ORDINAL(int_entry->u1.Ordinal))
1541                 {
1542                     PIMAGE_IMPORT_BY_NAME import_by_name;
1543                     import_by_name = (PIMAGE_IMPORT_BY_NAME)(base + int_entry->u1.AddressOfData);
1544                     if (lstrcmpA((char *) import_by_name->Name, "WaitForInputIdle") == 0)
1545                     {
1546                         /* Found the correct routine in the correct imported module. Patch it. */
1547                         DWORD old_prot;
1548                         VirtualProtect(&iat_entry->u1.Function, sizeof(ULONG_PTR), PAGE_READWRITE, &old_prot);
1549                         iat_entry->u1.Function = (ULONG_PTR) new_func;
1550                         VirtualProtect(&iat_entry->u1.Function, sizeof(ULONG_PTR), old_prot, &old_prot);
1551                         break;
1552                     }
1553                 }
1554                 int_entry++;
1555                 iat_entry++;
1556             }
1557             break;
1558         }
1559
1560         import_descriptor++;
1561     }
1562 }
1563
1564 static void test_dde(void)
1565 {
1566     char filename[MAX_PATH], defApplication[MAX_PATH];
1567     const dde_tests_t* test;
1568     char params[1024];
1569     int rc;
1570     HANDLE map;
1571     char *shared_block;
1572
1573     hook_WaitForInputIdle((void *) hooked_WaitForInputIdle);
1574
1575     sprintf(filename, "%s\\test file.sde", tmpdir);
1576
1577     /* Default service is application name minus path and extension */
1578     strcpy(defApplication, strrchr(argv0, '\\')+1);
1579     *strchr(defApplication, '.') = 0;
1580
1581     map = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
1582                              4096, "winetest_shlexec_dde_map");
1583     shared_block = MapViewOfFile(map, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 4096);
1584
1585     test = dde_tests;
1586     while (test->command)
1587     {
1588         if (!create_test_association(".sde"))
1589         {
1590             skip("Unable to create association for '.sfe'\n");
1591             return;
1592         }
1593         create_test_verb_dde(".sde", "Open", 0, test->command, test->ddeexec,
1594                              test->application, test->topic, test->ifexec);
1595
1596         if (test->application != NULL || test->topic != NULL)
1597         {
1598             strcpy(shared_block, test->application ? test->application : defApplication);
1599             strcpy(shared_block + strlen(shared_block) + 1, test->topic ? test->topic : SZDDESYS_TOPIC);
1600         }
1601         else
1602         {
1603             shared_block[0] = '\0';
1604             shared_block[1] = '\0';
1605         }
1606         ddeExec[0] = 0;
1607
1608         rc = shell_execute_ex(SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI, NULL, filename, NULL, NULL);
1609         if ((test->todo & 0x1)==0)
1610         {
1611             ok(32 < rc, "%s failed: rc=%d err=%d\n", shell_call,
1612                rc, GetLastError());
1613         }
1614         else todo_wine
1615         {
1616             ok(32 < rc, "%s failed: rc=%d err=%d\n", shell_call,
1617                rc, GetLastError());
1618         }
1619         if (32 < rc)
1620         {
1621             if ((test->todo & 0x2)==0)
1622             {
1623                 okChildInt("argcA", test->expectedArgs + 3);
1624             }
1625             else todo_wine
1626             {
1627                 okChildInt("argcA", test->expectedArgs + 3);
1628             }
1629             if (test->expectedArgs == 1)
1630             {
1631                 if ((test->todo & 0x4) == 0)
1632                 {
1633                     okChildPath("argvA3", filename);
1634                 }
1635                 else todo_wine
1636                 {
1637                     okChildPath("argvA3", filename);
1638                 }
1639             }
1640             if ((test->todo & 0x8) == 0)
1641             {
1642                 sprintf(params, test->expectedDdeExec, filename);
1643                 okChildPath("ddeExec", params);
1644             }
1645             else todo_wine
1646             {
1647                 sprintf(params, test->expectedDdeExec, filename);
1648                 okChildPath("ddeExec", params);
1649             }
1650         }
1651
1652         delete_test_association(".sde");
1653         test++;
1654     }
1655
1656     UnmapViewOfFile(shared_block);
1657     CloseHandle(map);
1658     hook_WaitForInputIdle((void *) WaitForInputIdle);
1659 }
1660
1661 #define DDE_DEFAULT_APP_VARIANTS 2
1662 typedef struct
1663 {
1664     const char* command;
1665     const char* expectedDdeApplication[DDE_DEFAULT_APP_VARIANTS];
1666     int todo;
1667     int rc[DDE_DEFAULT_APP_VARIANTS];
1668 } dde_default_app_tests_t;
1669
1670 static dde_default_app_tests_t dde_default_app_tests[] =
1671 {
1672     /* Windows XP and 98 handle default DDE app names in different ways.
1673      * The application name we see in the first test determines the pattern
1674      * of application names and return codes we will look for. */
1675
1676     /* Test unquoted existing filename with a space */
1677     {"%s\\test file.exe", {"test file", "test"}, 0x0, {33, 33}},
1678     {"%s\\test file.exe param", {"test file", "test"}, 0x0, {33, 33}},
1679
1680     /* Test quoted existing filename with a space */
1681     {"\"%s\\test file.exe\"", {"test file", "test file"}, 0x0, {33, 33}},
1682     {"\"%s\\test file.exe\" param", {"test file", "test file"}, 0x0, {33, 33}},
1683
1684     /* Test unquoted filename with a space that doesn't exist, but
1685      * test2.exe does */
1686     {"%s\\test2 file.exe", {"test2", "test2"}, 0x0, {33, 33}},
1687     {"%s\\test2 file.exe param", {"test2", "test2"}, 0x0, {33, 33}},
1688
1689     /* Test quoted filename with a space that does not exist */
1690     {"\"%s\\test2 file.exe\"", {"", "test2 file"}, 0x0, {5, 33}},
1691     {"\"%s\\test2 file.exe\" param", {"", "test2 file"}, 0x0, {5, 33}},
1692
1693     /* Test filename supplied without the extension */
1694     {"%s\\test2", {"test2", "test2"}, 0x0, {33, 33}},
1695     {"%s\\test2 param", {"test2", "test2"}, 0x0, {33, 33}},
1696
1697     /* Test an unquoted nonexistent filename */
1698     {"%s\\notexist.exe", {"", "notexist"}, 0x0, {5, 33}},
1699     {"%s\\notexist.exe param", {"", "notexist"}, 0x0, {5, 33}},
1700
1701     /* Test an application that will be found on the path */
1702     {"cmd", {"cmd", "cmd"}, 0x0, {33, 33}},
1703     {"cmd param", {"cmd", "cmd"}, 0x0, {33, 33}},
1704
1705     /* Test an application that will not be found on the path */
1706     {"xyzwxyzwxyz", {"", "xyzwxyzwxyz"}, 0x0, {5, 33}},
1707     {"xyzwxyzwxyz param", {"", "xyzwxyzwxyz"}, 0x0, {5, 33}},
1708
1709     {NULL, {NULL}, 0, {0}}
1710 };
1711
1712 typedef struct
1713 {
1714     char *filename;
1715     DWORD threadIdParent;
1716 } dde_thread_info_t;
1717
1718 static DWORD CALLBACK ddeThread(LPVOID arg)
1719 {
1720     dde_thread_info_t *info = arg;
1721     assert(info && info->filename);
1722     PostThreadMessage(info->threadIdParent,
1723                       WM_QUIT,
1724                       shell_execute_ex(SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI, NULL, info->filename, NULL, NULL),
1725                       0L);
1726     ExitThread(0);
1727 }
1728
1729 static void test_dde_default_app(void)
1730 {
1731     char filename[MAX_PATH];
1732     HSZ hszApplication;
1733     dde_thread_info_t info = { filename, GetCurrentThreadId() };
1734     const dde_default_app_tests_t* test;
1735     char params[1024];
1736     DWORD threadId;
1737     MSG msg;
1738     int rc, which = 0;
1739
1740     post_quit_on_execute = FALSE;
1741     ddeInst = 0;
1742     rc = DdeInitializeA(&ddeInst, ddeCb, CBF_SKIP_ALLNOTIFICATIONS | CBF_FAIL_ADVISES |
1743                         CBF_FAIL_POKES | CBF_FAIL_REQUESTS, 0L);
1744     assert(rc == DMLERR_NO_ERROR);
1745
1746     sprintf(filename, "%s\\test file.sde", tmpdir);
1747
1748     /* It is strictly not necessary to register an application name here, but wine's
1749      * DdeNameService implementation complains if 0L is passed instead of
1750      * hszApplication with DNS_FILTEROFF */
1751     hszApplication = DdeCreateStringHandleA(ddeInst, "shlexec", CP_WINANSI);
1752     hszTopic = DdeCreateStringHandleA(ddeInst, "shlexec", CP_WINANSI);
1753     assert(hszApplication && hszTopic);
1754     assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_REGISTER | DNS_FILTEROFF));
1755
1756     test = dde_default_app_tests;
1757     while (test->command)
1758     {
1759         if (!create_test_association(".sde"))
1760         {
1761             skip("Unable to create association for '.sde'\n");
1762             return;
1763         }
1764         sprintf(params, test->command, tmpdir);
1765         create_test_verb_dde(".sde", "Open", 1, params, "[test]", NULL,
1766                              "shlexec", NULL);
1767         ddeApplication[0] = 0;
1768
1769         /* No application will be run as we will respond to the first DDE event,
1770          * so don't wait for it */
1771         SetEvent(hEvent);
1772
1773         assert(CreateThread(NULL, 0, ddeThread, &info, 0, &threadId));
1774         while (GetMessage(&msg, NULL, 0, 0)) DispatchMessage(&msg);
1775         rc = msg.wParam > 32 ? 33 : msg.wParam;
1776
1777         /* First test, find which set of test data we expect to see */
1778         if (test == dde_default_app_tests)
1779         {
1780             int i;
1781             for (i=0; i<DDE_DEFAULT_APP_VARIANTS; i++)
1782             {
1783                 if (!strcmp(ddeApplication, test->expectedDdeApplication[i]))
1784                 {
1785                     which = i;
1786                     break;
1787                 }
1788             }
1789             if (i == DDE_DEFAULT_APP_VARIANTS)
1790                 skip("Default DDE application test does not match any available results, using first expected data set.\n");
1791         }
1792
1793         if ((test->todo & 0x1)==0)
1794         {
1795             ok(rc==test->rc[which], "%s failed: rc=%d err=%d\n", shell_call,
1796                rc, GetLastError());
1797         }
1798         else todo_wine
1799         {
1800             ok(rc==test->rc[which], "%s failed: rc=%d err=%d\n", shell_call,
1801                rc, GetLastError());
1802         }
1803         if (rc == 33)
1804         {
1805             if ((test->todo & 0x2)==0)
1806             {
1807                 ok(!strcmp(ddeApplication, test->expectedDdeApplication[which]),
1808                    "Expected application '%s', got '%s'\n",
1809                    test->expectedDdeApplication[which], ddeApplication);
1810             }
1811             else todo_wine
1812             {
1813                 ok(!strcmp(ddeApplication, test->expectedDdeApplication[which]),
1814                    "Expected application '%s', got '%s'\n",
1815                    test->expectedDdeApplication[which], ddeApplication);
1816             }
1817         }
1818
1819         delete_test_association(".sde");
1820         test++;
1821     }
1822
1823     assert(DdeNameService(ddeInst, hszApplication, 0L, DNS_UNREGISTER));
1824     assert(DdeFreeStringHandle(ddeInst, hszTopic));
1825     assert(DdeFreeStringHandle(ddeInst, hszApplication));
1826     assert(DdeUninitialize(ddeInst));
1827 }
1828
1829 static void init_test(void)
1830 {
1831     HMODULE hdll;
1832     HRESULT (WINAPI *pDllGetVersion)(DLLVERSIONINFO*);
1833     char filename[MAX_PATH];
1834     WCHAR lnkfile[MAX_PATH];
1835     char params[1024];
1836     const char* const * testfile;
1837     lnk_desc_t desc;
1838     DWORD rc;
1839     HRESULT r;
1840
1841     hdll=GetModuleHandleA("shell32.dll");
1842     pDllGetVersion=(void*)GetProcAddress(hdll, "DllGetVersion");
1843     if (pDllGetVersion)
1844     {
1845         dllver.cbSize=sizeof(dllver);
1846         pDllGetVersion(&dllver);
1847         trace("major=%d minor=%d build=%d platform=%d\n",
1848               dllver.dwMajorVersion, dllver.dwMinorVersion,
1849               dllver.dwBuildNumber, dllver.dwPlatformID);
1850     }
1851     else
1852     {
1853         memset(&dllver, 0, sizeof(dllver));
1854     }
1855
1856     r = CoInitialize(NULL);
1857     ok(r == S_OK, "CoInitialize failed (0x%08x)\n", r);
1858     if (FAILED(r))
1859         exit(1);
1860
1861     rc=GetModuleFileName(NULL, argv0, sizeof(argv0));
1862     assert(rc!=0 && rc<sizeof(argv0));
1863     if (GetFileAttributes(argv0)==INVALID_FILE_ATTRIBUTES)
1864     {
1865         strcat(argv0, ".so");
1866         ok(GetFileAttributes(argv0)!=INVALID_FILE_ATTRIBUTES,
1867            "unable to find argv0!\n");
1868     }
1869
1870     GetTempPathA(sizeof(filename), filename);
1871     GetTempFileNameA(filename, "wt", 0, tmpdir);
1872     DeleteFileA( tmpdir );
1873     rc = CreateDirectoryA( tmpdir, NULL );
1874     ok( rc, "failed to create %s err %u\n", tmpdir, GetLastError() );
1875     rc = GetTempFileNameA(tmpdir, "wt", 0, child_file);
1876     assert(rc != 0);
1877     init_event(child_file);
1878
1879     /* Set up the test files */
1880     testfile=testfiles;
1881     while (*testfile)
1882     {
1883         HANDLE hfile;
1884
1885         sprintf(filename, *testfile, tmpdir);
1886         hfile=CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
1887                      FILE_ATTRIBUTE_NORMAL, NULL);
1888         if (hfile==INVALID_HANDLE_VALUE)
1889         {
1890             trace("unable to create '%s': err=%d\n", filename, GetLastError());
1891             assert(0);
1892         }
1893         CloseHandle(hfile);
1894         testfile++;
1895     }
1896
1897     /* Setup the test shortcuts */
1898     sprintf(filename, "%s\\test_shortcut_shlexec.lnk", tmpdir);
1899     MultiByteToWideChar(CP_ACP, 0, filename, -1, lnkfile, sizeof(lnkfile)/sizeof(*lnkfile));
1900     desc.description=NULL;
1901     desc.workdir=NULL;
1902     sprintf(filename, "%s\\test file.shlexec", tmpdir);
1903     desc.path=filename;
1904     desc.pidl=NULL;
1905     desc.arguments="ignored";
1906     desc.showcmd=0;
1907     desc.icon=NULL;
1908     desc.icon_id=0;
1909     desc.hotkey=0;
1910     create_lnk(lnkfile, &desc, 0);
1911
1912     sprintf(filename, "%s\\test_shortcut_exe.lnk", tmpdir);
1913     MultiByteToWideChar(CP_ACP, 0, filename, -1, lnkfile, sizeof(lnkfile)/sizeof(*lnkfile));
1914     desc.description=NULL;
1915     desc.workdir=NULL;
1916     desc.path=argv0;
1917     desc.pidl=NULL;
1918     sprintf(params, "shlexec \"%s\" Lnk", child_file);
1919     desc.arguments=params;
1920     desc.showcmd=0;
1921     desc.icon=NULL;
1922     desc.icon_id=0;
1923     desc.hotkey=0;
1924     create_lnk(lnkfile, &desc, 0);
1925
1926     /* Create a basic association suitable for most tests */
1927     if (!create_test_association(".shlexec"))
1928     {
1929         skip("Unable to create association for '.shlexec'\n");
1930         return;
1931     }
1932     create_test_verb(".shlexec", "Open", 0, "Open \"%1\"");
1933     create_test_verb(".shlexec", "NoQuotes", 0, "NoQuotes %1");
1934     create_test_verb(".shlexec", "LowerL", 0, "LowerL %l");
1935     create_test_verb(".shlexec", "QuotedLowerL", 0, "QuotedLowerL \"%l\"");
1936     create_test_verb(".shlexec", "UpperL", 0, "UpperL %L");
1937     create_test_verb(".shlexec", "QuotedUpperL", 0, "QuotedUpperL \"%L\"");
1938 }
1939
1940 static void cleanup_test(void)
1941 {
1942     char filename[MAX_PATH];
1943     const char* const * testfile;
1944
1945     /* Delete the test files */
1946     testfile=testfiles;
1947     while (*testfile)
1948     {
1949         sprintf(filename, *testfile, tmpdir);
1950         /* Make sure we can delete the files ('test file.noassoc' is read-only now) */
1951         SetFileAttributes(filename, FILE_ATTRIBUTE_NORMAL);
1952         DeleteFile(filename);
1953         testfile++;
1954     }
1955     DeleteFile(child_file);
1956     RemoveDirectoryA(tmpdir);
1957
1958     /* Delete the test association */
1959     delete_test_association(".shlexec");
1960
1961     CloseHandle(hEvent);
1962
1963     CoUninitialize();
1964 }
1965
1966 static void test_commandline(void)
1967 {
1968     static const WCHAR one[] = {'o','n','e',0};
1969     static const WCHAR two[] = {'t','w','o',0};
1970     static const WCHAR three[] = {'t','h','r','e','e',0};
1971     static const WCHAR four[] = {'f','o','u','r',0};
1972
1973     static const WCHAR fmt1[] = {'%','s',' ','%','s',' ','%','s',' ','%','s',0};
1974     static const WCHAR fmt2[] = {' ','%','s',' ','%','s',' ','%','s',' ','%','s',0};
1975     static const WCHAR fmt3[] = {'%','s','=','%','s',' ','%','s','=','\"','%','s','\"',0};
1976     static const WCHAR fmt4[] = {'\"','%','s','\"',' ','\"','%','s',' ','%','s','\"',' ','%','s',0};
1977     static const WCHAR fmt5[] = {'\\','\"','%','s','\"',' ','%','s','=','\"','%','s','\\','\"',' ','\"','%','s','\\','\"',0};
1978     static const WCHAR fmt6[] = {0};
1979
1980     static const WCHAR chkfmt1[] = {'%','s','=','%','s',0};
1981     static const WCHAR chkfmt2[] = {'%','s',' ','%','s',0};
1982     static const WCHAR chkfmt3[] = {'\\','\"','%','s','\"',0};
1983     static const WCHAR chkfmt4[] = {'%','s','=','%','s','\"',' ','%','s','\"',0};
1984     WCHAR cmdline[255];
1985     LPWSTR *args = (LPWSTR*)0xdeadcafe;
1986     INT numargs = -1;
1987
1988     wsprintfW(cmdline,fmt1,one,two,three,four);
1989     args=CommandLineToArgvW(cmdline,&numargs);
1990     if (args == NULL && numargs == -1)
1991     {
1992         win_skip("CommandLineToArgvW not implemented, skipping\n");
1993         return;
1994     }
1995     ok(numargs == 4, "expected 4 args, got %i\n",numargs);
1996     ok(lstrcmpW(args[0],one)==0,"arg0 is not as expected\n");
1997     ok(lstrcmpW(args[1],two)==0,"arg1 is not as expected\n");
1998     ok(lstrcmpW(args[2],three)==0,"arg2 is not as expected\n");
1999     ok(lstrcmpW(args[3],four)==0,"arg3 is not as expected\n");
2000
2001     wsprintfW(cmdline,fmt2,one,two,three,four);
2002     args=CommandLineToArgvW(cmdline,&numargs);
2003     ok(numargs == 5, "expected 5 args, got %i\n",numargs);
2004     ok(args[0][0]==0,"arg0 is not as expected\n");
2005     ok(lstrcmpW(args[1],one)==0,"arg1 is not as expected\n");
2006     ok(lstrcmpW(args[2],two)==0,"arg2 is not as expected\n");
2007     ok(lstrcmpW(args[3],three)==0,"arg3 is not as expected\n");
2008     ok(lstrcmpW(args[4],four)==0,"arg4 is not as expected\n");
2009
2010     wsprintfW(cmdline,fmt3,one,two,three,four);
2011     args=CommandLineToArgvW(cmdline,&numargs);
2012     ok(numargs == 2, "expected 2 args, got %i\n",numargs);
2013     wsprintfW(cmdline,chkfmt1,one,two);
2014     ok(lstrcmpW(args[0],cmdline)==0,"arg0 is not as expected\n");
2015     wsprintfW(cmdline,chkfmt1,three,four);
2016     ok(lstrcmpW(args[1],cmdline)==0,"arg1 is not as expected\n");
2017
2018     wsprintfW(cmdline,fmt4,one,two,three,four);
2019     args=CommandLineToArgvW(cmdline,&numargs);
2020     ok(numargs == 3, "expected 3 args, got %i\n",numargs);
2021     ok(lstrcmpW(args[0],one)==0,"arg0 is not as expected\n");
2022     wsprintfW(cmdline,chkfmt2,two,three);
2023     ok(lstrcmpW(args[1],cmdline)==0,"arg1 is not as expected\n");
2024     ok(lstrcmpW(args[2],four)==0,"arg2 is not as expected\n");
2025
2026     wsprintfW(cmdline,fmt5,one,two,three,four);
2027     args=CommandLineToArgvW(cmdline,&numargs);
2028     ok(numargs == 2, "expected 2 args, got %i\n",numargs);
2029     wsprintfW(cmdline,chkfmt3,one);
2030     todo_wine ok(lstrcmpW(args[0],cmdline)==0,"arg0 is not as expected\n");
2031     wsprintfW(cmdline,chkfmt4,two,three,four);
2032     todo_wine ok(lstrcmpW(args[1],cmdline)==0,"arg1 is not as expected\n");
2033
2034     wsprintfW(cmdline,fmt6);
2035     args=CommandLineToArgvW(cmdline,&numargs);
2036     ok(numargs == 1, "expected 1 args, got %i\n",numargs);
2037 }
2038
2039 START_TEST(shlexec)
2040 {
2041
2042     myARGC = winetest_get_mainargs(&myARGV);
2043     if (myARGC >= 3)
2044     {
2045         doChild(myARGC, myARGV);
2046         exit(0);
2047     }
2048
2049     init_test();
2050
2051     test_lpFile_parsed();
2052     test_filename();
2053     test_find_executable();
2054     test_lnks();
2055     test_exes();
2056     test_exes_long();
2057     test_dde();
2058     test_dde_default_app();
2059     test_commandline();
2060
2061     cleanup_test();
2062 }