start.c 9.93 KB
Newer Older
1 2 3 4 5
/*
 * Start a program using ShellExecuteEx, optionally wait for it to finish
 * Compatible with Microsoft's "c:\windows\command\start.exe"
 *
 * Copyright 2003 Dan Kegel
6
 * Copyright 2007 Lyutin Anatoly (Etersoft)
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 24
 */

#include <stdio.h>
#include <stdlib.h>
25
#include <windows.h>
26
#include <shlobj.h>
27
#include <shellapi.h>
28

29 30 31
#include <wine/unicode.h>
#include <wine/debug.h>

32 33
#include "resources.h"

34 35
WINE_DEFAULT_DEBUG_CHANNEL(start);

36 37 38
/**
 Output given message to stdout without formatting.
*/
39
static void output(const WCHAR *message)
40 41
{
	DWORD count;
42 43
	DWORD   res;
	int    wlen = strlenW(message);
44

45
	if (!wlen) return;
46

47 48
	res = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), message, wlen, &count, NULL);

49 50 51
	/* If writing to console fails, assume it's file
         * i/o so convert to OEM codepage and output
         */
52 53 54 55 56 57 58 59 60 61 62
	if (!res)
	{
		DWORD len;
		char  *mesA;
		/* Convert to OEM, then output */
		len = WideCharToMultiByte( GetConsoleOutputCP(), 0, message, wlen, NULL, 0, NULL, NULL );
		mesA = HeapAlloc(GetProcessHeap(), 0, len*sizeof(char));
		if (!mesA) return;
		WideCharToMultiByte( GetConsoleOutputCP(), 0, message, wlen, mesA, len, NULL, NULL );
		WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), mesA, len, &count, FALSE);
		HeapFree(GetProcessHeap(), 0, mesA);
63 64 65 66 67 68 69 70 71 72
	}
}

/**
 Output given message from string table,
 followed by ": ",
 followed by description of given GetLastError() value to stdout,
 followed by a trailing newline,
 then terminate.
*/
73

74
static void fatal_error(const WCHAR *msg, DWORD error_code, const WCHAR *filename)
75
{
76
    DWORD_PTR args[1];
77 78 79 80 81 82 83
    LPVOID lpMsgBuf;
    int status;
    static const WCHAR colonsW[] = { ':', ' ', 0 };
    static const WCHAR newlineW[] = { '\n', 0 };

    output(msg);
    output(colonsW);
84 85 86
    args[0] = (DWORD_PTR)filename;
    status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
                            NULL, error_code, 0, (LPWSTR)&lpMsgBuf, 0, (__ms_va_list *)args );
87 88 89 90 91 92 93 94 95 96 97 98
    if (!status)
    {
        WINE_ERR("FormatMessage failed\n");
    } else
    {
        output(lpMsgBuf);
        LocalFree((HLOCAL) lpMsgBuf);
        output(newlineW);
    }
    ExitProcess(1);
}

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 105
					msg, sizeof(msg)/sizeof(WCHAR)))
		WINE_ERR("LoadString failed, error %d\n", GetLastError());
106

107
	fatal_error(msg, error_code, filename);
108 109 110 111
}
	
static void fatal_string(int which)
{
112
	WCHAR msg[2048];
113

114
	if (!LoadStringW(GetModuleHandleW(NULL), which,
115 116
					msg, sizeof(msg)/sizeof(WCHAR)))
		WINE_ERR("LoadString failed, error %d\n", GetLastError());
117 118 119 120 121

	output(msg);
	ExitProcess(1);
}

122
static void usage(void)
123 124 125 126
{
	fatal_string(STRING_USAGE);
}

127
static WCHAR *build_args( int argc, WCHAR **argvW )
128
{
129 130 131 132
	int i, wlen = 1;
	WCHAR *ret, *p;
	static const WCHAR FormatQuotesW[] = { ' ', '\"', '%', 's', '\"', 0 };
	static const WCHAR FormatW[] = { ' ', '%', 's', 0 };
133 134

	for (i = 0; i < argc; i++ )
135
	{
136 137 138
		wlen += strlenW(argvW[i]) + 1;
		if (strchrW(argvW[i], ' '))
			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 146
		if (strchrW(argvW[i], ' '))
			p += sprintfW(p, FormatQuotesW, argvW[i]);
147
		else
148
			p += sprintfW(p, FormatW, argvW[i]);
149
	}
150 151 152
	return ret;
}

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
static WCHAR *get_parent_dir(WCHAR* path)
{
	WCHAR *last_slash;
	WCHAR *result;
	int len;

	last_slash = strrchrW( path, '\\' );
	if (last_slash == NULL)
		len = 1;
	else
		len = last_slash - path + 1;

	result = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
	CopyMemory(result, path, (len-1)*sizeof(WCHAR));
	result[len-1] = '\0';

	return result;
}

172
int wmain (int argc, WCHAR *argv[])
173
{
174 175
	SHELLEXECUTEINFOW sei;
	WCHAR *args = NULL;
176
	int i;
177
	int unix_mode = 0;
178
	int progid_open = 0;
179 180 181
	WCHAR *dos_filename = NULL;
	WCHAR *parent_directory = NULL;
	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 186
	static const WCHAR progIDOpenW[] =
		{ 'p', 'r', 'o', 'g', 'I', 'D', 'O', 'p', 'e', 'n', 0};
187

188 189
	memset(&sei, 0, sizeof(sei));
	sei.cbSize = sizeof(sei);
190
	sei.lpVerb = openW;
191 192
	sei.nShow = SW_SHOWNORMAL;
	/* Dunno what these mean, but it looks like winMe's start uses them */
193 194 195
	sei.fMask = SEE_MASK_FLAG_DDEWAIT|
	            SEE_MASK_FLAG_NO_UI|
	            SEE_MASK_NO_CONSOLE;
196 197 198 199 200

	/* Canonical Microsoft commandline flag processing:
	 * flags start with /, are case insensitive,
	 * and may be run together in same word.
	 */
201
	for (i=1; i<argc; i++) {
202 203
		int ci;

204
		if (argv[i][0] != '/')
205 206
			break;

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 210
			break;

211
		/* Handle all options in this word */
212
		for (ci=0; argv[i][ci]; ) {
213 214
			/* Skip slash */
			ci++;
215
			switch(argv[i][ci]) {
216 217 218 219 220 221
			case 'b':
			case 'B':
				break; /* FIXME: should stop new window from being created */
			case 'i':
			case 'I':
				break; /* FIXME: should ignore any changes to current environment */
222 223
			case 'm':
			case 'M':
224
				if (argv[i][ci+1] == 'a' || argv[i][ci+1] == 'A')
225 226 227 228 229 230 231 232
					sei.nShow = SW_SHOWMAXIMIZED;
				else
					sei.nShow = SW_SHOWMINIMIZED;
				break;
			case 'r':
			case 'R':
				/* sei.nShow = SW_SHOWNORMAL; */
				break;
233 234 235 236 237 238 239 240 241
			case 'u':
			case 'U':
				if (strncmpiW(&argv[i][ci], unixW, 4) == 0)
					unix_mode = 1;
				else {
					WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
					usage();
				}
				break;
242 243 244 245 246 247 248 249 250
			case 'p':
			case 'P':
				if (strncmpiW(&argv[i][ci], progIDOpenW, 17) == 0)
					progid_open = 1;
				else {
					WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
					usage();
				}
				break;
251 252 253 254
			case 'w':
			case 'W':
				sei.fMask |= SEE_MASK_NOCLOSEPROCESS;
				break;
255 256 257
			case '?':
				usage();
				break;
258
			default:
259
				WINE_ERR("Option '%s' not recognized\n", wine_dbgstr_w( argv[i]+ci-1));
260 261 262
				usage();
			}
			/* Skip to next slash */
263
			while (argv[i][ci] && (argv[i][ci] != '/'))
264 265 266 267
				ci++;
		}
	}

268
	if (i == argc)
269 270
		usage();

271 272 273 274 275
	if (progid_open) {
		sei.lpClass = argv[i++];
		sei.fMask |= SEE_MASK_CLASSNAME;
	}

276
	sei.lpFile = argv[i++];
277

278 279
	args = build_args( argc - i, &argv[i] );
	sei.lpParameters = args;
280

281
	if (unix_mode || progid_open) {
282
		LPWSTR (*CDECL wine_get_dos_file_name_ptr)(LPCSTR);
283 284 285
		char* multibyte_unixpath;
		int multibyte_unixpath_len;

286
		wine_get_dos_file_name_ptr = (void*)GetProcAddress(GetModuleHandleA("KERNEL32"), "wine_get_dos_file_name");
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

		if (!wine_get_dos_file_name_ptr)
			fatal_string(STRING_UNIXFAIL);

		multibyte_unixpath_len = WideCharToMultiByte(CP_UNIXCP, 0, sei.lpFile, -1, NULL, 0, NULL, NULL);
		multibyte_unixpath = HeapAlloc(GetProcessHeap(), 0, multibyte_unixpath_len);

		WideCharToMultiByte(CP_UNIXCP, 0, sei.lpFile, -1, multibyte_unixpath, multibyte_unixpath_len, NULL, NULL);

		dos_filename = wine_get_dos_file_name_ptr(multibyte_unixpath);

		HeapFree(GetProcessHeap(), 0, multibyte_unixpath);

		if (!dos_filename)
			fatal_string(STRING_UNIXFAIL);

		sei.lpFile = dos_filename;
		sei.lpDirectory = parent_directory = get_parent_dir(dos_filename);
305
		sei.fMask &= ~SEE_MASK_FLAG_NO_UI;
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

                if (GetBinaryTypeW(sei.lpFile, &binary_type)) {
                    WCHAR *commandline;
                    STARTUPINFOW startup_info;
                    PROCESS_INFORMATION process_information;
                    static WCHAR commandlineformat[] = {'"','%','s','"','%','s',0};

                    /* 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 */

                    commandline = HeapAlloc(GetProcessHeap(), 0, (strlenW(sei.lpFile)+3+strlenW(sei.lpParameters))*sizeof(WCHAR));
                    sprintfW(commandline, commandlineformat, sei.lpFile, sei.lpParameters);

                    ZeroMemory(&startup_info, sizeof(startup_info));
                    startup_info.cb = sizeof(startup_info);

                    if (!CreateProcessW(
                            NULL, /* lpApplicationName */
                            commandline, /* lpCommandLine */
                            NULL, /* lpProcessAttributes */
                            NULL, /* lpThreadAttributes */
                            FALSE, /* bInheritHandles */
                            CREATE_NEW_CONSOLE, /* dwCreationFlags */
                            NULL, /* lpEnvironment */
                            sei.lpDirectory, /* lpCurrentDirectory */
                            &startup_info, /* lpStartupInfo */
                            &process_information /* lpProcessInformation */ ))
                    {
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 346
	HeapFree( GetProcessHeap(), 0, dos_filename );
	HeapFree( GetProcessHeap(), 0, parent_directory );
347

348 349
	if (sei.fMask & SEE_MASK_NOCLOSEPROCESS) {
		DWORD exitcode;
350 351
		WaitForSingleObject(sei.hProcess, INFINITE);
		GetExitCodeProcess(sei.hProcess, &exitcode);
352 353 354 355 356
		ExitProcess(exitcode);
	}

	ExitProcess(0);
}