start: One language specifier in the English resource is enough.
[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 <windows.h>
24 #include <winuser.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <shlobj.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 its file
50         i/o so convert to OEM codepage and output                  */
51         if (!res)
52         {
53                 DWORD len;
54                 char  *mesA;
55                 /* Convert to OEM, then output */
56                 len = WideCharToMultiByte( GetConsoleOutputCP(), 0, message, wlen, NULL, 0, NULL, NULL );
57                 mesA = HeapAlloc(GetProcessHeap(), 0, len*sizeof(char));
58                 if (!mesA) return;
59                 WideCharToMultiByte( GetConsoleOutputCP(), 0, message, wlen, mesA, len, NULL, NULL );
60                 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), mesA, len, &count, FALSE);
61                 HeapFree(GetProcessHeap(), 0, mesA);
62         }
63 }
64
65 /**
66  Output given message from string table,
67  followed by ": ",
68  followed by description of given GetLastError() value to stdout,
69  followed by a trailing newline,
70  then terminate.
71 */
72
73 static void fatal_error(const WCHAR *msg, DWORD error_code, const WCHAR *filename)
74 {
75     DWORD_PTR args[1];
76     LPVOID lpMsgBuf;
77     int status;
78     static const WCHAR colonsW[] = { ':', ' ', 0 };
79     static const WCHAR newlineW[] = { '\n', 0 };
80
81     output(msg);
82     output(colonsW);
83     args[0] = (DWORD_PTR)filename;
84     status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
85                             NULL, error_code, 0, (LPWSTR)&lpMsgBuf, 0, (__ms_va_list *)args );
86     if (!status)
87     {
88         WINE_ERR("FormatMessage failed\n");
89     } else
90     {
91         output(lpMsgBuf);
92         LocalFree((HLOCAL) lpMsgBuf);
93         output(newlineW);
94     }
95     ExitProcess(1);
96 }
97
98 static void fatal_string_error(int which, DWORD error_code, const WCHAR *filename)
99 {
100         WCHAR msg[2048];
101
102         if (!LoadStringW(GetModuleHandleW(NULL), which,
103                                         msg, sizeof(msg)/sizeof(WCHAR)))
104                 WINE_ERR("LoadString failed, error %d\n", GetLastError());
105
106         fatal_error(msg, error_code, filename);
107 }
108         
109 static void fatal_string(int which)
110 {
111         WCHAR msg[2048];
112
113         if (!LoadStringW(GetModuleHandleW(NULL), which,
114                                         msg, sizeof(msg)/sizeof(WCHAR)))
115                 WINE_ERR("LoadString failed, error %d\n", GetLastError());
116
117         output(msg);
118         ExitProcess(1);
119 }
120
121 static void usage(void)
122 {
123         fatal_string(STRING_USAGE);
124 }
125
126 static void license(void)
127 {
128         fatal_string(STRING_LICENSE);
129 }
130
131 static WCHAR *build_args( int argc, WCHAR **argvW )
132 {
133         int i, wlen = 1;
134         WCHAR *ret, *p;
135         static const WCHAR FormatQuotesW[] = { ' ', '\"', '%', 's', '\"', 0 };
136         static const WCHAR FormatW[] = { ' ', '%', 's', 0 };
137
138         for (i = 0; i < argc; i++ )
139         {
140                 wlen += strlenW(argvW[i]) + 1;
141                 if (strchrW(argvW[i], ' '))
142                         wlen += 2;
143         }
144         ret = HeapAlloc( GetProcessHeap(), 0, wlen*sizeof(WCHAR) );
145         ret[0] = 0;
146
147         for (i = 0, p = ret; i < argc; i++ )
148         {
149                 if (strchrW(argvW[i], ' '))
150                         p += sprintfW(p, FormatQuotesW, argvW[i]);
151                 else
152                         p += sprintfW(p, FormatW, argvW[i]);
153         }
154         return ret;
155 }
156
157 static WCHAR *get_parent_dir(WCHAR* path)
158 {
159         WCHAR *last_slash;
160         WCHAR *result;
161         int len;
162
163         last_slash = strrchrW( path, '\\' );
164         if (last_slash == NULL)
165                 len = 1;
166         else
167                 len = last_slash - path + 1;
168
169         result = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
170         CopyMemory(result, path, (len-1)*sizeof(WCHAR));
171         result[len-1] = '\0';
172
173         return result;
174 }
175
176 int wmain (int argc, WCHAR *argv[])
177 {
178         SHELLEXECUTEINFOW sei;
179         WCHAR *args = NULL;
180         int i;
181         int unix_mode = 0;
182         int progid_open = 0;
183         WCHAR *dos_filename = NULL;
184         WCHAR *parent_directory = NULL;
185         DWORD binary_type;
186
187         static const WCHAR openW[] = { 'o', 'p', 'e', 'n', 0 };
188         static const WCHAR unixW[] = { 'u', 'n', 'i', 'x', 0 };
189         static const WCHAR progIDOpenW[] =
190                 { 'p', 'r', 'o', 'g', 'I', 'D', 'O', 'p', 'e', 'n', 0};
191
192         memset(&sei, 0, sizeof(sei));
193         sei.cbSize = sizeof(sei);
194         sei.lpVerb = openW;
195         sei.nShow = SW_SHOWNORMAL;
196         /* Dunno what these mean, but it looks like winMe's start uses them */
197         sei.fMask = SEE_MASK_FLAG_DDEWAIT|
198                     SEE_MASK_FLAG_NO_UI|
199                     SEE_MASK_NO_CONSOLE;
200
201         /* Canonical Microsoft commandline flag processing:
202          * flags start with /, are case insensitive,
203          * and may be run together in same word.
204          */
205         for (i=1; i<argc; i++) {
206                 int ci;
207
208                 if (argv[i][0] != '/')
209                         break;
210
211                 /* Unix paths can start with / so we have to assume anything following /U is not a flag */
212                 if (unix_mode || progid_open)
213                         break;
214
215                 /* Handle all options in this word */
216                 for (ci=0; argv[i][ci]; ) {
217                         /* Skip slash */
218                         ci++;
219                         switch(argv[i][ci]) {
220                         case 'b':
221                         case 'B':
222                                 break; /* FIXME: should stop new window from being created */
223                         case 'i':
224                         case 'I':
225                                 break; /* FIXME: should ignore any changes to current environment */
226                         case 'l':
227                         case 'L':
228                                 license();
229                                 break;  /* notreached */
230                         case 'm':
231                         case 'M':
232                                 if (argv[i][ci+1] == 'a' || argv[i][ci+1] == 'A')
233                                         sei.nShow = SW_SHOWMAXIMIZED;
234                                 else
235                                         sei.nShow = SW_SHOWMINIMIZED;
236                                 break;
237                         case 'r':
238                         case 'R':
239                                 /* sei.nShow = SW_SHOWNORMAL; */
240                                 break;
241                         case 'u':
242                         case 'U':
243                                 if (strncmpiW(&argv[i][ci], unixW, 4) == 0)
244                                         unix_mode = 1;
245                                 else {
246                                         WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
247                                         usage();
248                                 }
249                                 break;
250                         case 'p':
251                         case 'P':
252                                 if (strncmpiW(&argv[i][ci], progIDOpenW, 17) == 0)
253                                         progid_open = 1;
254                                 else {
255                                         WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
256                                         usage();
257                                 }
258                                 break;
259                         case 'w':
260                         case 'W':
261                                 sei.fMask |= SEE_MASK_NOCLOSEPROCESS;
262                                 break;
263                         default:
264                                 WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
265                                 usage();
266                         }
267                         /* Skip to next slash */
268                         while (argv[i][ci] && (argv[i][ci] != '/'))
269                                 ci++;
270                 }
271         }
272
273         if (i == argc)
274                 usage();
275
276         if (progid_open) {
277                 sei.lpClass = argv[i++];
278                 sei.fMask |= SEE_MASK_CLASSNAME;
279         }
280
281         sei.lpFile = argv[i++];
282
283         args = build_args( argc - i, &argv[i] );
284         sei.lpParameters = args;
285
286         if (unix_mode || progid_open) {
287                 LPWSTR (*CDECL wine_get_dos_file_name_ptr)(LPCSTR);
288                 char* multibyte_unixpath;
289                 int multibyte_unixpath_len;
290
291                 wine_get_dos_file_name_ptr = (void*)GetProcAddress(GetModuleHandleA("KERNEL32"), "wine_get_dos_file_name");
292
293                 if (!wine_get_dos_file_name_ptr)
294                         fatal_string(STRING_UNIXFAIL);
295
296                 multibyte_unixpath_len = WideCharToMultiByte(CP_UNIXCP, 0, sei.lpFile, -1, NULL, 0, NULL, NULL);
297                 multibyte_unixpath = HeapAlloc(GetProcessHeap(), 0, multibyte_unixpath_len);
298
299                 WideCharToMultiByte(CP_UNIXCP, 0, sei.lpFile, -1, multibyte_unixpath, multibyte_unixpath_len, NULL, NULL);
300
301                 dos_filename = wine_get_dos_file_name_ptr(multibyte_unixpath);
302
303                 HeapFree(GetProcessHeap(), 0, multibyte_unixpath);
304
305                 if (!dos_filename)
306                         fatal_string(STRING_UNIXFAIL);
307
308                 sei.lpFile = dos_filename;
309                 sei.lpDirectory = parent_directory = get_parent_dir(dos_filename);
310                 sei.fMask &= ~SEE_MASK_FLAG_NO_UI;
311
312                 if (GetBinaryTypeW(sei.lpFile, &binary_type)) {
313                     WCHAR *commandline;
314                     STARTUPINFOW startup_info;
315                     PROCESS_INFORMATION process_information;
316                     static WCHAR commandlineformat[] = {'"','%','s','"','%','s',0};
317
318                     /* 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 */
319
320                     commandline = HeapAlloc(GetProcessHeap(), 0, (strlenW(sei.lpFile)+3+strlenW(sei.lpParameters))*sizeof(WCHAR));
321                     sprintfW(commandline, commandlineformat, sei.lpFile, sei.lpParameters);
322
323                     ZeroMemory(&startup_info, sizeof(startup_info));
324                     startup_info.cb = sizeof(startup_info);
325
326                     if (!CreateProcessW(
327                             NULL, /* lpApplicationName */
328                             commandline, /* lpCommandLine */
329                             NULL, /* lpProcessAttributes */
330                             NULL, /* lpThreadAttributes */
331                             FALSE, /* bInheritHandles */
332                             CREATE_NEW_CONSOLE, /* dwCreationFlags */
333                             NULL, /* lpEnvironment */
334                             sei.lpDirectory, /* lpCurrentDirectory */
335                             &startup_info, /* lpStartupInfo */
336                             &process_information /* lpProcessInformation */ ))
337                     {
338                         fatal_string_error(STRING_EXECFAIL, GetLastError(), sei.lpFile);
339                     }
340                     sei.hProcess = process_information.hProcess;
341                     goto done;
342                 }
343         }
344
345         if (!ShellExecuteExW(&sei))
346             fatal_string_error(STRING_EXECFAIL, GetLastError(), sei.lpFile);
347
348 done:
349         HeapFree( GetProcessHeap(), 0, args );
350         HeapFree( GetProcessHeap(), 0, dos_filename );
351         HeapFree( GetProcessHeap(), 0, parent_directory );
352
353         if (sei.fMask & SEE_MASK_NOCLOSEPROCESS) {
354                 DWORD exitcode;
355                 WaitForSingleObject(sei.hProcess, INFINITE);
356                 GetExitCodeProcess(sei.hProcess, &exitcode);
357                 ExitProcess(exitcode);
358         }
359
360         ExitProcess(0);
361 }