mshtml: Move IOleInPlaceFrame::SetActiveObject call to separated function.
[wine] / dlls / shell32 / shlexec.c
1 /*
2  *                              Shell Library Functions
3  *
4  * Copyright 1998 Marcus Meissner
5  * Copyright 2002 Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32 #include <ctype.h>
33 #include <assert.h>
34
35 #define COBJMACROS
36
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "winreg.h"
41 #include "winuser.h"
42 #include "shlwapi.h"
43 #include "ddeml.h"
44
45 #include "wine/winbase16.h"
46 #include "shell32_main.h"
47 #include "pidl.h"
48
49 #include "wine/debug.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(exec);
52
53 static const WCHAR wszOpen[] = {'o','p','e','n',0};
54 static const WCHAR wszExe[] = {'.','e','x','e',0};
55 static const WCHAR wszILPtr[] = {':','%','p',0};
56 static const WCHAR wszShell[] = {'\\','s','h','e','l','l','\\',0};
57 static const WCHAR wszFolder[] = {'F','o','l','d','e','r',0};
58 static const WCHAR wszEmpty[] = {0};
59
60 #define SEE_MASK_CLASSALL (SEE_MASK_CLASSNAME | SEE_MASK_CLASSKEY)
61
62
63 /***********************************************************************
64  *      SHELL_ArgifyW [Internal]
65  *
66  * this function is supposed to expand the escape sequences found in the registry
67  * some diving reported that the following were used:
68  * + %1, %2...  seem to report to parameter of index N in ShellExecute pmts
69  *      %1 file
70  *      %2 printer
71  *      %3 driver
72  *      %4 port
73  * %I address of a global item ID (explorer switch /idlist)
74  * %L seems to be %1 as long filename followed by the 8+3 variation
75  * %S ???
76  * %* all following parameters (see batfile)
77  *
78  */
79 static BOOL SHELL_ArgifyW(WCHAR* out, int len, const WCHAR* fmt, const WCHAR* lpFile, LPITEMIDLIST pidl, LPCWSTR args, DWORD* out_len)
80 {
81     WCHAR   xlpFile[1024];
82     BOOL    done = FALSE;
83     BOOL    found_p1 = FALSE;
84     PWSTR   res = out;
85     PCWSTR  cmd;
86     DWORD   used = 0;
87
88     TRACE("%p, %d, %s, %s, %p, %p\n", out, len, debugstr_w(fmt),
89           debugstr_w(lpFile), pidl, args);
90
91     while (*fmt)
92     {
93         if (*fmt == '%')
94         {
95             switch (*++fmt)
96             {
97             case '\0':
98             case '%':
99                 used++;
100                 if (used < len)
101                     *res++ = '%';
102                 break;
103
104             case '2':
105             case '3':
106             case '4':
107             case '5':
108             case '6':
109             case '7':
110             case '8':
111             case '9':
112             case '0':
113             case '*':
114                 if (args)
115                 {
116                     if (*fmt == '*')
117                     {
118                         used++;
119                         if (used < len)
120                             *res++ = '"';
121                         while(*args)
122                         {
123                             used++;
124                             if (used < len)
125                                 *res++ = *args++;
126                             else
127                                 args++;
128                         }
129                         used++;
130                         if (used < len)
131                             *res++ = '"';
132                     }
133                     else
134                     {
135                         while(*args && !isspace(*args))
136                         {
137                             used++;
138                             if (used < len)
139                                 *res++ = *args++;
140                             else
141                                 args++;
142                         }
143
144                         while(isspace(*args))
145                             ++args;
146                     }
147                     break;
148                 }
149                 /* else fall through */
150             case '1':
151                 if (!done || (*fmt == '1'))
152                 {
153                     /*FIXME Is the call to SearchPathW() really needed? We already have separated out the parameter string in args. */
154                     if (SearchPathW(NULL, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
155                         cmd = xlpFile;
156                     else
157                         cmd = lpFile;
158
159                     used += strlenW(cmd);
160                     if (used < len)
161                     {
162                         strcpyW(res, cmd);
163                         res += strlenW(cmd);
164                     }
165                 }
166                 found_p1 = TRUE;
167                 break;
168
169             /*
170              * IE uses this a lot for activating things such as windows media
171              * player. This is not verified to be fully correct but it appears
172              * to work just fine.
173              */
174             case 'l':
175             case 'L':
176                 if (lpFile) {
177                     used += strlenW(lpFile);
178                     if (used < len)
179                     {
180                         strcpyW(res, lpFile);
181                         res += strlenW(lpFile);
182                     }
183                 }
184                 found_p1 = TRUE;
185                 break;
186
187             case 'i':
188             case 'I':
189                 if (pidl) {
190                     INT chars = 0;
191                     /* %p should not exceed 8, maybe 16 when looking foward to 64bit.
192                      * allowing a buffer of 100 should more than exceed all needs */
193                     WCHAR buf[100];
194                     LPVOID  pv;
195                     HGLOBAL hmem = SHAllocShared(pidl, ILGetSize(pidl), 0);
196                     pv = SHLockShared(hmem, 0);
197                     chars = sprintfW(buf, wszILPtr, pv);
198                     if (chars >= sizeof(buf)/sizeof(WCHAR))
199                         ERR("pidl format buffer too small!\n");
200                     used += chars;
201                     if (used < len)
202                     {
203                         strcpyW(res,buf);
204                         res += chars;
205                     }
206                     SHUnlockShared(pv);
207                 }
208                 found_p1 = TRUE;
209                 break;
210
211             default:
212                 /*
213                  * Check if this is an env-variable here...
214                  */
215
216                 /* Make sure that we have at least one more %.*/
217                 if (strchrW(fmt, '%'))
218                 {
219                     WCHAR   tmpBuffer[1024];
220                     PWSTR   tmpB = tmpBuffer;
221                     WCHAR   tmpEnvBuff[MAX_PATH];
222                     DWORD   envRet;
223
224                     while (*fmt != '%')
225                         *tmpB++ = *fmt++;
226                     *tmpB++ = 0;
227
228                     TRACE("Checking %s to be an env-var\n", debugstr_w(tmpBuffer));
229
230                     envRet = GetEnvironmentVariableW(tmpBuffer, tmpEnvBuff, MAX_PATH);
231                     if (envRet == 0 || envRet > MAX_PATH)
232                     {
233                         used += strlenW(tmpBuffer);
234                         if (used < len)
235                         {
236                             strcpyW( res, tmpBuffer );
237                             res += strlenW(tmpBuffer);
238                         }
239                     }
240                     else
241                     {
242                         used += strlenW(tmpEnvBuff);
243                         if (used < len)
244                         {
245                             strcpyW( res, tmpEnvBuff );
246                             res += strlenW(tmpEnvBuff);
247                         }
248                     }
249                 }
250                 done = TRUE;
251                 break;
252             }
253             /* Don't skip past terminator (catch a single '%' at the end) */
254             if (*fmt != '\0')
255             {
256                 fmt++;
257             }
258         }
259         else
260         {
261             used ++;
262             if (used < len) 
263                 *res++ = *fmt++;
264             else
265                 fmt++;
266         }
267     }
268
269     *res = '\0';
270     TRACE("used %i of %i space\n",used,len);
271     if (out_len)
272         *out_len = used;
273
274     return found_p1;
275 }
276
277 static HRESULT SHELL_GetPathFromIDListForExecuteW(LPCITEMIDLIST pidl, LPWSTR pszPath, UINT uOutSize)
278 {
279     STRRET strret;
280     IShellFolder* desktop;
281
282     HRESULT hr = SHGetDesktopFolder(&desktop);
283
284     if (SUCCEEDED(hr)) {
285         hr = IShellFolder_GetDisplayNameOf(desktop, pidl, SHGDN_FORPARSING, &strret);
286
287         if (SUCCEEDED(hr))
288             StrRetToStrNW(pszPath, uOutSize, &strret, pidl);
289
290         IShellFolder_Release(desktop);
291     }
292
293     return hr;
294 }
295
296 /*************************************************************************
297  *      SHELL_ExecuteW [Internal]
298  *
299  */
300 static UINT_PTR SHELL_ExecuteW(const WCHAR *lpCmd, WCHAR *env, BOOL shWait,
301                             const SHELLEXECUTEINFOW *psei, LPSHELLEXECUTEINFOW psei_out)
302 {
303     STARTUPINFOW  startup;
304     PROCESS_INFORMATION info;
305     UINT_PTR retval = SE_ERR_NOASSOC;
306     UINT gcdret = 0;
307     WCHAR curdir[MAX_PATH];
308     DWORD dwCreationFlags;
309     const WCHAR *lpDirectory = NULL;
310
311     TRACE("Execute %s from directory %s\n", debugstr_w(lpCmd), debugstr_w(psei->lpDirectory));
312
313     /* make sure we don't fail the CreateProcess if the calling app passes in
314      * a bad working directory */
315     if (psei->lpDirectory && psei->lpDirectory[0])
316     {
317         DWORD attr = GetFileAttributesW(psei->lpDirectory);
318         if (attr != INVALID_FILE_ATTRIBUTES && attr & FILE_ATTRIBUTE_DIRECTORY)
319             lpDirectory = psei->lpDirectory;
320     }
321
322     /* ShellExecute specifies the command from psei->lpDirectory
323      * if present. Not from the current dir as CreateProcess does */
324     if( lpDirectory )
325         if( ( gcdret = GetCurrentDirectoryW( MAX_PATH, curdir)))
326             if( !SetCurrentDirectoryW( lpDirectory))
327                 ERR("cannot set directory %s\n", debugstr_w(lpDirectory));
328     ZeroMemory(&startup,sizeof(STARTUPINFOW));
329     startup.cb = sizeof(STARTUPINFOW);
330     startup.dwFlags = STARTF_USESHOWWINDOW;
331     startup.wShowWindow = psei->nShow;
332     dwCreationFlags = CREATE_UNICODE_ENVIRONMENT;
333     if (psei->fMask & SEE_MASK_NO_CONSOLE)
334         dwCreationFlags |= CREATE_NEW_CONSOLE;
335     if (CreateProcessW(NULL, (LPWSTR)lpCmd, NULL, NULL, FALSE, dwCreationFlags, env,
336                        lpDirectory, &startup, &info))
337     {
338         /* Give 30 seconds to the app to come up, if desired. Probably only needed
339            when starting app immediately before making a DDE connection. */
340         if (shWait)
341             if (WaitForInputIdle( info.hProcess, 30000 ) == WAIT_FAILED)
342                 WARN("WaitForInputIdle failed: Error %d\n", GetLastError() );
343         retval = 33;
344         if (psei->fMask & SEE_MASK_NOCLOSEPROCESS)
345             psei_out->hProcess = info.hProcess;
346         else
347             CloseHandle( info.hProcess );
348         CloseHandle( info.hThread );
349     }
350     else if ((retval = GetLastError()) >= 32)
351     {
352         TRACE("CreateProcess returned error %ld\n", retval);
353         retval = ERROR_BAD_FORMAT;
354     }
355
356     TRACE("returning %lu\n", retval);
357
358     psei_out->hInstApp = (HINSTANCE)retval;
359     if( gcdret )
360         if( !SetCurrentDirectoryW( curdir))
361             ERR("cannot return to directory %s\n", debugstr_w(curdir));
362
363     return retval;
364 }
365
366
367 /***********************************************************************
368  *           SHELL_BuildEnvW    [Internal]
369  *
370  * Build the environment for the new process, adding the specified
371  * path to the PATH variable. Returned pointer must be freed by caller.
372  */
373 static void *SHELL_BuildEnvW( const WCHAR *path )
374 {
375     static const WCHAR wPath[] = {'P','A','T','H','=',0};
376     WCHAR *strings, *new_env;
377     WCHAR *p, *p2;
378     int total = strlenW(path) + 1;
379     BOOL got_path = FALSE;
380
381     if (!(strings = GetEnvironmentStringsW())) return NULL;
382     p = strings;
383     while (*p)
384     {
385         int len = strlenW(p) + 1;
386         if (!strncmpiW( p, wPath, 5 )) got_path = TRUE;
387         total += len;
388         p += len;
389     }
390     if (!got_path) total += 5;  /* we need to create PATH */
391     total++;  /* terminating null */
392
393     if (!(new_env = HeapAlloc( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
394     {
395         FreeEnvironmentStringsW( strings );
396         return NULL;
397     }
398     p = strings;
399     p2 = new_env;
400     while (*p)
401     {
402         int len = strlenW(p) + 1;
403         memcpy( p2, p, len * sizeof(WCHAR) );
404         if (!strncmpiW( p, wPath, 5 ))
405         {
406             p2[len - 1] = ';';
407             strcpyW( p2 + len, path );
408             p2 += strlenW(path) + 1;
409         }
410         p += len;
411         p2 += len;
412     }
413     if (!got_path)
414     {
415         strcpyW( p2, wPath );
416         strcatW( p2, path );
417         p2 += strlenW(p2) + 1;
418     }
419     *p2 = 0;
420     FreeEnvironmentStringsW( strings );
421     return new_env;
422 }
423
424
425 /***********************************************************************
426  *           SHELL_TryAppPathW  [Internal]
427  *
428  * Helper function for SHELL_FindExecutable
429  * @param lpResult - pointer to a buffer of size MAX_PATH
430  * On entry: szName is a filename (probably without path separators).
431  * On exit: if szName found in "App Path", place full path in lpResult, and return true
432  */
433 static BOOL SHELL_TryAppPathW( LPCWSTR szName, LPWSTR lpResult, WCHAR **env)
434 {
435     static const WCHAR wszKeyAppPaths[] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s',
436         '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','A','p','p',' ','P','a','t','h','s','\\',0};
437     static const WCHAR wPath[] = {'P','a','t','h',0};
438     HKEY hkApp = 0;
439     WCHAR buffer[1024];
440     LONG len;
441     LONG res;
442     BOOL found = FALSE;
443
444     if (env) *env = NULL;
445     strcpyW(buffer, wszKeyAppPaths);
446     strcatW(buffer, szName);
447     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hkApp);
448     if (res) goto end;
449
450     len = MAX_PATH*sizeof(WCHAR);
451     res = RegQueryValueW(hkApp, NULL, lpResult, &len);
452     if (res) goto end;
453     found = TRUE;
454
455     if (env)
456     {
457         DWORD count = sizeof(buffer);
458         if (!RegQueryValueExW(hkApp, wPath, NULL, NULL, (LPBYTE)buffer, &count) && buffer[0])
459             *env = SHELL_BuildEnvW( buffer );
460     }
461
462 end:
463     if (hkApp) RegCloseKey(hkApp);
464     return found;
465 }
466
467 static UINT SHELL_FindExecutableByOperation(LPCWSTR lpOperation, LPWSTR key, LPWSTR filetype, LPWSTR command, LONG commandlen)
468 {
469     static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
470     HKEY hkeyClass;
471     WCHAR verb[MAX_PATH];
472
473     if (RegOpenKeyExW(HKEY_CLASSES_ROOT, filetype, 0, 0x02000000, &hkeyClass))
474         return SE_ERR_NOASSOC;
475     if (!HCR_GetDefaultVerbW(hkeyClass, lpOperation, verb, sizeof(verb)))
476         return SE_ERR_NOASSOC;
477     RegCloseKey(hkeyClass);
478
479     /* Looking for ...buffer\shell\<verb>\command */
480     strcatW(filetype, wszShell);
481     strcatW(filetype, verb);
482     strcatW(filetype, wCommand);
483
484     if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, command,
485                        &commandlen) == ERROR_SUCCESS)
486     {
487         commandlen /= sizeof(WCHAR);
488         if (key) strcpyW(key, filetype);
489 #if 0
490         LPWSTR tmp;
491         WCHAR param[256];
492         LONG paramlen = sizeof(param);
493         static const WCHAR wSpace[] = {' ',0};
494
495         /* FIXME: it seems all Windows version don't behave the same here.
496          * the doc states that this ddeexec information can be found after
497          * the exec names.
498          * on Win98, it doesn't appear, but I think it does on Win2k
499          */
500         /* Get the parameters needed by the application
501            from the associated ddeexec key */
502         tmp = strstrW(filetype, wCommand);
503         tmp[0] = '\0';
504         strcatW(filetype, wDdeexec);
505         if (RegQueryValueW(HKEY_CLASSES_ROOT, filetype, param,
506                                      &paramlen) == ERROR_SUCCESS)
507         {
508             paramlen /= sizeof(WCHAR);
509             strcatW(command, wSpace);
510             strcatW(command, param);
511             commandlen += paramlen;
512         }
513 #endif
514
515         command[commandlen] = '\0';
516
517         return 33; /* FIXME see SHELL_FindExecutable() */
518     }
519
520     return SE_ERR_NOASSOC;
521 }
522
523 /*************************************************************************
524  *      SHELL_FindExecutable [Internal]
525  *
526  * Utility for code sharing between FindExecutable and ShellExecute
527  * in:
528  *      lpFile the name of a file
529  *      lpOperation the operation on it (open)
530  * out:
531  *      lpResult a buffer, big enough :-(, to store the command to do the
532  *              operation on the file
533  *      key a buffer, big enough, to get the key name to do actually the
534  *              command (it'll be used afterwards for more information
535  *              on the operation)
536  */
537 UINT SHELL_FindExecutable(LPCWSTR lpPath, LPCWSTR lpFile, LPCWSTR lpOperation,
538                                  LPWSTR lpResult, int resultLen, LPWSTR key, WCHAR **env, LPITEMIDLIST pidl, LPCWSTR args)
539 {
540     static const WCHAR wWindows[] = {'w','i','n','d','o','w','s',0};
541     static const WCHAR wPrograms[] = {'p','r','o','g','r','a','m','s',0};
542     static const WCHAR wExtensions[] = {'e','x','e',' ','p','i','f',' ','b','a','t',' ','c','m','d',' ','c','o','m',0};
543     WCHAR *extension = NULL; /* pointer to file extension */
544     WCHAR filetype[256];     /* registry name for this filetype */
545     LONG  filetypelen = sizeof(filetype); /* length of above */
546     WCHAR command[1024];     /* command from registry */
547     WCHAR wBuffer[256];      /* Used to GetProfileString */
548     UINT  retval = SE_ERR_NOASSOC;
549     WCHAR *tok;              /* token pointer */
550     WCHAR xlpFile[256];      /* result of SearchPath */
551     DWORD attribs;           /* file attributes */
552
553     TRACE("%s\n", debugstr_w(lpFile));
554
555     if (!lpResult)
556         return ERROR_INVALID_PARAMETER;
557
558     xlpFile[0] = '\0';
559     lpResult[0] = '\0'; /* Start off with an empty return string */
560     if (key) *key = '\0';
561
562     /* trap NULL parameters on entry */
563     if (!lpFile)
564     {
565         WARN("(lpFile=%s,lpResult=%s): NULL parameter\n",
566              debugstr_w(lpFile), debugstr_w(lpResult));
567         return ERROR_FILE_NOT_FOUND; /* File not found. Close enough, I guess. */
568     }
569
570     if (SHELL_TryAppPathW( lpFile, lpResult, env ))
571     {
572         TRACE("found %s via App Paths\n", debugstr_w(lpResult));
573         return 33;
574     }
575
576     if (SearchPathW(lpPath, lpFile, wszExe, sizeof(xlpFile)/sizeof(WCHAR), xlpFile, NULL))
577     {
578         TRACE("SearchPathW returned non-zero\n");
579         lpFile = xlpFile;
580         /* Hey, isn't this value ignored?  Why make this call?  Shouldn't we return here?  --dank*/
581     }
582
583     attribs = GetFileAttributesW(lpFile);
584     if (attribs!=INVALID_FILE_ATTRIBUTES && (attribs&FILE_ATTRIBUTE_DIRECTORY))
585     {
586        strcpyW(filetype, wszFolder);
587        filetypelen = 6;    /* strlen("Folder") */
588     }
589     else
590     {
591         /* First thing we need is the file's extension */
592         extension = strrchrW(xlpFile, '.'); /* Assume last "." is the one; */
593         /* File->Run in progman uses */
594         /* .\FILE.EXE :( */
595         TRACE("xlpFile=%s,extension=%s\n", debugstr_w(xlpFile), debugstr_w(extension));
596
597         if (extension == NULL || extension[1]==0)
598         {
599             WARN("Returning SE_ERR_NOASSOC\n");
600             return SE_ERR_NOASSOC;
601         }
602
603         /* Three places to check: */
604         /* 1. win.ini, [windows], programs (NB no leading '.') */
605         /* 2. Registry, HKEY_CLASS_ROOT\<filetype>\shell\open\command */
606         /* 3. win.ini, [extensions], extension (NB no leading '.' */
607         /* All I know of the order is that registry is checked before */
608         /* extensions; however, it'd make sense to check the programs */
609         /* section first, so that's what happens here. */
610
611         /* See if it's a program - if GetProfileString fails, we skip this
612          * section. Actually, if GetProfileString fails, we've probably
613          * got a lot more to worry about than running a program... */
614         if (GetProfileStringW(wWindows, wPrograms, wExtensions, wBuffer, sizeof(wBuffer)/sizeof(WCHAR)) > 0)
615         {
616             CharLowerW(wBuffer);
617             tok = wBuffer;
618             while (*tok)
619             {
620                 WCHAR *p = tok;
621                 while (*p && *p != ' ' && *p != '\t') p++;
622                 if (*p)
623                 {
624                     *p++ = 0;
625                     while (*p == ' ' || *p == '\t') p++;
626                 }
627
628                 if (strcmpiW(tok, &extension[1]) == 0) /* have to skip the leading "." */
629                 {
630                     strcpyW(lpResult, xlpFile);
631                     /* Need to perhaps check that the file has a path
632                      * attached */
633                     TRACE("found %s\n", debugstr_w(lpResult));
634                     return 33;
635                     /* Greater than 32 to indicate success */
636                 }
637                 tok = p;
638             }
639         }
640
641         /* Check registry */
642         if (RegQueryValueW(HKEY_CLASSES_ROOT, extension, filetype,
643                            &filetypelen) == ERROR_SUCCESS)
644         {
645             filetypelen /= sizeof(WCHAR);
646             if (filetypelen == sizeof(filetype)/sizeof(WCHAR))
647                 filetypelen--;
648             filetype[filetypelen] = '\0';
649             TRACE("File type: %s\n", debugstr_w(filetype));
650         }
651         else
652         {
653             *filetype = '\0';
654             filetypelen = 0;
655         }
656     }
657
658     if (*filetype)
659     {
660         /* pass the operation string to SHELL_FindExecutableByOperation() */
661         filetype[filetypelen] = '\0';
662         retval = SHELL_FindExecutableByOperation(lpOperation, key, filetype, command, sizeof(command));
663
664         if (retval > 32)
665         {
666             DWORD finishedLen;
667             SHELL_ArgifyW(lpResult, resultLen, command, xlpFile, pidl, args, &finishedLen);
668             if (finishedLen > resultLen)
669                 ERR("Argify buffer not large enough.. truncated\n");
670
671             /* Remove double quotation marks and command line arguments */
672             if (*lpResult == '"')
673             {
674                 WCHAR *p = lpResult;
675                 while (*(p + 1) != '"')
676                 {
677                     *p = *(p + 1);
678                     p++;
679                 }
680                 *p = '\0';
681             }
682             else
683             {
684                 /* Truncate on first space, like Windows:
685                  * http://support.microsoft.com/?scid=kb%3Ben-us%3B140724
686                  */
687                 WCHAR *p = lpResult;
688                 while (*p != ' ' && *p != '\0')
689                     p++;
690                 *p='\0';
691             }
692         }
693     }
694     else /* Check win.ini */
695     {
696         static const WCHAR wExtensions[] = {'e','x','t','e','n','s','i','o','n','s',0};
697
698         /* Toss the leading dot */
699         extension++;
700         if (GetProfileStringW(wExtensions, extension, wszEmpty, command, sizeof(command)/sizeof(WCHAR)) > 0)
701         {
702             if (strlenW(command) != 0)
703             {
704                 strcpyW(lpResult, command);
705                 tok = strchrW(lpResult, '^'); /* should be ^.extension? */
706                 if (tok != NULL)
707                 {
708                     tok[0] = '\0';
709                     strcatW(lpResult, xlpFile); /* what if no dir in xlpFile? */
710                     tok = strchrW(command, '^'); /* see above */
711                     if ((tok != NULL) && (strlenW(tok)>5))
712                     {
713                         strcatW(lpResult, &tok[5]);
714                     }
715                 }
716                 retval = 33; /* FIXME - see above */
717             }
718         }
719     }
720
721     TRACE("returning %s\n", debugstr_w(lpResult));
722     return retval;
723 }
724
725 /******************************************************************
726  *              dde_cb
727  *
728  * callback for the DDE connection. not really useful
729  */
730 static HDDEDATA CALLBACK dde_cb(UINT uType, UINT uFmt, HCONV hConv,
731                                 HSZ hsz1, HSZ hsz2, HDDEDATA hData,
732                                 ULONG_PTR dwData1, ULONG_PTR dwData2)
733 {
734     TRACE("dde_cb: %04x, %04x, %p, %p, %p, %p, %08lx, %08lx\n",
735            uType, uFmt, hConv, hsz1, hsz2, hData, dwData1, dwData2);
736     return NULL;
737 }
738
739 /******************************************************************
740  *              dde_connect
741  *
742  * ShellExecute helper. Used to do an operation with a DDE connection
743  *
744  * Handles both the direct connection (try #1), and if it fails,
745  * launching an application and trying (#2) to connect to it
746  *
747  */
748 static unsigned dde_connect(const WCHAR* key, const WCHAR* start, WCHAR* ddeexec,
749                             const WCHAR* lpFile, WCHAR *env,
750                             LPCWSTR szCommandline, LPITEMIDLIST pidl, SHELL_ExecuteW32 execfunc,
751                             const SHELLEXECUTEINFOW *psei, LPSHELLEXECUTEINFOW psei_out)
752 {
753     static const WCHAR wApplication[] = {'\\','a','p','p','l','i','c','a','t','i','o','n',0};
754     static const WCHAR wTopic[] = {'\\','t','o','p','i','c',0};
755     WCHAR       regkey[256];
756     WCHAR *     endkey = regkey + strlenW(key);
757     WCHAR       app[256], topic[256], ifexec[256], res[256];
758     LONG        applen, topiclen, ifexeclen;
759     WCHAR *     exec;
760     DWORD       ddeInst = 0;
761     DWORD       tid;
762     DWORD       resultLen;
763     HSZ         hszApp, hszTopic;
764     HCONV       hConv;
765     HDDEDATA    hDdeData;
766     unsigned    ret = SE_ERR_NOASSOC;
767     BOOL unicode = !(GetVersion() & 0x80000000);
768
769     strcpyW(regkey, key);
770     strcpyW(endkey, wApplication);
771     applen = sizeof(app);
772     if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, app, &applen) != ERROR_SUCCESS)
773     {
774         WCHAR command[1024], fullpath[MAX_PATH];
775         static const WCHAR wSo[] = { '.','s','o',0 };
776         int sizeSo = sizeof(wSo)/sizeof(WCHAR);
777         LPWSTR ptr = NULL;
778         DWORD ret = 0;
779
780         /* Get application command from start string and find filename of application */
781         if (*start == '"')
782         {
783             strcpyW(command, start+1);
784             if ((ptr = strchrW(command, '"')))
785                 *ptr = 0;
786             ret = SearchPathW(NULL, command, wszExe, sizeof(fullpath)/sizeof(WCHAR), fullpath, &ptr);
787         }
788         else
789         {
790             LPWSTR p,space;
791             for (p=(LPWSTR)start; (space=strchrW(p, ' ')); p=space+1)
792             {
793                 int idx = space-start;
794                 memcpy(command, start, idx*sizeof(WCHAR));
795                 command[idx] = '\0';
796                 if ((ret = SearchPathW(NULL, command, wszExe, sizeof(fullpath)/sizeof(WCHAR), fullpath, &ptr)))
797                     break;
798             }
799             if (!ret)
800                 ret = SearchPathW(NULL, start, wszExe, sizeof(fullpath)/sizeof(WCHAR), fullpath, &ptr);
801         }
802
803         if (!ret)
804         {
805             ERR("Unable to find application path for command %s\n", debugstr_w(start));
806             return ERROR_ACCESS_DENIED;
807         }
808         strcpyW(app, ptr);
809
810         /* Remove extensions (including .so) */
811         ptr = app + strlenW(app) - (sizeSo-1);
812         if (strlenW(app) >= sizeSo &&
813             !strcmpW(ptr, wSo))
814             *ptr = 0;
815
816         ptr = strrchrW(app, '.');
817         assert(ptr);
818         *ptr = 0;
819     }
820
821     strcpyW(endkey, wTopic);
822     topiclen = sizeof(topic);
823     if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, topic, &topiclen) != ERROR_SUCCESS)
824     {
825         static const WCHAR wSystem[] = {'S','y','s','t','e','m',0};
826         strcpyW(topic, wSystem);
827     }
828
829     if (unicode)
830     {
831         if (DdeInitializeW(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
832             return 2;
833     }
834     else
835     {
836         if (DdeInitializeA(&ddeInst, dde_cb, APPCMD_CLIENTONLY, 0L) != DMLERR_NO_ERROR)
837             return 2;
838     }
839
840     hszApp = DdeCreateStringHandleW(ddeInst, app, CP_WINUNICODE);
841     hszTopic = DdeCreateStringHandleW(ddeInst, topic, CP_WINUNICODE);
842
843     hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
844     exec = ddeexec;
845     if (!hConv)
846     {
847         static const WCHAR wIfexec[] = {'\\','i','f','e','x','e','c',0};
848         TRACE("Launching %s\n", debugstr_w(start));
849         ret = execfunc(start, env, TRUE, psei, psei_out);
850         if (ret <= 32)
851         {
852             TRACE("Couldn't launch\n");
853             goto error;
854         }
855         hConv = DdeConnect(ddeInst, hszApp, hszTopic, NULL);
856         if (!hConv)
857         {
858             TRACE("Couldn't connect. ret=%d\n", ret);
859             DdeUninitialize(ddeInst);
860             SetLastError(ERROR_DDE_FAIL);
861             return 30; /* whatever */
862         }
863         strcpyW(endkey, wIfexec);
864         ifexeclen = sizeof(ifexec);
865         if (RegQueryValueW(HKEY_CLASSES_ROOT, regkey, ifexec, &ifexeclen) == ERROR_SUCCESS)
866         {
867             exec = ifexec;
868         }
869     }
870
871     SHELL_ArgifyW(res, sizeof(res)/sizeof(WCHAR), exec, lpFile, pidl, szCommandline, &resultLen);
872     if (resultLen > sizeof(res)/sizeof(WCHAR))
873         ERR("Argify buffer not large enough, truncated\n");
874     TRACE("%s %s => %s\n", debugstr_w(exec), debugstr_w(lpFile), debugstr_w(res));
875
876     /* It's documented in the KB 330337 that IE has a bug and returns
877      * error DMLERR_NOTPROCESSED on XTYP_EXECUTE request.
878      */
879     if (unicode)
880         hDdeData = DdeClientTransaction((LPBYTE)res, (strlenW(res) + 1) * sizeof(WCHAR), hConv, 0L, 0,
881                                          XTYP_EXECUTE, 30000, &tid);
882     else
883     {
884         DWORD lenA = WideCharToMultiByte(CP_ACP, 0, res, -1, NULL, 0, NULL, NULL);
885         char *resA = HeapAlloc(GetProcessHeap(), 0, lenA);
886         WideCharToMultiByte(CP_ACP, 0, res, -1, resA, lenA, NULL, NULL);
887         hDdeData = DdeClientTransaction( (LPBYTE)resA, lenA, hConv, 0L, 0,
888                                          XTYP_EXECUTE, 10000, &tid );
889         HeapFree(GetProcessHeap(), 0, resA);
890     }
891     if (hDdeData)
892         DdeFreeDataHandle(hDdeData);
893     else
894         WARN("DdeClientTransaction failed with error %04x\n", DdeGetLastError(ddeInst));
895     ret = 33;
896
897     DdeDisconnect(hConv);
898
899  error:
900     DdeUninitialize(ddeInst);
901
902     return ret;
903 }
904
905 /*************************************************************************
906  *      execute_from_key [Internal]
907  */
908 static UINT_PTR execute_from_key(LPCWSTR key, LPCWSTR lpFile, WCHAR *env, LPCWSTR szCommandline,
909                              LPCWSTR executable_name,
910                              SHELL_ExecuteW32 execfunc,
911                              LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out)
912 {
913     static const WCHAR wCommand[] = {'c','o','m','m','a','n','d',0};
914     static const WCHAR wDdeexec[] = {'d','d','e','e','x','e','c',0};
915     WCHAR cmd[256], param[1024], ddeexec[256];
916     LONG cmdlen = sizeof(cmd), ddeexeclen = sizeof(ddeexec);
917     UINT_PTR retval = SE_ERR_NOASSOC;
918     DWORD resultLen;
919     LPWSTR tmp;
920
921     TRACE("%s %s %s %s %s\n", debugstr_w(key), debugstr_w(lpFile), debugstr_w(env),
922            debugstr_w(szCommandline), debugstr_w(executable_name));
923
924     cmd[0] = '\0';
925     param[0] = '\0';
926
927     /* Get the application from the registry */
928     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, cmd, &cmdlen) == ERROR_SUCCESS)
929     {
930         TRACE("got cmd: %s\n", debugstr_w(cmd));
931
932         /* Is there a replace() function anywhere? */
933         cmdlen /= sizeof(WCHAR);
934         cmd[cmdlen] = '\0';
935         SHELL_ArgifyW(param, sizeof(param)/sizeof(WCHAR), cmd, lpFile, psei->lpIDList, szCommandline, &resultLen);
936         if (resultLen > sizeof(param)/sizeof(WCHAR))
937             ERR("Argify buffer not large enough, truncating\n");
938     }
939
940     /* Get the parameters needed by the application
941        from the associated ddeexec key */
942     tmp = strstrW(key, wCommand);
943     assert(tmp);
944     strcpyW(tmp, wDdeexec);
945
946     if (RegQueryValueW(HKEY_CLASSES_ROOT, key, ddeexec, &ddeexeclen) == ERROR_SUCCESS)
947     {
948         TRACE("Got ddeexec %s => %s\n", debugstr_w(key), debugstr_w(ddeexec));
949         if (!param[0]) strcpyW(param, executable_name);
950         retval = dde_connect(key, param, ddeexec, lpFile, env, szCommandline, psei->lpIDList, execfunc, psei, psei_out);
951     }
952     else if (param[0])
953     {
954         TRACE("executing: %s\n", debugstr_w(param));
955         retval = execfunc(param, env, FALSE, psei, psei_out);
956     }
957     else
958         WARN("Nothing appropriate found for %s\n", debugstr_w(key));
959
960     return retval;
961 }
962
963 /*************************************************************************
964  * FindExecutableA                      [SHELL32.@]
965  */
966 HINSTANCE WINAPI FindExecutableA(LPCSTR lpFile, LPCSTR lpDirectory, LPSTR lpResult)
967 {
968     HINSTANCE retval;
969     WCHAR *wFile = NULL, *wDirectory = NULL;
970     WCHAR wResult[MAX_PATH];
971
972     if (lpFile) __SHCloneStrAtoW(&wFile, lpFile);
973     if (lpDirectory) __SHCloneStrAtoW(&wDirectory, lpDirectory);
974
975     retval = FindExecutableW(wFile, wDirectory, wResult);
976     WideCharToMultiByte(CP_ACP, 0, wResult, -1, lpResult, MAX_PATH, NULL, NULL);
977     SHFree( wFile );
978     SHFree( wDirectory );
979
980     TRACE("returning %s\n", lpResult);
981     return retval;
982 }
983
984 /*************************************************************************
985  * FindExecutableW                      [SHELL32.@]
986  *
987  * This function returns the executable associated with the specified file
988  * for the default verb.
989  *
990  * PARAMS
991  *  lpFile   [I] The file to find the association for. This must refer to
992  *               an existing file otherwise FindExecutable fails and returns
993  *               SE_ERR_FNF.
994  *  lpResult [O] Points to a buffer into which the executable path is
995  *               copied. This parameter must not be NULL otherwise
996  *               FindExecutable() segfaults. The buffer must be of size at
997  *               least MAX_PATH characters.
998  *
999  * RETURNS
1000  *  A value greater than 32 on success, less than or equal to 32 otherwise.
1001  *  See the SE_ERR_* constants.
1002  *
1003  * NOTES
1004  *  On Windows XP and 2003, FindExecutable() seems to first convert the
1005  *  filename into 8.3 format, thus taking into account only the first three
1006  *  characters of the extension, and expects to find an association for those.
1007  *  However other Windows versions behave sanely.
1008  */
1009 HINSTANCE WINAPI FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, LPWSTR lpResult)
1010 {
1011     UINT_PTR retval = SE_ERR_NOASSOC;
1012     WCHAR old_dir[1024];
1013
1014     TRACE("File %s, Dir %s\n", debugstr_w(lpFile), debugstr_w(lpDirectory));
1015
1016     lpResult[0] = '\0'; /* Start off with an empty return string */
1017     if (lpFile == NULL)
1018         return (HINSTANCE)SE_ERR_FNF;
1019
1020     if (lpDirectory)
1021     {
1022         GetCurrentDirectoryW(sizeof(old_dir)/sizeof(WCHAR), old_dir);
1023         SetCurrentDirectoryW(lpDirectory);
1024     }
1025
1026     retval = SHELL_FindExecutable(lpDirectory, lpFile, wszOpen, lpResult, MAX_PATH, NULL, NULL, NULL, NULL);
1027
1028     TRACE("returning %s\n", debugstr_w(lpResult));
1029     if (lpDirectory)
1030         SetCurrentDirectoryW(old_dir);
1031     return (HINSTANCE)retval;
1032 }
1033
1034 /* FIXME: is this already implemented somewhere else? */
1035 static HKEY ShellExecute_GetClassKey( const SHELLEXECUTEINFOW *sei )
1036 {
1037     LPCWSTR ext = NULL, lpClass = NULL;
1038     LPWSTR cls = NULL;
1039     DWORD type = 0, sz = 0;
1040     HKEY hkey = 0;
1041     LONG r;
1042
1043     if (sei->fMask & SEE_MASK_CLASSALL)
1044         return sei->hkeyClass;
1045  
1046     if (sei->fMask & SEE_MASK_CLASSNAME)
1047         lpClass = sei->lpClass;
1048     else
1049     {
1050         ext = PathFindExtensionW( sei->lpFile );
1051         TRACE("ext = %s\n", debugstr_w( ext ) );
1052         if (!ext)
1053             return hkey;
1054
1055         r = RegOpenKeyW( HKEY_CLASSES_ROOT, ext, &hkey );
1056         if (r != ERROR_SUCCESS )
1057             return hkey;
1058
1059         r = RegQueryValueExW( hkey, NULL, 0, &type, NULL, &sz );
1060         if ( r == ERROR_SUCCESS && type == REG_SZ )
1061         {
1062             sz += sizeof (WCHAR);
1063             cls = HeapAlloc( GetProcessHeap(), 0, sz );
1064             cls[0] = 0;
1065             RegQueryValueExW( hkey, NULL, 0, &type, (LPBYTE) cls, &sz );
1066         }
1067
1068         RegCloseKey( hkey );
1069         lpClass = cls;
1070     }
1071
1072     TRACE("class = %s\n", debugstr_w(lpClass) );
1073
1074     hkey = 0;
1075     if ( lpClass )
1076         RegOpenKeyW( HKEY_CLASSES_ROOT, lpClass, &hkey );
1077
1078     HeapFree( GetProcessHeap(), 0, cls );
1079
1080     return hkey;
1081 }
1082
1083 static IDataObject *shellex_get_dataobj( LPSHELLEXECUTEINFOW sei )
1084 {
1085     LPCITEMIDLIST pidllast = NULL;
1086     IDataObject *dataobj = NULL;
1087     IShellFolder *shf = NULL;
1088     LPITEMIDLIST pidl = NULL;
1089     HRESULT r;
1090
1091     if (sei->fMask & SEE_MASK_CLASSALL)
1092         pidl = sei->lpIDList;
1093     else
1094     {
1095         WCHAR fullpath[MAX_PATH];
1096
1097         fullpath[0] = 0;
1098         r = GetFullPathNameW( sei->lpFile, MAX_PATH, fullpath, NULL );
1099         if (!r)
1100             goto end;
1101
1102         pidl = ILCreateFromPathW( fullpath );
1103     }
1104
1105     r = SHBindToParent( pidl, &IID_IShellFolder, (LPVOID*)&shf, &pidllast );
1106     if ( FAILED( r ) )
1107         goto end;
1108
1109     IShellFolder_GetUIObjectOf( shf, NULL, 1, &pidllast,
1110                                 &IID_IDataObject, NULL, (LPVOID*) &dataobj );
1111
1112 end:
1113     if ( pidl != sei->lpIDList )
1114         ILFree( pidl );
1115     if ( shf )
1116         IShellFolder_Release( shf );
1117     return dataobj;
1118 }
1119
1120 static HRESULT shellex_run_context_menu_default( IShellExtInit *obj,
1121                                                  LPSHELLEXECUTEINFOW sei )
1122 {
1123     IContextMenu *cm = NULL;
1124     CMINVOKECOMMANDINFOEX ici;
1125     MENUITEMINFOW info;
1126     WCHAR string[0x80];
1127     INT i, n, def = -1;
1128     HMENU hmenu = 0;
1129     HRESULT r;
1130
1131     TRACE("%p %p\n", obj, sei );
1132
1133     r = IShellExtInit_QueryInterface( obj, &IID_IContextMenu, (LPVOID*) &cm );
1134     if ( FAILED( r ) )
1135         return r;
1136
1137     hmenu = CreateMenu();
1138     if ( !hmenu )
1139         goto end;
1140
1141     /* the number of the last menu added is returned in r */
1142     r = IContextMenu_QueryContextMenu( cm, hmenu, 0, 0x20, 0x7fff, CMF_DEFAULTONLY );
1143     if ( FAILED( r ) )
1144         goto end;
1145
1146     n = GetMenuItemCount( hmenu );
1147     for ( i = 0; i < n; i++ )
1148     {
1149         memset( &info, 0, sizeof info );
1150         info.cbSize = sizeof info;
1151         info.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_STATE | MIIM_DATA | MIIM_ID;
1152         info.dwTypeData = string;
1153         info.cch = sizeof string;
1154         string[0] = 0;
1155         GetMenuItemInfoW( hmenu, i, TRUE, &info );
1156
1157         TRACE("menu %d %s %08x %08lx %08x %08x\n", i, debugstr_w(string),
1158             info.fState, info.dwItemData, info.fType, info.wID );
1159         if ( ( !sei->lpVerb && (info.fState & MFS_DEFAULT) ) ||
1160              ( sei->lpVerb && !lstrcmpiW( sei->lpVerb, string ) ) )
1161         {
1162             def = i;
1163             break;
1164         }
1165     }
1166
1167     r = E_FAIL;
1168     if ( def == -1 )
1169         goto end;
1170
1171     memset( &ici, 0, sizeof ici );
1172     ici.cbSize = sizeof ici;
1173     ici.fMask = CMIC_MASK_UNICODE | (sei->fMask & (SEE_MASK_NOASYNC|SEE_MASK_ASYNCOK|SEE_MASK_FLAG_NO_UI));
1174     ici.nShow = sei->nShow;
1175     ici.lpVerb = MAKEINTRESOURCEA( def );
1176     ici.hwnd = sei->hwnd;
1177     ici.lpParametersW = sei->lpParameters;
1178     
1179     r = IContextMenu_InvokeCommand( cm, (LPCMINVOKECOMMANDINFO) &ici );
1180
1181     TRACE("invoke command returned %08x\n", r );
1182
1183 end:
1184     if ( hmenu )
1185         DestroyMenu( hmenu );
1186     if ( cm )
1187         IContextMenu_Release( cm );
1188     return r;
1189 }
1190
1191 static HRESULT shellex_load_object_and_run( HKEY hkey, LPCGUID guid, LPSHELLEXECUTEINFOW sei )
1192 {
1193     IDataObject *dataobj = NULL;
1194     IObjectWithSite *ows = NULL;
1195     IShellExtInit *obj = NULL;
1196     HRESULT r;
1197
1198     TRACE("%p %s %p\n", hkey, debugstr_guid( guid ), sei );
1199
1200     r = CoInitialize( NULL );
1201     if ( FAILED( r ) )
1202         goto end;
1203
1204     r = CoCreateInstance( guid, NULL, CLSCTX_INPROC_SERVER,
1205                            &IID_IShellExtInit, (LPVOID*)&obj );
1206     if ( FAILED( r ) )
1207     {
1208         ERR("failed %08x\n", r );
1209         goto end;
1210     }
1211
1212     dataobj = shellex_get_dataobj( sei );
1213     if ( !dataobj )
1214     {
1215         ERR("failed to get data object\n");
1216         goto end;
1217     }
1218
1219     r = IShellExtInit_Initialize( obj, NULL, dataobj, hkey );
1220     if ( FAILED( r ) )
1221         goto end;
1222
1223     r = IShellExtInit_QueryInterface( obj, &IID_IObjectWithSite, (LPVOID*) &ows );
1224     if ( FAILED( r ) )
1225         goto end;
1226
1227     IObjectWithSite_SetSite( ows, NULL );
1228
1229     r = shellex_run_context_menu_default( obj, sei );
1230
1231 end:
1232     if ( ows )
1233         IObjectWithSite_Release( ows );
1234     if ( dataobj )
1235         IDataObject_Release( dataobj );
1236     if ( obj )
1237         IShellExtInit_Release( obj );
1238     CoUninitialize();
1239     return r;
1240 }
1241
1242
1243 /*************************************************************************
1244  *      ShellExecute_FromContextMenu [Internal]
1245  */
1246 static LONG ShellExecute_FromContextMenu( LPSHELLEXECUTEINFOW sei )
1247 {
1248     static const WCHAR szcm[] = { 's','h','e','l','l','e','x','\\',
1249         'C','o','n','t','e','x','t','M','e','n','u','H','a','n','d','l','e','r','s',0 };
1250     HKEY hkey, hkeycm = 0;
1251     WCHAR szguid[39];
1252     HRESULT hr;
1253     GUID guid;
1254     DWORD i;
1255     LONG r;
1256
1257     TRACE("%s\n", debugstr_w(sei->lpFile) );
1258
1259     hkey = ShellExecute_GetClassKey( sei );
1260     if ( !hkey )
1261         return ERROR_FUNCTION_FAILED;
1262
1263     r = RegOpenKeyW( hkey, szcm, &hkeycm );
1264     if ( r == ERROR_SUCCESS )
1265     {
1266         i = 0;
1267         while ( 1 )
1268         {
1269             r = RegEnumKeyW( hkeycm, i++, szguid, 39 );
1270             if ( r != ERROR_SUCCESS )
1271                 break;
1272
1273             hr = CLSIDFromString( szguid, &guid );
1274             if (SUCCEEDED(hr))
1275             {
1276                 /* stop at the first one that succeeds in running */
1277                 hr = shellex_load_object_and_run( hkey, &guid, sei );
1278                 if ( SUCCEEDED( hr ) )
1279                     break;
1280             }
1281         }
1282         RegCloseKey( hkeycm );
1283     }
1284
1285     if ( hkey != sei->hkeyClass )
1286         RegCloseKey( hkey );
1287     return r;
1288 }
1289
1290 static UINT_PTR SHELL_execute_class( LPCWSTR wszApplicationName, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
1291 {
1292     static const WCHAR wSpace[] = {' ',0};
1293     WCHAR execCmd[1024], wcmd[1024];
1294     /* launch a document by fileclass like 'WordPad.Document.1' */
1295     /* the Commandline contains 'c:\Path\wordpad.exe "%1"' */
1296     /* FIXME: wcmd should not be of a fixed size. Fixed to 1024, MAX_PATH is way too short! */
1297     ULONG cmask=(psei->fMask & SEE_MASK_CLASSALL);
1298     DWORD resultLen;
1299     BOOL done;
1300
1301     HCR_GetExecuteCommandW((cmask == SEE_MASK_CLASSKEY) ? psei->hkeyClass : NULL,
1302                            (cmask == SEE_MASK_CLASSNAME) ? psei->lpClass: NULL,
1303                            psei->lpVerb,
1304                            execCmd, sizeof(execCmd));
1305
1306     /* FIXME: get the extension of lpFile, check if it fits to the lpClass */
1307     TRACE("SEE_MASK_CLASSNAME->%s, doc->%s\n", debugstr_w(execCmd), debugstr_w(wszApplicationName));
1308
1309     wcmd[0] = '\0';
1310     done = SHELL_ArgifyW(wcmd, sizeof(wcmd)/sizeof(WCHAR), execCmd, wszApplicationName, psei->lpIDList, NULL, &resultLen);
1311     if (!done && wszApplicationName[0])
1312     {
1313         strcatW(wcmd, wSpace);
1314         strcatW(wcmd, wszApplicationName);
1315     }
1316     if (resultLen > sizeof(wcmd)/sizeof(WCHAR))
1317         ERR("Argify buffer not large enough... truncating\n");
1318     return execfunc(wcmd, NULL, FALSE, psei, psei_out);
1319 }
1320
1321 static BOOL SHELL_translate_idlist( LPSHELLEXECUTEINFOW sei, LPWSTR wszParameters, DWORD parametersLen, LPWSTR wszApplicationName, DWORD dwApplicationNameLen )
1322 {
1323     static const WCHAR wExplorer[] = {'e','x','p','l','o','r','e','r','.','e','x','e',0};
1324     WCHAR buffer[MAX_PATH];
1325     BOOL appKnownSingular = FALSE;
1326
1327     /* last chance to translate IDList: now also allow CLSID paths */
1328     if (SUCCEEDED(SHELL_GetPathFromIDListForExecuteW(sei->lpIDList, buffer, sizeof(buffer)))) {
1329         if (buffer[0]==':' && buffer[1]==':') {
1330             /* open shell folder for the specified class GUID */
1331             if (lstrlenW(buffer) + 1 > parametersLen)
1332                 ERR("parameters len exceeds buffer size (%i > %i), truncating\n",
1333                     lstrlenW(buffer) + 1, parametersLen);
1334             lstrcpynW(wszParameters, buffer, parametersLen);
1335             if (lstrlenW(wExplorer) > dwApplicationNameLen)
1336                 ERR("application len exceeds buffer size (%i > %i), truncating\n",
1337                     lstrlenW(wExplorer) + 1, dwApplicationNameLen);
1338             lstrcpynW(wszApplicationName, wExplorer, dwApplicationNameLen);
1339             appKnownSingular = TRUE;
1340
1341             sei->fMask &= ~SEE_MASK_INVOKEIDLIST;
1342         } else {
1343             WCHAR target[MAX_PATH];
1344             DWORD attribs;
1345             DWORD resultLen;
1346             /* Check if we're executing a directory and if so use the
1347                handler for the Folder class */
1348             strcpyW(target, buffer);
1349             attribs = GetFileAttributesW(buffer);
1350             if (attribs != INVALID_FILE_ATTRIBUTES &&
1351                 (attribs & FILE_ATTRIBUTE_DIRECTORY) &&
1352                 HCR_GetExecuteCommandW(0, wszFolder,
1353                                        sei->lpVerb,
1354                                        buffer, sizeof(buffer))) {
1355                 SHELL_ArgifyW(wszApplicationName, dwApplicationNameLen,
1356                               buffer, target, sei->lpIDList, NULL, &resultLen);
1357                 if (resultLen > dwApplicationNameLen)
1358                     ERR("Argify buffer not large enough... truncating\n");
1359                 appKnownSingular = FALSE;
1360             }
1361             sei->fMask &= ~SEE_MASK_INVOKEIDLIST;
1362         }
1363     }
1364     return appKnownSingular;
1365 }
1366
1367 static UINT_PTR SHELL_quote_and_execute( LPCWSTR wcmd, LPCWSTR wszParameters, LPCWSTR lpstrProtocol, LPCWSTR wszApplicationName, LPWSTR env, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
1368 {
1369     static const WCHAR wQuote[] = {'"',0};
1370     static const WCHAR wSpace[] = {' ',0};
1371     UINT_PTR retval;
1372     DWORD len;
1373     WCHAR *wszQuotedCmd;
1374
1375     /* Length of quotes plus length of command plus NULL terminator */
1376     len = 2 + lstrlenW(wcmd) + 1;
1377     if (wszParameters[0])
1378     {
1379         /* Length of space plus length of parameters */
1380         len += 1 + lstrlenW(wszParameters);
1381     }
1382     wszQuotedCmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1383     /* Must quote to handle case where cmd contains spaces,
1384      * else security hole if malicious user creates executable file "C:\\Program"
1385      */
1386     strcpyW(wszQuotedCmd, wQuote);
1387     strcatW(wszQuotedCmd, wcmd);
1388     strcatW(wszQuotedCmd, wQuote);
1389     if (wszParameters[0]) {
1390         strcatW(wszQuotedCmd, wSpace);
1391         strcatW(wszQuotedCmd, wszParameters);
1392     }
1393     TRACE("%s/%s => %s/%s\n", debugstr_w(wszApplicationName), debugstr_w(psei->lpVerb), debugstr_w(wszQuotedCmd), debugstr_w(lpstrProtocol));
1394     if (*lpstrProtocol)
1395         retval = execute_from_key(lpstrProtocol, wszApplicationName, env, psei->lpParameters, wcmd, execfunc, psei, psei_out);
1396     else
1397         retval = execfunc(wszQuotedCmd, env, FALSE, psei, psei_out);
1398     HeapFree(GetProcessHeap(), 0, wszQuotedCmd);
1399     return retval;
1400 }
1401
1402 static UINT_PTR SHELL_execute_url( LPCWSTR lpFile, LPCWSTR wFile, LPCWSTR wcmd, LPSHELLEXECUTEINFOW psei, LPSHELLEXECUTEINFOW psei_out, SHELL_ExecuteW32 execfunc )
1403 {
1404     static const WCHAR wShell[] = {'\\','s','h','e','l','l','\\',0};
1405     static const WCHAR wCommand[] = {'\\','c','o','m','m','a','n','d',0};
1406     UINT_PTR retval;
1407     WCHAR *lpstrProtocol;
1408     LPCWSTR lpstrRes;
1409     INT iSize;
1410     DWORD len;
1411
1412     lpstrRes = strchrW(lpFile, ':');
1413     if (lpstrRes)
1414         iSize = lpstrRes - lpFile;
1415     else
1416         iSize = strlenW(lpFile);
1417
1418     TRACE("Got URL: %s\n", debugstr_w(lpFile));
1419     /* Looking for ...protocol\shell\lpOperation\command */
1420     len = iSize + lstrlenW(wShell) + lstrlenW(wCommand) + 1;
1421     if (psei->lpVerb)
1422         len += lstrlenW(psei->lpVerb);
1423     else
1424         len += lstrlenW(wszOpen);
1425     lpstrProtocol = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1426     memcpy(lpstrProtocol, lpFile, iSize*sizeof(WCHAR));
1427     lpstrProtocol[iSize] = '\0';
1428     strcatW(lpstrProtocol, wShell);
1429     strcatW(lpstrProtocol, psei->lpVerb? psei->lpVerb: wszOpen);
1430     strcatW(lpstrProtocol, wCommand);
1431
1432     /* Remove File Protocol from lpFile */
1433     /* In the case file://path/file     */
1434     if (!strncmpiW(lpFile, wFile, iSize))
1435     {
1436         lpFile += iSize;
1437         while (*lpFile == ':') lpFile++;
1438     }
1439     retval = execute_from_key(lpstrProtocol, lpFile, NULL, psei->lpParameters,
1440                               wcmd, execfunc, psei, psei_out);
1441     HeapFree(GetProcessHeap(), 0, lpstrProtocol);
1442     return retval;
1443 }
1444
1445 /*************************************************************************
1446  *      SHELL_execute [Internal]
1447  */
1448 BOOL SHELL_execute( LPSHELLEXECUTEINFOW sei, SHELL_ExecuteW32 execfunc )
1449 {
1450     static const WCHAR wSpace[] = {' ',0};
1451     static const WCHAR wWww[] = {'w','w','w',0};
1452     static const WCHAR wFile[] = {'f','i','l','e',0};
1453     static const WCHAR wHttp[] = {'h','t','t','p',':','/','/',0};
1454     static const DWORD unsupportedFlags =
1455         SEE_MASK_INVOKEIDLIST  | SEE_MASK_ICON         | SEE_MASK_HOTKEY |
1456         SEE_MASK_CONNECTNETDRV | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI |
1457         SEE_MASK_UNICODE       | SEE_MASK_ASYNCOK      | SEE_MASK_HMONITOR;
1458
1459     WCHAR parametersBuffer[1024], dirBuffer[MAX_PATH], wcmdBuffer[1024];
1460     WCHAR *wszApplicationName, *wszParameters, *wszDir, *wcmd;
1461     DWORD dwApplicationNameLen = MAX_PATH+2;
1462     DWORD parametersLen = sizeof(parametersBuffer) / sizeof(WCHAR);
1463     DWORD dirLen = sizeof(dirBuffer) / sizeof(WCHAR);
1464     DWORD wcmdLen = sizeof(wcmdBuffer) / sizeof(WCHAR);
1465     DWORD len;
1466     SHELLEXECUTEINFOW sei_tmp;  /* modifiable copy of SHELLEXECUTEINFO struct */
1467     WCHAR wfileName[MAX_PATH];
1468     WCHAR *env;
1469     WCHAR lpstrProtocol[256];
1470     LPCWSTR lpFile;
1471     UINT_PTR retval = SE_ERR_NOASSOC;
1472     BOOL appKnownSingular = FALSE;
1473
1474     /* make a local copy of the LPSHELLEXECUTEINFO structure and work with this from now on */
1475     memcpy(&sei_tmp, sei, sizeof(sei_tmp));
1476
1477     TRACE("mask=0x%08x hwnd=%p verb=%s file=%s parm=%s dir=%s show=0x%08x class=%s\n",
1478             sei_tmp.fMask, sei_tmp.hwnd, debugstr_w(sei_tmp.lpVerb),
1479             debugstr_w(sei_tmp.lpFile), debugstr_w(sei_tmp.lpParameters),
1480             debugstr_w(sei_tmp.lpDirectory), sei_tmp.nShow,
1481             ((sei_tmp.fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME) ?
1482                 debugstr_w(sei_tmp.lpClass) : "not used");
1483
1484     sei->hProcess = NULL;
1485
1486     /* make copies of all path/command strings */
1487     if (!sei_tmp.lpFile)
1488     {
1489         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1490         *wszApplicationName = '\0';
1491     }
1492     else if (*sei_tmp.lpFile == '\"')
1493     {
1494         DWORD l = strlenW(sei_tmp.lpFile+1);
1495         if(l >= dwApplicationNameLen) dwApplicationNameLen = l+1;
1496         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1497         memcpy(wszApplicationName, sei_tmp.lpFile+1, (l+1)*sizeof(WCHAR));
1498         if (wszApplicationName[l-1] == '\"')
1499             wszApplicationName[l-1] = '\0';
1500         appKnownSingular = TRUE;
1501         TRACE("wszApplicationName=%s\n",debugstr_w(wszApplicationName));
1502     } else {
1503         DWORD l = strlenW(sei_tmp.lpFile)+1;
1504         if(l > dwApplicationNameLen) dwApplicationNameLen = l+1;
1505         wszApplicationName = HeapAlloc(GetProcessHeap(), 0, dwApplicationNameLen*sizeof(WCHAR));
1506         memcpy(wszApplicationName, sei_tmp.lpFile, l*sizeof(WCHAR));
1507     }
1508
1509     wszParameters = parametersBuffer;
1510     if (sei_tmp.lpParameters)
1511     {
1512         len = lstrlenW(sei_tmp.lpParameters) + 1;
1513         if (len > parametersLen)
1514         {
1515             wszParameters = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1516             parametersLen = len;
1517         }
1518         strcpyW(wszParameters, sei_tmp.lpParameters);
1519     }
1520     else
1521         *wszParameters = '\0';
1522
1523     wszDir = dirBuffer;
1524     if (sei_tmp.lpDirectory)
1525     {
1526         len = lstrlenW(sei_tmp.lpDirectory) + 1;
1527         if (len > dirLen)
1528         {
1529             wszDir = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1530             dirLen = len;
1531         }
1532         strcpyW(wszDir, sei_tmp.lpDirectory);
1533     }
1534     else
1535         *wszDir = '\0';
1536
1537     /* adjust string pointers to point to the new buffers */
1538     sei_tmp.lpFile = wszApplicationName;
1539     sei_tmp.lpParameters = wszParameters;
1540     sei_tmp.lpDirectory = wszDir;
1541
1542     if (sei_tmp.fMask & unsupportedFlags)
1543     {
1544         FIXME("flags ignored: 0x%08x\n", sei_tmp.fMask & unsupportedFlags);
1545     }
1546
1547     /* process the IDList */
1548     if (sei_tmp.fMask & SEE_MASK_IDLIST)
1549     {
1550         IShellExecuteHookW* pSEH;
1551
1552         HRESULT hr = SHBindToParent(sei_tmp.lpIDList, &IID_IShellExecuteHookW, (LPVOID*)&pSEH, NULL);
1553
1554         if (SUCCEEDED(hr))
1555         {
1556             hr = IShellExecuteHookW_Execute(pSEH, &sei_tmp);
1557
1558             IShellExecuteHookW_Release(pSEH);
1559
1560             if (hr == S_OK) {
1561                 HeapFree(GetProcessHeap(), 0, wszApplicationName);
1562                 if (wszParameters != parametersBuffer)
1563                     HeapFree(GetProcessHeap(), 0, wszParameters);
1564                 if (wszDir != dirBuffer)
1565                     HeapFree(GetProcessHeap(), 0, wszDir);
1566                 return TRUE;
1567             }
1568         }
1569
1570         SHGetPathFromIDListW(sei_tmp.lpIDList, wszApplicationName);
1571         appKnownSingular = TRUE;
1572         TRACE("-- idlist=%p (%s)\n", sei_tmp.lpIDList, debugstr_w(wszApplicationName));
1573     }
1574
1575     if ( ERROR_SUCCESS == ShellExecute_FromContextMenu( &sei_tmp ) )
1576     {
1577         sei->hInstApp = (HINSTANCE) 33;
1578         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1579         if (wszParameters != parametersBuffer)
1580             HeapFree(GetProcessHeap(), 0, wszParameters);
1581         if (wszDir != dirBuffer)
1582             HeapFree(GetProcessHeap(), 0, wszDir);
1583         return TRUE;
1584     }
1585
1586     if (sei_tmp.fMask & SEE_MASK_CLASSALL)
1587     {
1588         retval = SHELL_execute_class( wszApplicationName, &sei_tmp, sei,
1589                                       execfunc );
1590         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1591         if (wszParameters != parametersBuffer)
1592             HeapFree(GetProcessHeap(), 0, wszParameters);
1593         if (wszDir != dirBuffer)
1594             HeapFree(GetProcessHeap(), 0, wszDir);
1595         return retval > 32;
1596     }
1597
1598     /* Has the IDList not yet been translated? */
1599     if (sei_tmp.fMask & SEE_MASK_IDLIST)
1600     {
1601         appKnownSingular = SHELL_translate_idlist( &sei_tmp, wszParameters,
1602                                                    parametersLen,
1603                                                    wszApplicationName,
1604                                                    dwApplicationNameLen );
1605     }
1606
1607     /* expand environment strings */
1608     len = ExpandEnvironmentStringsW(sei_tmp.lpFile, NULL, 0);
1609     if (len>0)
1610     {
1611         LPWSTR buf;
1612         buf = HeapAlloc(GetProcessHeap(),0,(len+1)*sizeof(WCHAR));
1613
1614         ExpandEnvironmentStringsW(sei_tmp.lpFile, buf, len+1);
1615         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1616         dwApplicationNameLen = len+1;
1617         wszApplicationName = buf;
1618         /* appKnownSingular unmodified */
1619
1620         sei_tmp.lpFile = wszApplicationName;
1621     }
1622
1623     if (*sei_tmp.lpParameters)
1624     {
1625         len = ExpandEnvironmentStringsW(sei_tmp.lpParameters, NULL, 0);
1626         if (len > 0)
1627         {
1628             LPWSTR buf;
1629             len++;
1630             buf = HeapAlloc(GetProcessHeap(),0,len*sizeof(WCHAR));
1631             ExpandEnvironmentStringsW(sei_tmp.lpParameters, buf, len);
1632             if (wszParameters != parametersBuffer)
1633                 HeapFree(GetProcessHeap(), 0, wszParameters);
1634             wszParameters = buf;
1635             parametersLen = len;
1636             sei_tmp.lpParameters = wszParameters;
1637         }
1638     }
1639
1640     if (*sei_tmp.lpDirectory)
1641     {
1642         len = ExpandEnvironmentStringsW(sei_tmp.lpDirectory, NULL, 0);
1643         if (len > 0)
1644         {
1645             LPWSTR buf;
1646             len++;
1647             buf = HeapAlloc(GetProcessHeap(),0,len*sizeof(WCHAR));
1648             ExpandEnvironmentStringsW(sei_tmp.lpDirectory, buf, len);
1649             if (wszDir != dirBuffer)
1650                 HeapFree(GetProcessHeap(), 0, wszDir);
1651             wszDir = buf;
1652             sei_tmp.lpDirectory = wszDir;
1653         }
1654     }
1655
1656     /* Else, try to execute the filename */
1657     TRACE("execute:%s,%s,%s\n", debugstr_w(wszApplicationName), debugstr_w(wszParameters), debugstr_w(wszDir));
1658
1659     /* separate out command line arguments from executable file name */
1660     if (!*sei_tmp.lpParameters && !appKnownSingular) {
1661         /* If the executable path is quoted, handle the rest of the command line as parameters. */
1662         if (sei_tmp.lpFile[0] == '"') {
1663             LPWSTR src = wszApplicationName/*sei_tmp.lpFile*/ + 1;
1664             LPWSTR dst = wfileName;
1665             LPWSTR end;
1666
1667             /* copy the unquoted executable path to 'wfileName' */
1668             while(*src && *src!='"')
1669                 *dst++ = *src++;
1670
1671             *dst = '\0';
1672
1673             if (*src == '"') {
1674                 end = ++src;
1675
1676                 while(isspace(*src))
1677                     ++src;
1678             } else
1679                 end = src;
1680
1681             /* copy the parameter string to 'wszParameters' */
1682             strcpyW(wszParameters, src);
1683
1684             /* terminate previous command string after the quote character */
1685             *end = '\0';
1686         }
1687         else
1688         {
1689             /* If the executable name is not quoted, we have to use this search loop here,
1690                that in CreateProcess() is not sufficient because it does not handle shell links. */
1691             WCHAR buffer[MAX_PATH], xlpFile[MAX_PATH];
1692             LPWSTR space, s;
1693
1694             LPWSTR beg = wszApplicationName/*sei_tmp.lpFile*/;
1695             for(s=beg; (space=strchrW(s, ' ')); s=space+1) {
1696                 int idx = space-sei_tmp.lpFile;
1697                 memcpy(buffer, sei_tmp.lpFile, idx * sizeof(WCHAR));
1698                 buffer[idx] = '\0';
1699
1700                 /*FIXME This finds directory paths if the targeted file name contains spaces. */
1701                 if (SearchPathW(*sei_tmp.lpDirectory? sei_tmp.lpDirectory: NULL, buffer, wszExe, sizeof(xlpFile), xlpFile, NULL))
1702                 {
1703                     /* separate out command from parameter string */
1704                     LPCWSTR p = space + 1;
1705
1706                     while(isspaceW(*p))
1707                         ++p;
1708
1709                     strcpyW(wszParameters, p);
1710                     *space = '\0';
1711
1712                     break;
1713                 }
1714             }
1715
1716             strcpyW(wfileName, sei_tmp.lpFile);
1717         }
1718     } else
1719         strcpyW(wfileName, sei_tmp.lpFile);
1720
1721     lpFile = wfileName;
1722
1723     wcmd = wcmdBuffer;
1724     len = lstrlenW(wszApplicationName) + 1;
1725     if (sei_tmp.lpParameters[0])
1726         len += 1 + lstrlenW(wszParameters);
1727     if (len > wcmdLen)
1728     {
1729         wcmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1730         wcmdLen = len;
1731     }
1732     strcpyW(wcmd, wszApplicationName);
1733     if (sei_tmp.lpParameters[0]) {
1734         strcatW(wcmd, wSpace);
1735         strcatW(wcmd, wszParameters);
1736     }
1737
1738     retval = execfunc(wcmd, NULL, FALSE, &sei_tmp, sei);
1739     if (retval > 32) {
1740         HeapFree(GetProcessHeap(), 0, wszApplicationName);
1741         if (wszParameters != parametersBuffer)
1742             HeapFree(GetProcessHeap(), 0, wszParameters);
1743         if (wszDir != dirBuffer)
1744             HeapFree(GetProcessHeap(), 0, wszDir);
1745         if (wcmd != wcmdBuffer)
1746             HeapFree(GetProcessHeap(), 0, wcmd);
1747         return TRUE;
1748     }
1749
1750     /* Else, try to find the executable */
1751     wcmd[0] = '\0';
1752     retval = SHELL_FindExecutable(sei_tmp.lpDirectory, lpFile, sei_tmp.lpVerb, wcmd, wcmdLen, lpstrProtocol, &env, sei_tmp.lpIDList, sei_tmp.lpParameters);
1753     if (retval > 32)  /* Found */
1754     {
1755         retval = SHELL_quote_and_execute( wcmd, wszParameters, lpstrProtocol,
1756                                           wszApplicationName, env, &sei_tmp,
1757                                           sei, execfunc );
1758         HeapFree( GetProcessHeap(), 0, env );
1759     }
1760     else if (PathIsURLW(lpFile))    /* File not found, check for URL */
1761     {
1762         retval = SHELL_execute_url( lpFile, wFile, wcmd, &sei_tmp, sei, execfunc );
1763     }
1764     /* Check if file specified is in the form www.??????.*** */
1765     else if (!strncmpiW(lpFile, wWww, 3))
1766     {
1767         /* if so, append lpFile http:// and call ShellExecute */
1768         WCHAR lpstrTmpFile[256];
1769         strcpyW(lpstrTmpFile, wHttp);
1770         strcatW(lpstrTmpFile, lpFile);
1771         retval = (UINT_PTR)ShellExecuteW(sei_tmp.hwnd, sei_tmp.lpVerb, lpstrTmpFile, NULL, NULL, 0);
1772     }
1773
1774     TRACE("retval %lu\n", retval);
1775
1776     HeapFree(GetProcessHeap(), 0, wszApplicationName);
1777     if (wszParameters != parametersBuffer)
1778         HeapFree(GetProcessHeap(), 0, wszParameters);
1779     if (wszDir != dirBuffer)
1780         HeapFree(GetProcessHeap(), 0, wszDir);
1781     if (wcmd != wcmdBuffer)
1782         HeapFree(GetProcessHeap(), 0, wcmd);
1783
1784     sei->hInstApp = (HINSTANCE)(retval > 32 ? 33 : retval);
1785     return retval > 32;
1786 }
1787
1788 /*************************************************************************
1789  * ShellExecuteA                        [SHELL32.290]
1790  */
1791 HINSTANCE WINAPI ShellExecuteA(HWND hWnd, LPCSTR lpOperation,LPCSTR lpFile,
1792                                LPCSTR lpParameters,LPCSTR lpDirectory, INT iShowCmd)
1793 {
1794     SHELLEXECUTEINFOA sei;
1795
1796     TRACE("%p,%s,%s,%s,%s,%d\n",
1797           hWnd, debugstr_a(lpOperation), debugstr_a(lpFile),
1798           debugstr_a(lpParameters), debugstr_a(lpDirectory), iShowCmd);
1799
1800     sei.cbSize = sizeof(sei);
1801     sei.fMask = 0;
1802     sei.hwnd = hWnd;
1803     sei.lpVerb = lpOperation;
1804     sei.lpFile = lpFile;
1805     sei.lpParameters = lpParameters;
1806     sei.lpDirectory = lpDirectory;
1807     sei.nShow = iShowCmd;
1808     sei.lpIDList = 0;
1809     sei.lpClass = 0;
1810     sei.hkeyClass = 0;
1811     sei.dwHotKey = 0;
1812     sei.hProcess = 0;
1813
1814     ShellExecuteExA (&sei);
1815     return sei.hInstApp;
1816 }
1817
1818 /*************************************************************************
1819  * ShellExecuteExA                              [SHELL32.292]
1820  *
1821  */
1822 BOOL WINAPI ShellExecuteExA (LPSHELLEXECUTEINFOA sei)
1823 {
1824     SHELLEXECUTEINFOW seiW;
1825     BOOL ret;
1826     WCHAR *wVerb = NULL, *wFile = NULL, *wParameters = NULL, *wDirectory = NULL, *wClass = NULL;
1827
1828     TRACE("%p\n", sei);
1829
1830     memcpy(&seiW, sei, sizeof(SHELLEXECUTEINFOW));
1831
1832     if (sei->lpVerb)
1833         seiW.lpVerb = __SHCloneStrAtoW(&wVerb, sei->lpVerb);
1834
1835     if (sei->lpFile)
1836         seiW.lpFile = __SHCloneStrAtoW(&wFile, sei->lpFile);
1837
1838     if (sei->lpParameters)
1839         seiW.lpParameters = __SHCloneStrAtoW(&wParameters, sei->lpParameters);
1840
1841     if (sei->lpDirectory)
1842         seiW.lpDirectory = __SHCloneStrAtoW(&wDirectory, sei->lpDirectory);
1843
1844     if ((sei->fMask & SEE_MASK_CLASSALL) == SEE_MASK_CLASSNAME && sei->lpClass)
1845         seiW.lpClass = __SHCloneStrAtoW(&wClass, sei->lpClass);
1846     else
1847         seiW.lpClass = NULL;
1848
1849     ret = SHELL_execute( &seiW, SHELL_ExecuteW );
1850
1851     sei->hInstApp = seiW.hInstApp;
1852
1853     if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
1854         sei->hProcess = seiW.hProcess;
1855
1856     SHFree(wVerb);
1857     SHFree(wFile);
1858     SHFree(wParameters);
1859     SHFree(wDirectory);
1860     SHFree(wClass);
1861
1862     return ret;
1863 }
1864
1865 /*************************************************************************
1866  * ShellExecuteExW                              [SHELL32.293]
1867  *
1868  */
1869 BOOL WINAPI ShellExecuteExW (LPSHELLEXECUTEINFOW sei)
1870 {
1871     return SHELL_execute( sei, SHELL_ExecuteW );
1872 }
1873
1874 /*************************************************************************
1875  * ShellExecuteW                        [SHELL32.294]
1876  * from shellapi.h
1877  * WINSHELLAPI HINSTANCE APIENTRY ShellExecuteW(HWND hwnd, LPCWSTR lpOperation,
1878  * LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd);
1879  */
1880 HINSTANCE WINAPI ShellExecuteW(HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile,
1881                                LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd)
1882 {
1883     SHELLEXECUTEINFOW sei;
1884
1885     TRACE("\n");
1886     sei.cbSize = sizeof(sei);
1887     sei.fMask = 0;
1888     sei.hwnd = hwnd;
1889     sei.lpVerb = lpOperation;
1890     sei.lpFile = lpFile;
1891     sei.lpParameters = lpParameters;
1892     sei.lpDirectory = lpDirectory;
1893     sei.nShow = nShowCmd;
1894     sei.lpIDList = 0;
1895     sei.lpClass = 0;
1896     sei.hkeyClass = 0;
1897     sei.dwHotKey = 0;
1898     sei.hProcess = 0;
1899
1900     SHELL_execute( &sei, SHELL_ExecuteW );
1901     return sei.hInstApp;
1902 }
1903
1904 /*************************************************************************
1905  * OpenAs_RunDLLA          [SHELL32.@]
1906  */
1907 void WINAPI OpenAs_RunDLLA(HWND hwnd, HINSTANCE hinst, LPCSTR cmdline, int cmdshow)
1908 {
1909     FIXME("%p, %p, %s, %d\n", hwnd, hinst, debugstr_a(cmdline), cmdshow);
1910 }
1911
1912 /*************************************************************************
1913  * OpenAs_RunDLLW          [SHELL32.@]
1914  */
1915 void WINAPI OpenAs_RunDLLW(HWND hwnd, HINSTANCE hinst, LPCWSTR cmdline, int cmdshow)
1916 {
1917     FIXME("%p, %p, %s, %d\n", hwnd, hinst, debugstr_w(cmdline), cmdshow);
1918 }