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