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