Release 1.4.1.
[wine] / programs / start / start.c
1 /*
2  * Start a program using ShellExecuteEx, optionally wait for it to finish
3  * Compatible with Microsoft's "c:\windows\command\start.exe"
4  *
5  * Copyright 2003 Dan Kegel
6  * Copyright 2007 Lyutin Anatoly (Etersoft)
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <windows.h>
26 #include <shlobj.h>
27 #include <shellapi.h>
28
29 #include <wine/unicode.h>
30 #include <wine/debug.h>
31
32 #include "resources.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(start);
35
36 /**
37  Output given message to stdout without formatting.
38 */
39 static void output(const WCHAR *message)
40 {
41         DWORD count;
42         DWORD   res;
43         int    wlen = strlenW(message);
44
45         if (!wlen) return;
46
47         res = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), message, wlen, &count, NULL);
48
49         /* If writing to console fails, assume it's file
50          * i/o so convert to OEM codepage and output
51          */
52         if (!res)
53         {
54                 DWORD len;
55                 char  *mesA;
56                 /* Convert to OEM, then output */
57                 len = WideCharToMultiByte( GetConsoleOutputCP(), 0, message, wlen, NULL, 0, NULL, NULL );
58                 mesA = HeapAlloc(GetProcessHeap(), 0, len*sizeof(char));
59                 if (!mesA) return;
60                 WideCharToMultiByte( GetConsoleOutputCP(), 0, message, wlen, mesA, len, NULL, NULL );
61                 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), mesA, len, &count, FALSE);
62                 HeapFree(GetProcessHeap(), 0, mesA);
63         }
64 }
65
66 /**
67  Output given message from string table,
68  followed by ": ",
69  followed by description of given GetLastError() value to stdout,
70  followed by a trailing newline,
71  then terminate.
72 */
73
74 static void fatal_error(const WCHAR *msg, DWORD error_code, const WCHAR *filename)
75 {
76     DWORD_PTR args[1];
77     LPVOID lpMsgBuf;
78     int status;
79     static const WCHAR colonsW[] = { ':', ' ', 0 };
80     static const WCHAR newlineW[] = { '\n', 0 };
81
82     output(msg);
83     output(colonsW);
84     args[0] = (DWORD_PTR)filename;
85     status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
86                             NULL, error_code, 0, (LPWSTR)&lpMsgBuf, 0, (__ms_va_list *)args );
87     if (!status)
88     {
89         WINE_ERR("FormatMessage failed\n");
90     } else
91     {
92         output(lpMsgBuf);
93         LocalFree((HLOCAL) lpMsgBuf);
94         output(newlineW);
95     }
96     ExitProcess(1);
97 }
98
99 static void fatal_string_error(int which, DWORD error_code, const WCHAR *filename)
100 {
101         WCHAR msg[2048];
102
103         if (!LoadStringW(GetModuleHandleW(NULL), which,
104                                         msg, sizeof(msg)/sizeof(WCHAR)))
105                 WINE_ERR("LoadString failed, error %d\n", GetLastError());
106
107         fatal_error(msg, error_code, filename);
108 }
109         
110 static void fatal_string(int which)
111 {
112         WCHAR msg[2048];
113
114         if (!LoadStringW(GetModuleHandleW(NULL), which,
115                                         msg, sizeof(msg)/sizeof(WCHAR)))
116                 WINE_ERR("LoadString failed, error %d\n", GetLastError());
117
118         output(msg);
119         ExitProcess(1);
120 }
121
122 static void usage(void)
123 {
124         fatal_string(STRING_USAGE);
125 }
126
127 static WCHAR *build_args( int argc, WCHAR **argvW )
128 {
129         int i, wlen = 1;
130         WCHAR *ret, *p;
131         static const WCHAR FormatQuotesW[] = { ' ', '\"', '%', 's', '\"', 0 };
132         static const WCHAR FormatW[] = { ' ', '%', 's', 0 };
133
134         for (i = 0; i < argc; i++ )
135         {
136                 wlen += strlenW(argvW[i]) + 1;
137                 if (strchrW(argvW[i], ' '))
138                         wlen += 2;
139         }
140         ret = HeapAlloc( GetProcessHeap(), 0, wlen*sizeof(WCHAR) );
141         ret[0] = 0;
142
143         for (i = 0, p = ret; i < argc; i++ )
144         {
145                 if (strchrW(argvW[i], ' '))
146                         p += sprintfW(p, FormatQuotesW, argvW[i]);
147                 else
148                         p += sprintfW(p, FormatW, argvW[i]);
149         }
150         return ret;
151 }
152
153 static WCHAR *get_parent_dir(WCHAR* path)
154 {
155         WCHAR *last_slash;
156         WCHAR *result;
157         int len;
158
159         last_slash = strrchrW( path, '\\' );
160         if (last_slash == NULL)
161                 len = 1;
162         else
163                 len = last_slash - path + 1;
164
165         result = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
166         CopyMemory(result, path, (len-1)*sizeof(WCHAR));
167         result[len-1] = '\0';
168
169         return result;
170 }
171
172 int wmain (int argc, WCHAR *argv[])
173 {
174         SHELLEXECUTEINFOW sei;
175         WCHAR *args = NULL;
176         int i;
177         int unix_mode = 0;
178         int progid_open = 0;
179         WCHAR *dos_filename = NULL;
180         WCHAR *parent_directory = NULL;
181         DWORD binary_type;
182
183         static const WCHAR openW[] = { 'o', 'p', 'e', 'n', 0 };
184         static const WCHAR unixW[] = { 'u', 'n', 'i', 'x', 0 };
185         static const WCHAR progIDOpenW[] =
186                 { 'p', 'r', 'o', 'g', 'I', 'D', 'O', 'p', 'e', 'n', 0};
187
188         memset(&sei, 0, sizeof(sei));
189         sei.cbSize = sizeof(sei);
190         sei.lpVerb = openW;
191         sei.nShow = SW_SHOWNORMAL;
192         /* Dunno what these mean, but it looks like winMe's start uses them */
193         sei.fMask = SEE_MASK_FLAG_DDEWAIT|
194                     SEE_MASK_FLAG_NO_UI|
195                     SEE_MASK_NO_CONSOLE;
196
197         /* Canonical Microsoft commandline flag processing:
198          * flags start with /, are case insensitive,
199          * and may be run together in same word.
200          */
201         for (i=1; i<argc; i++) {
202                 int ci;
203
204                 if (argv[i][0] != '/')
205                         break;
206
207                 /* Unix paths can start with / so we have to assume anything following /U is not a flag */
208                 if (unix_mode || progid_open)
209                         break;
210
211                 /* Handle all options in this word */
212                 for (ci=0; argv[i][ci]; ) {
213                         /* Skip slash */
214                         ci++;
215                         switch(argv[i][ci]) {
216                         case 'b':
217                         case 'B':
218                                 break; /* FIXME: should stop new window from being created */
219                         case 'i':
220                         case 'I':
221                                 break; /* FIXME: should ignore any changes to current environment */
222                         case 'm':
223                         case 'M':
224                                 if (argv[i][ci+1] == 'a' || argv[i][ci+1] == 'A')
225                                         sei.nShow = SW_SHOWMAXIMIZED;
226                                 else
227                                         sei.nShow = SW_SHOWMINIMIZED;
228                                 break;
229                         case 'r':
230                         case 'R':
231                                 /* sei.nShow = SW_SHOWNORMAL; */
232                                 break;
233                         case 'u':
234                         case 'U':
235                                 if (strncmpiW(&argv[i][ci], unixW, 4) == 0)
236                                         unix_mode = 1;
237                                 else {
238                                         WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
239                                         usage();
240                                 }
241                                 break;
242                         case 'p':
243                         case 'P':
244                                 if (strncmpiW(&argv[i][ci], progIDOpenW, 17) == 0)
245                                         progid_open = 1;
246                                 else {
247                                         WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
248                                         usage();
249                                 }
250                                 break;
251                         case 'w':
252                         case 'W':
253                                 sei.fMask |= SEE_MASK_NOCLOSEPROCESS;
254                                 break;
255                         case '?':
256                                 usage();
257                                 break;
258                         default:
259                                 WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
260                                 usage();
261                         }
262                         /* Skip to next slash */
263                         while (argv[i][ci] && (argv[i][ci] != '/'))
264                                 ci++;
265                 }
266         }
267
268         if (i == argc)
269                 usage();
270
271         if (progid_open) {
272                 sei.lpClass = argv[i++];
273                 sei.fMask |= SEE_MASK_CLASSNAME;
274         }
275
276         sei.lpFile = argv[i++];
277
278         args = build_args( argc - i, &argv[i] );
279         sei.lpParameters = args;
280
281         if (unix_mode || progid_open) {
282                 LPWSTR (*CDECL wine_get_dos_file_name_ptr)(LPCSTR);
283                 char* multibyte_unixpath;
284                 int multibyte_unixpath_len;
285
286                 wine_get_dos_file_name_ptr = (void*)GetProcAddress(GetModuleHandleA("KERNEL32"), "wine_get_dos_file_name");
287
288                 if (!wine_get_dos_file_name_ptr)
289                         fatal_string(STRING_UNIXFAIL);
290
291                 multibyte_unixpath_len = WideCharToMultiByte(CP_UNIXCP, 0, sei.lpFile, -1, NULL, 0, NULL, NULL);
292                 multibyte_unixpath = HeapAlloc(GetProcessHeap(), 0, multibyte_unixpath_len);
293
294                 WideCharToMultiByte(CP_UNIXCP, 0, sei.lpFile, -1, multibyte_unixpath, multibyte_unixpath_len, NULL, NULL);
295
296                 dos_filename = wine_get_dos_file_name_ptr(multibyte_unixpath);
297
298                 HeapFree(GetProcessHeap(), 0, multibyte_unixpath);
299
300                 if (!dos_filename)
301                         fatal_string(STRING_UNIXFAIL);
302
303                 sei.lpFile = dos_filename;
304                 sei.lpDirectory = parent_directory = get_parent_dir(dos_filename);
305                 sei.fMask &= ~SEE_MASK_FLAG_NO_UI;
306
307                 if (GetBinaryTypeW(sei.lpFile, &binary_type)) {
308                     WCHAR *commandline;
309                     STARTUPINFOW startup_info;
310                     PROCESS_INFORMATION process_information;
311                     static WCHAR commandlineformat[] = {'"','%','s','"','%','s',0};
312
313                     /* explorer on windows always quotes the filename when running a binary on windows (see bug 5224) so we have to use CreateProcessW in this case */
314
315                     commandline = HeapAlloc(GetProcessHeap(), 0, (strlenW(sei.lpFile)+3+strlenW(sei.lpParameters))*sizeof(WCHAR));
316                     sprintfW(commandline, commandlineformat, sei.lpFile, sei.lpParameters);
317
318                     ZeroMemory(&startup_info, sizeof(startup_info));
319                     startup_info.cb = sizeof(startup_info);
320
321                     if (!CreateProcessW(
322                             NULL, /* lpApplicationName */
323                             commandline, /* lpCommandLine */
324                             NULL, /* lpProcessAttributes */
325                             NULL, /* lpThreadAttributes */
326                             FALSE, /* bInheritHandles */
327                             CREATE_NEW_CONSOLE, /* dwCreationFlags */
328                             NULL, /* lpEnvironment */
329                             sei.lpDirectory, /* lpCurrentDirectory */
330                             &startup_info, /* lpStartupInfo */
331                             &process_information /* lpProcessInformation */ ))
332                     {
333                         fatal_string_error(STRING_EXECFAIL, GetLastError(), sei.lpFile);
334                     }
335                     sei.hProcess = process_information.hProcess;
336                     goto done;
337                 }
338         }
339
340         if (!ShellExecuteExW(&sei))
341             fatal_string_error(STRING_EXECFAIL, GetLastError(), sei.lpFile);
342
343 done:
344         HeapFree( GetProcessHeap(), 0, args );
345         HeapFree( GetProcessHeap(), 0, dos_filename );
346         HeapFree( GetProcessHeap(), 0, parent_directory );
347
348         if (sei.fMask & SEE_MASK_NOCLOSEPROCESS) {
349                 DWORD exitcode;
350                 WaitForSingleObject(sei.hProcess, INFINITE);
351                 GetExitCodeProcess(sei.hProcess, &exitcode);
352                 ExitProcess(exitcode);
353         }
354
355         ExitProcess(0);
356 }