2 * Start a program using ShellExecuteEx, optionally wait for it to finish
3 * Compatible with Microsoft's "c:\windows\command\start.exe"
5 * Copyright 2003 Dan Kegel
6 * Copyright 2007 Lyutin Anatoly (Etersoft)
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.
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.
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
29 #include <wine/debug.h>
31 #include "resources.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(start
);
36 Output given message to stdout without formatting.
38 static void output(const WCHAR
*message
)
42 int wlen
= lstrlenW(message
);
46 res
= WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE
), message
, wlen
, &count
, NULL
);
48 /* If writing to console fails, assume it's file
49 * i/o so convert to OEM codepage and output
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));
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
);
66 Output given message from string table,
68 followed by description of given GetLastError() value to stdout,
69 followed by a trailing newline,
73 static void fatal_error(const WCHAR
*msg
, DWORD error_code
, const WCHAR
*filename
)
78 static const WCHAR colonsW
[] = { ':', ' ', 0 };
79 static const WCHAR newlineW
[] = { '\n', 0 };
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
);
88 WINE_ERR("FormatMessage failed\n");
92 LocalFree((HLOCAL
) lpMsgBuf
);
98 static void fatal_string_error(int which
, DWORD error_code
, const WCHAR
*filename
)
102 if (!LoadStringW(GetModuleHandleW(NULL
), which
, msg
, ARRAY_SIZE(msg
)))
103 WINE_ERR("LoadString failed, error %d\n", GetLastError());
105 fatal_error(msg
, error_code
, filename
);
108 static void fatal_string(int which
)
112 if (!LoadStringW(GetModuleHandleW(NULL
), which
, msg
, ARRAY_SIZE(msg
)))
113 WINE_ERR("LoadString failed, error %d\n", GetLastError());
119 static void usage(void)
121 fatal_string(STRING_USAGE
);
124 static WCHAR
*build_args( int argc
, WCHAR
**argvW
)
128 static const WCHAR FormatQuotesW
[] = { ' ', '\"', '%', 's', '\"', 0 };
129 static const WCHAR FormatW
[] = { ' ', '%', 's', 0 };
131 for (i
= 0; i
< argc
; i
++ )
133 wlen
+= lstrlenW(argvW
[i
]) + 1;
134 if (wcschr(argvW
[i
], ' '))
137 ret
= HeapAlloc( GetProcessHeap(), 0, wlen
*sizeof(WCHAR
) );
140 for (i
= 0, p
= ret
; i
< argc
; i
++ )
142 if (wcschr(argvW
[i
], ' '))
143 p
+= swprintf(p
, wlen
- (p
- ret
), FormatQuotesW
, argvW
[i
]);
145 p
+= swprintf(p
, wlen
- (p
- ret
), FormatW
, argvW
[i
]);
150 static WCHAR
*get_parent_dir(WCHAR
* path
)
156 last_slash
= wcsrchr( path
, '\\' );
157 if (last_slash
== NULL
)
160 len
= last_slash
- path
+ 1;
162 result
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
163 CopyMemory(result
, path
, (len
-1)*sizeof(WCHAR
));
164 result
[len
-1] = '\0';
169 static BOOL
is_option(const WCHAR
* arg
, const WCHAR
* opt
)
171 return CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
,
172 arg
, -1, opt
, -1) == CSTR_EQUAL
;
175 static void parse_title(const WCHAR
*arg
, WCHAR
*title
, int size
)
178 * WCMD_start() in programs/cmd/builtins.c
179 * WCMD_parameter_with_delims() in programs/cmd/batch.c
180 * The shell has already tokenized the command line for us.
181 * All we need to do is filter out all the quotes.
185 const WCHAR
*p
= arg
;
187 for (next
= 0; next
< (size
-1) && *p
; p
++) {
194 static BOOL
search_path(const WCHAR
*firstParam
, WCHAR
**full_path
)
196 /* Copied from WCMD_run_program() in programs/cmd/wcmdmain.c */
198 #define MAXSTRING 8192
199 static const WCHAR slashW
[] = {'\\','\0',};
200 static const WCHAR envPath
[] = {'P','A','T','H','\0'};
201 static const WCHAR envPathExt
[] = {'P','A','T','H','E','X','T','\0'};
202 static const WCHAR dfltPathExt
[] = {'.','b','a','t',';',
205 '.','e','x','e','\0'};
206 static const WCHAR delims
[] = {'/','\\',':','\0'};
208 WCHAR temp
[MAX_PATH
];
209 WCHAR pathtosearch
[MAXSTRING
];
211 WCHAR stemofsearch
[MAX_PATH
]; /* maximum allowed executable name is
212 MAX_PATH, including null character */
214 WCHAR pathext
[MAXSTRING
];
215 BOOL extensionsupplied
= FALSE
;
218 /* Calculate the search path and stem to search for */
219 if (wcspbrk (firstParam
, delims
) == NULL
) { /* No explicit path given, search path */
220 static const WCHAR curDir
[] = {'.',';','\0'};
221 lstrcpyW(pathtosearch
, curDir
);
222 len
= GetEnvironmentVariableW(envPath
, &pathtosearch
[2], ARRAY_SIZE(pathtosearch
)-2);
223 if ((len
== 0) || (len
>= ARRAY_SIZE(pathtosearch
) - 2)) {
224 static const WCHAR curDir
[] = {'.','\0'};
225 lstrcpyW (pathtosearch
, curDir
);
227 if (wcschr(firstParam
, '.') != NULL
) extensionsupplied
= TRUE
;
228 if (lstrlenW(firstParam
) >= MAX_PATH
) {
232 lstrcpyW(stemofsearch
, firstParam
);
236 /* Convert eg. ..\fred to include a directory by removing file part */
237 GetFullPathNameW(firstParam
, ARRAY_SIZE(pathtosearch
), pathtosearch
, NULL
);
238 lastSlash
= wcsrchr(pathtosearch
, '\\');
239 if (lastSlash
&& wcschr(lastSlash
, '.') != NULL
) extensionsupplied
= TRUE
;
240 lstrcpyW(stemofsearch
, lastSlash
+1);
242 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
243 c:\windows\a.bat syntax */
244 if (lastSlash
) *(lastSlash
+ 1) = 0x00;
247 /* Now extract PATHEXT */
248 len
= GetEnvironmentVariableW(envPathExt
, pathext
, ARRAY_SIZE(pathext
));
249 if ((len
== 0) || (len
>= ARRAY_SIZE(pathext
))) {
250 lstrcpyW (pathext
, dfltPathExt
);
253 /* Loop through the search path, dir by dir */
254 pathposn
= pathtosearch
;
255 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch
),
256 wine_dbgstr_w(stemofsearch
));
258 WCHAR thisDir
[MAX_PATH
] = {'\0'};
262 BOOL inside_quotes
= FALSE
;
264 /* Work on the first directory on the search path */
266 while ((inside_quotes
|| *pos
!= ';') && *pos
!= 0)
269 inside_quotes
= !inside_quotes
;
273 if (*pos
) { /* Reached semicolon */
274 memcpy(thisDir
, pathposn
, (pos
-pathposn
) * sizeof(WCHAR
));
275 thisDir
[(pos
-pathposn
)] = 0x00;
277 } else { /* Reached string end */
278 lstrcpyW(thisDir
, pathposn
);
283 length
= lstrlenW(thisDir
);
284 if (thisDir
[length
- 1] == '"')
285 thisDir
[length
- 1] = 0;
288 lstrcpyW(temp
, thisDir
);
290 lstrcpyW(temp
, thisDir
+ 1);
292 /* Since you can have eg. ..\.. on the path, need to expand
293 to full information */
294 GetFullPathNameW(temp
, MAX_PATH
, thisDir
, NULL
);
296 /* 1. If extension supplied, see if that file exists */
297 lstrcatW(thisDir
, slashW
);
298 lstrcatW(thisDir
, stemofsearch
);
299 pos
= &thisDir
[lstrlenW(thisDir
)]; /* Pos = end of name */
301 /* 1. If extension supplied, see if that file exists */
302 if (extensionsupplied
) {
303 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
308 /* 2. Any .* matches? */
311 WIN32_FIND_DATAW finddata
;
312 static const WCHAR allFiles
[] = {'.','*','\0'};
314 lstrcatW(thisDir
,allFiles
);
315 h
= FindFirstFileW(thisDir
, &finddata
);
317 if (h
!= INVALID_HANDLE_VALUE
) {
319 WCHAR
*thisExt
= pathext
;
321 /* 3. Yes - Try each path ext */
323 WCHAR
*nextExt
= wcschr(thisExt
, ';');
326 memcpy(pos
, thisExt
, (nextExt
-thisExt
) * sizeof(WCHAR
));
327 pos
[(nextExt
-thisExt
)] = 0x00;
330 lstrcpyW(pos
, thisExt
);
334 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
343 int needed_size
= lstrlenW(thisDir
) + 1;
344 *full_path
= HeapAlloc(GetProcessHeap(), 0, needed_size
* sizeof(WCHAR
));
346 lstrcpyW(*full_path
, thisDir
);
353 int __cdecl
wmain (int argc
, WCHAR
*argv
[])
355 SHELLEXECUTEINFOW sei
;
356 DWORD creation_flags
;
359 BOOL unix_mode
= FALSE
;
360 BOOL progid_open
= FALSE
;
363 WCHAR
*dos_filename
= NULL
;
364 WCHAR
*fullpath
= NULL
;
365 WCHAR
*parent_directory
= NULL
;
368 static const WCHAR bW
[] = { '/', 'b', 0 };
369 static const WCHAR minW
[] = { '/', 'm', 'i', 'n', 0 };
370 static const WCHAR maxW
[] = { '/', 'm', 'a', 'x', 0 };
371 static const WCHAR lowW
[] = { '/', 'l', 'o', 'w', 0 };
372 static const WCHAR normalW
[] = { '/', 'n', 'o', 'r', 'm', 'a', 'l', 0 };
373 static const WCHAR highW
[] = { '/', 'h', 'i', 'g', 'h', 0 };
374 static const WCHAR realtimeW
[] = { '/', 'r', 'e', 'a', 'l', 't', 'i', 'm', 'e', 0 };
375 static const WCHAR abovenormalW
[] = { '/', 'a', 'b', 'o', 'v', 'e', 'n', 'o', 'r', 'm', 'a', 'l', 0 };
376 static const WCHAR belownormalW
[] = { '/', 'b', 'e', 'l', 'o', 'w', 'n', 'o', 'r', 'm', 'a', 'l', 0 };
377 static const WCHAR separateW
[] = { '/', 's', 'e', 'p', 'a', 'r', 'a', 't', 'e', 0 };
378 static const WCHAR sharedW
[] = { '/', 's', 'h', 'a', 'r', 'e', 'd', 0 };
379 static const WCHAR nodeW
[] = { '/', 'n', 'o', 'd', 'e', 0 };
380 static const WCHAR affinityW
[] = { '/', 'a', 'f', 'f', 'i', 'n', 'i', 't', 'y', 0 };
381 static const WCHAR wW
[] = { '/', 'w', 0 };
382 static const WCHAR waitW
[] = { '/', 'w', 'a', 'i', 't', 0 };
383 static const WCHAR helpW
[] = { '/', '?', 0 };
384 static const WCHAR unixW
[] = { '/', 'u', 'n', 'i', 'x', 0 };
385 static const WCHAR progIDOpenW
[] =
386 { '/', 'p', 'r', 'o', 'g', 'I', 'D', 'O', 'p', 'e', 'n', 0};
387 static const WCHAR openW
[] = { 'o', 'p', 'e', 'n', 0 };
388 static const WCHAR cmdW
[] = { 'c', 'm', 'd', '.', 'e', 'x', 'e', 0 };
390 memset(&sei
, 0, sizeof(sei
));
391 sei
.cbSize
= sizeof(sei
);
393 sei
.nShow
= SW_SHOWNORMAL
;
394 /* Dunno what these mean, but it looks like winMe's start uses them */
395 sei
.fMask
= SEE_MASK_FLAG_DDEWAIT
|
397 sei
.lpDirectory
= NULL
;
398 creation_flags
= CREATE_NEW_CONSOLE
;
400 /* Canonical Microsoft commandline flag processing:
401 * flags start with / and are case insensitive.
403 for (i
=1; i
<argc
; i
++) {
404 /* parse first quoted argument as console title */
405 if (!title
&& argv
[i
][0] == '"') {
406 /* it will remove at least 1 quote */
407 int maxChars
= lstrlenW(argv
[1]);
408 title
= HeapAlloc(GetProcessHeap(), 0, maxChars
*sizeof(WCHAR
));
410 parse_title(argv
[i
], title
, maxChars
);
412 WINE_ERR("out of memory\n");
417 if (argv
[i
][0] != '/')
420 /* Unix paths can start with / so we have to assume anything following /unix is not a flag */
421 if (unix_mode
|| progid_open
)
424 if (argv
[i
][0] == '/' && (argv
[i
][1] == 'd' || argv
[i
][1] == 'D')) {
426 /* The start directory was concatenated to the option */
427 sei
.lpDirectory
= argv
[i
]+2;
428 else if (i
+1 == argc
) {
429 WINE_ERR("you must specify a directory path for the /d option\n");
432 sei
.lpDirectory
= argv
[++i
];
434 else if (is_option(argv
[i
], bW
)) {
435 creation_flags
&= ~CREATE_NEW_CONSOLE
;
437 else if (argv
[i
][0] == '/' && (argv
[i
][1] == 'i' || argv
[i
][1] == 'I')) {
438 TRACE("/i is ignored\n"); /* FIXME */
440 else if (is_option(argv
[i
], minW
)) {
441 sei
.nShow
= SW_SHOWMINIMIZED
;
443 else if (is_option(argv
[i
], maxW
)) {
444 sei
.nShow
= SW_SHOWMAXIMIZED
;
446 else if (is_option(argv
[i
], lowW
)) {
447 creation_flags
|= IDLE_PRIORITY_CLASS
;
449 else if (is_option(argv
[i
], normalW
)) {
450 creation_flags
|= NORMAL_PRIORITY_CLASS
;
452 else if (is_option(argv
[i
], highW
)) {
453 creation_flags
|= HIGH_PRIORITY_CLASS
;
455 else if (is_option(argv
[i
], realtimeW
)) {
456 creation_flags
|= REALTIME_PRIORITY_CLASS
;
458 else if (is_option(argv
[i
], abovenormalW
)) {
459 creation_flags
|= ABOVE_NORMAL_PRIORITY_CLASS
;
461 else if (is_option(argv
[i
], belownormalW
)) {
462 creation_flags
|= BELOW_NORMAL_PRIORITY_CLASS
;
464 else if (is_option(argv
[i
], separateW
)) {
465 TRACE("/separate is ignored\n"); /* FIXME */
467 else if (is_option(argv
[i
], sharedW
)) {
468 TRACE("/shared is ignored\n"); /* FIXME */
470 else if (is_option(argv
[i
], nodeW
)) {
472 WINE_ERR("you must specify a numa node for the /node option\n");
476 TRACE("/node is ignored\n"); /* FIXME */
480 else if (is_option(argv
[i
], affinityW
))
483 WINE_ERR("you must specify a numa node for the /node option\n");
487 TRACE("/affinity is ignored\n"); /* FIXME */
491 else if (is_option(argv
[i
], wW
) || is_option(argv
[i
], waitW
)) {
492 sei
.fMask
|= SEE_MASK_NOCLOSEPROCESS
;
494 else if (is_option(argv
[i
], helpW
)) {
498 /* Wine extensions */
500 else if (is_option(argv
[i
], unixW
)) {
503 else if (is_option(argv
[i
], progIDOpenW
)) {
508 WINE_ERR("Unknown option '%s'\n", wine_dbgstr_w(argv
[i
]));
516 sei
.lpClass
= argv
[i
++];
517 sei
.fMask
|= SEE_MASK_CLASSNAME
;
521 if (progid_open
|| unix_mode
)
528 args
= build_args( argc
- i
, &argv
[i
] );
529 sei
.lpParameters
= args
;
531 if (unix_mode
|| progid_open
) {
532 LPWSTR (*CDECL wine_get_dos_file_name_ptr
)(LPCSTR
);
533 char* multibyte_unixpath
;
534 int multibyte_unixpath_len
;
536 wine_get_dos_file_name_ptr
= (void*)GetProcAddress(GetModuleHandleA("KERNEL32"), "wine_get_dos_file_name");
538 if (!wine_get_dos_file_name_ptr
)
539 fatal_string(STRING_UNIXFAIL
);
541 multibyte_unixpath_len
= WideCharToMultiByte(CP_UNIXCP
, 0, file
, -1, NULL
, 0, NULL
, NULL
);
542 multibyte_unixpath
= HeapAlloc(GetProcessHeap(), 0, multibyte_unixpath_len
);
544 WideCharToMultiByte(CP_UNIXCP
, 0, file
, -1, multibyte_unixpath
, multibyte_unixpath_len
, NULL
, NULL
);
546 dos_filename
= wine_get_dos_file_name_ptr(multibyte_unixpath
);
548 HeapFree(GetProcessHeap(), 0, multibyte_unixpath
);
551 fatal_string(STRING_UNIXFAIL
);
553 sei
.lpFile
= dos_filename
;
554 if (!sei
.lpDirectory
)
555 sei
.lpDirectory
= parent_directory
= get_parent_dir(dos_filename
);
556 sei
.fMask
&= ~SEE_MASK_FLAG_NO_UI
;
558 if (search_path(file
, &fullpath
)) {
559 if (fullpath
!= NULL
) {
560 sei
.lpFile
= fullpath
;
562 fatal_string_error(STRING_EXECFAIL
, ERROR_OUTOFMEMORY
, file
);
569 if (GetBinaryTypeW(sei
.lpFile
, &binary_type
)) {
571 STARTUPINFOW startup_info
;
572 PROCESS_INFORMATION process_information
;
573 static const WCHAR commandlineformat
[] = {'"','%','s','"','%','s',0};
575 /* 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 */
577 commandline
= HeapAlloc(GetProcessHeap(), 0, (lstrlenW(sei
.lpFile
)+3+lstrlenW(sei
.lpParameters
))*sizeof(WCHAR
));
578 swprintf(commandline
, lstrlenW(sei
.lpFile
) + 3 + lstrlenW(sei
.lpParameters
),
579 commandlineformat
, sei
.lpFile
, sei
.lpParameters
);
581 ZeroMemory(&startup_info
, sizeof(startup_info
));
582 startup_info
.cb
= sizeof(startup_info
);
583 startup_info
.wShowWindow
= sei
.nShow
;
584 startup_info
.dwFlags
|= STARTF_USESHOWWINDOW
;
585 startup_info
.lpTitle
= title
;
588 sei
.lpFile
, /* lpApplicationName */
589 commandline
, /* lpCommandLine */
590 NULL
, /* lpProcessAttributes */
591 NULL
, /* lpThreadAttributes */
592 FALSE
, /* bInheritHandles */
593 creation_flags
, /* dwCreationFlags */
594 NULL
, /* lpEnvironment */
595 sei
.lpDirectory
, /* lpCurrentDirectory */
596 &startup_info
, /* lpStartupInfo */
597 &process_information
/* lpProcessInformation */ ))
599 fatal_string_error(STRING_EXECFAIL
, GetLastError(), sei
.lpFile
);
601 sei
.hProcess
= process_information
.hProcess
;
605 if (!ShellExecuteExW(&sei
))
607 static const WCHAR pathextW
[] = {'P','A','T','H','E','X','T',0};
608 const WCHAR
*filename
= sei
.lpFile
;
609 DWORD size
, filename_len
;
612 size
= GetEnvironmentVariableW(pathextW
, NULL
, 0);
617 env
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
));
619 fatal_string_error(STRING_EXECFAIL
, ERROR_OUTOFMEMORY
, sei
.lpFile
);
620 GetEnvironmentVariableW(pathextW
, env
, size
);
622 filename_len
= lstrlenW(filename
);
623 name
= HeapAlloc(GetProcessHeap(), 0, (filename_len
+ size
) * sizeof(WCHAR
));
625 fatal_string_error(STRING_EXECFAIL
, ERROR_OUTOFMEMORY
, sei
.lpFile
);
629 while ((ptr
= wcschr(start
, ';')))
637 lstrcpyW(name
, filename
);
638 memcpy(&name
[filename_len
], start
, (ptr
- start
) * sizeof(WCHAR
));
639 name
[filename_len
+ (ptr
- start
)] = 0;
641 if (ShellExecuteExW(&sei
))
643 HeapFree(GetProcessHeap(), 0, name
);
644 HeapFree(GetProcessHeap(), 0, env
);
653 fatal_string_error(STRING_EXECFAIL
, GetLastError(), filename
);
657 HeapFree( GetProcessHeap(), 0, args
);
658 HeapFree( GetProcessHeap(), 0, dos_filename
);
659 HeapFree( GetProcessHeap(), 0, fullpath
);
660 HeapFree( GetProcessHeap(), 0, parent_directory
);
661 HeapFree( GetProcessHeap(), 0, title
);
663 if (sei
.fMask
& SEE_MASK_NOCLOSEPROCESS
) {
665 WaitForSingleObject(sei
.hProcess
, INFINITE
);
666 GetExitCodeProcess(sei
.hProcess
, &exitcode
);
667 ExitProcess(exitcode
);