1 /* Proxy shell designed for use with Emacs on Windows 95 and NT.
2 Copyright (C) 1997 Free Software Foundation, Inc.
4 Accepts subset of Unix sh(1) command-line options, for compatability
5 with elisp code written for Unix. When possible, executes external
6 programs directly (a common use of /bin/sh by Emacs), otherwise
7 invokes the user-specified command processor to handle built-in shell
8 commands, batch files and interactive mode.
10 The main function is simply to process the "-c string" option in the
11 way /bin/sh does, since the standard Windows command shells use the
12 convention that everything after "/c" (the Windows equivalent of
13 "-c") is the input string.
15 This file is part of GNU Emacs.
17 GNU Emacs is free software; you can redistribute it and/or modify
18 it under the terms of the GNU General Public License as published by
19 the Free Software Foundation; either version 2, or (at your option)
22 GNU Emacs is distributed in the hope that it will be useful,
23 but WITHOUT ANY WARRANTY; without even the implied warranty of
24 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 GNU General Public License for more details.
27 You should have received a copy of the GNU General Public License
28 along with GNU Emacs; see the file COPYING. If not, write to
29 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
30 Boston, MA 02111-1307, USA. */
34 #include <stdarg.h> /* va_args */
35 #include <malloc.h> /* alloca */
36 #include <stdlib.h> /* getenv */
37 #include <string.h> /* strlen */
40 /******* Mock C library routines *********************************/
42 /* These routines are used primarily to minimize the executable size. */
44 #define stdin GetStdHandle (STD_INPUT_HANDLE)
45 #define stdout GetStdHandle (STD_OUTPUT_HANDLE)
46 #define stderr GetStdHandle (STD_ERROR_HANDLE)
49 vfprintf(HANDLE hnd
, char * msg
, va_list args
)
54 wvsprintf (buf
, msg
, args
);
55 return WriteFile (hnd
, buf
, strlen (buf
), &bytes_written
, NULL
);
59 fprintf(HANDLE hnd
, char * msg
, ...)
65 rc
= vfprintf (hnd
, msg
, args
);
72 printf(char * msg
, ...)
78 rc
= vfprintf (stdout
, msg
, args
);
85 fail (char * msg
, ...)
90 vfprintf (stderr
, msg
, args
);
97 warn (char * msg
, ...)
101 va_start (args
, msg
);
102 vfprintf (stderr
, msg
, args
);
106 /******************************************************************/
109 canon_filename (char *fname
)
124 skip_space (char *str
)
126 while (isspace (*str
)) str
++;
131 skip_nonspace (char *str
)
133 while (*str
&& !isspace (*str
)) str
++;
137 int escape_char
= '\\';
139 /* Get next token from input, advancing pointer. */
141 get_next_token (char * buf
, char ** pSrc
)
149 int escape_char_run
= 0;
151 /* Go through src until an ending quote is found, unescaping
152 quotes along the way. If the escape char is not quote, then do
153 special handling of multiple escape chars preceding a quote
154 char (ie. the reverse of what Emacs does to escape quotes). */
158 if (p
[0] == escape_char
&& escape_char
!= '"')
163 else if (p
[0] == '"')
165 while (escape_char_run
> 1)
168 escape_char_run
-= 2;
171 if (escape_char_run
> 0)
177 else if (p
[1] == escape_char
&& escape_char
== '"')
179 /* quote escaped by doubling */
185 /* The ending quote. */
187 /* Leave input pointer after token. */
192 else if (p
[0] == '\0')
194 /* End of string, but no ending quote found. We might want to
195 flag this as an error, but for now will consider the end as
196 the end of the token. */
208 /* Next token is delimited by whitespace. */
209 char * p1
= skip_nonspace (p
);
210 memcpy (o
, p
, p1
- p
);
220 /* Search for EXEC file in DIR. If EXEC does not have an extension,
221 DIR is searched for EXEC with the standard extensions appended. */
223 search_dir (char *dir
, char *exec
, int bufsize
, char *buffer
)
225 char *exts
[] = {".bat", ".cmd", ".exe", ".com"};
226 int n_exts
= sizeof (exts
) / sizeof (char *);
230 /* Search the directory for the program. */
231 for (i
= 0; i
< n_exts
; i
++)
233 rc
= SearchPath (dir
, exec
, exts
[i
], bufsize
, buffer
, &dummy
);
241 /* Return the absolute name of executable file PROG, including
242 any file extensions. If an absolute name for PROG cannot be found,
245 make_absolute (char *prog
)
247 char absname
[MAX_PATH
];
249 char curdir
[MAX_PATH
];
254 /* At least partial absolute path specified; search there. */
255 if ((isalpha (prog
[0]) && prog
[1] == ':') ||
258 /* Split the directory from the filename. */
259 fname
= strrchr (prog
, '\\');
261 /* Only a drive specifier is given. */
263 strncpy (dir
, prog
, fname
- prog
);
264 dir
[fname
- prog
] = '\0';
266 /* Search the directory for the program. */
267 if (search_dir (dir
, prog
, MAX_PATH
, absname
) > 0)
268 return strdup (absname
);
273 if (GetCurrentDirectory (MAX_PATH
, curdir
) <= 0)
276 /* Relative path; search in current dir. */
277 if (strpbrk (prog
, "\\"))
279 if (search_dir (curdir
, prog
, MAX_PATH
, absname
) > 0)
280 return strdup (absname
);
285 /* Just filename; search current directory then PATH. */
286 path
= alloca (strlen (getenv ("PATH")) + strlen (curdir
) + 2);
287 strcpy (path
, curdir
);
289 strcat (path
, getenv ("PATH"));
293 /* Get next directory from path. */
295 while (*p
&& *p
!= ';') p
++;
296 strncpy (dir
, path
, p
- path
);
297 dir
[p
- path
] = '\0';
299 /* Search the directory for the program. */
300 if (search_dir (dir
, prog
, MAX_PATH
, absname
) > 0)
301 return strdup (absname
);
303 /* Move to the next directory. */
310 /*****************************************************************/
316 /* Parse commandline into argv array, allowing proper quoting of args. */
320 char * cmdline
= GetCommandLine ();
327 /* Information about child proc is global, to allow for automatic
328 termination when interrupted. At the moment, only one child process
329 can be running at any one time. */
331 PROCESS_INFORMATION child
;
332 int interactive
= TRUE
;
335 console_event_handler (DWORD event
)
340 case CTRL_BREAK_EVENT
:
343 /* Both command.com and cmd.exe have the annoying behaviour of
344 prompting "Terminate batch job (y/n)?" when interrupted
345 while running a batch file, even if running in
346 non-interactive (-c) mode. Try to make up for this
347 deficiency by forcibly terminating the subprocess if
348 running non-interactively. */
349 if (child
.hProcess
&&
350 WaitForSingleObject (child
.hProcess
, 500) != WAIT_OBJECT_0
)
351 TerminateProcess (child
.hProcess
, 0);
352 exit (STATUS_CONTROL_C_EXIT
);
358 /* CLOSE, LOGOFF and SHUTDOWN events - actually we don't get these
360 fail ("cmdproxy: received %d event\n", event
);
362 TerminateProcess (child
.hProcess
, 0);
369 spawn (char * progname
, char * cmdline
)
372 SECURITY_ATTRIBUTES sec_attrs
;
375 sec_attrs
.nLength
= sizeof (sec_attrs
);
376 sec_attrs
.lpSecurityDescriptor
= NULL
;
377 sec_attrs
.bInheritHandle
= FALSE
;
379 memset (&start
, 0, sizeof (start
));
380 start
.cb
= sizeof (start
);
382 if (CreateProcess (progname
, cmdline
, &sec_attrs
, NULL
, TRUE
,
383 0, NULL
, NULL
, &start
, &child
))
385 /* wait for completion and pass on return code */
386 WaitForSingleObject (child
.hProcess
, INFINITE
);
387 GetExitCodeProcess (child
.hProcess
, &rc
);
388 CloseHandle (child
.hThread
);
389 CloseHandle (child
.hProcess
);
390 child
.hProcess
= NULL
;
396 /******* Main program ********************************************/
399 main (int argc
, char ** argv
)
406 char modname
[MAX_PATH
];
412 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
) console_event_handler
, TRUE
);
414 /* We serve double duty: we can be called either as a proxy for the
415 real shell (that is, because we are defined to be the user shell),
416 or in our role as a helper application for running DOS programs.
417 In the former case, we interpret the command line options as if we
418 were a Unix shell, but in the latter case we simply pass our
419 command line to CreateProcess. We know which case we are dealing
420 with by whether argv[0] refers to ourself or to some other program.
421 (This relies on an arcane feature of CreateProcess, where we can
422 specify cmdproxy as the module to run, but specify a different
423 program in the command line - the MSVC startup code sets argv[0]
424 from the command line.) */
426 if (!GetModuleFileName (NULL
, modname
, sizeof (modname
)))
427 fail ("GetModuleFileName failed");
429 /* Although Emacs always sets argv[0] to an absolute pathname, we
430 might get run in other ways as well, so convert argv[0] to an
431 absolute name before comparing to the module name. */
432 if (!SearchPath (NULL
, argv
[0], ".exe", sizeof (path
), path
, &progname
)
433 || stricmp (modname
, path
) != 0)
435 /* We are being used as a helper to run a DOS app; just pass
436 command line to DOS app without change. */
437 /* TODO: fill in progname. */
438 return spawn (NULL
, GetCommandLine ());
441 /* Process command line. If running interactively (-c or /c not
442 specified) then spawn a real command shell, passing it the command
445 If not running interactively, then attempt to execute the specified
446 command directly. If necessary, spawn a real shell to execute the
453 /* If no args, spawn real shell for interactive use. */
456 /* Ask for a reasonable size environment for command.com. */
462 /* Only support single letter switches (except for -e); allow / as
463 switch char for compatability with cmd.exe. */
464 if ( ((*argv
)[0] == '-' || (*argv
)[0] == '/')
465 && (*argv
)[1] != '\0' && (*argv
)[2] == '\0' )
467 if ( ((*argv
)[1] == 'c') && ((*argv
)[2] == '\0') )
470 fail ("error: expecting arg for %s", *argv
);
474 else if ( ((*argv
)[1] == 'i') && ((*argv
)[2] == '\0') )
477 warn ("warning: %s ignored because of -c", *argv
);
479 else if ( ((*argv
)[1] == 'e') && ((*argv
)[2] == ':') )
481 envsize
= atoi (*argv
+ 3);
482 /* Enforce a reasonable minimum size. */
488 warn ("warning: unknown option %s ignored", *argv
);
495 /* If -c option, determine if we must spawn a real shell, or if we can
496 execute the command directly ourself. */
499 /* If no redirection or piping, and if program can be found, then
500 run program directly. Otherwise invoke a real shell. */
502 static char copout_chars
[] = "|<>&";
504 if (strpbrk (cmdline
, copout_chars
) == NULL
)
508 /* The program name is the first token of cmdline. Since
509 filenames cannot legally contain embedded quotes, the value
510 of escape_char doesn't matter. */
512 if (!get_next_token (path
, &args
))
513 fail ("error: no program name specified.\n");
515 canon_filename (path
);
516 progname
= make_absolute (path
);
518 /* If we found the program, run it directly (if not found it
519 might be an internal shell command, so don't fail). */
520 if (progname
!= NULL
)
529 progname
= getenv ("COMSPEC");
531 fail ("error: COMSPEC is not set");
533 canon_filename (progname
);
534 progname
= make_absolute (progname
);
536 if (progname
== NULL
|| strchr (progname
, '\\') == NULL
)
537 fail ("make_absolute failed");
541 /* Convert to syntax expected by cmd.exe/command.com for
542 running non-interactively. Always quote program name in
543 case path contains spaces (fortunately it can't contain
544 quotes, since they are illegal in path names). */
545 wsprintf (p
= alloca (strlen (cmdline
) + strlen (progname
) + 7),
546 "\"%s\" /c %s", progname
, cmdline
);
551 /* Provide dir arg expected by command.com when first started
552 interactively (the "command search path"). cmd.exe does
553 not require it, but accepts it silently - presumably other
554 DOS compatible shells do the same. To avoid potential
555 problems with spaces in command dir (which cannot be quoted
556 - command.com doesn't like it), we always use the 8.3 form. */
557 GetShortPathName (progname
, path
, sizeof (path
));
558 p
= strrchr (path
, '\\');
559 /* Trailing slash is acceptable. */
562 /* Set environment size - again cmd.exe ignores this silently. */
563 wsprintf (p
, " /e:%d", envsize
);
565 /* Quote progname in case it contains spaces. */
566 wsprintf (cmdline
= alloca (strlen (progname
) + strlen (path
) + 4),
567 "\"%s\" %s", progname
, path
);
572 fail ("Internal error: program name not defined\n");
577 rc
= spawn (progname
, cmdline
);