cmdproxy.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. /* Proxy shell designed for use with Emacs on Windows 95 and NT.
  2. Copyright (C) 1997, 2001-2017 Free Software Foundation, Inc.
  3. Accepts subset of Unix sh(1) command-line options, for compatibility
  4. with elisp code written for Unix. When possible, executes external
  5. programs directly (a common use of /bin/sh by Emacs), otherwise
  6. invokes the user-specified command processor to handle built-in shell
  7. commands, batch files and interactive mode.
  8. The main function is simply to process the "-c string" option in the
  9. way /bin/sh does, since the standard Windows command shells use the
  10. convention that everything after "/c" (the Windows equivalent of
  11. "-c") is the input string.
  12. This file is part of GNU Emacs.
  13. GNU Emacs is free software: you can redistribute it and/or modify
  14. it under the terms of the GNU General Public License as published by
  15. the Free Software Foundation, either version 3 of the License, or (at
  16. your option) any later version.
  17. GNU Emacs is distributed in the hope that it will be useful,
  18. but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. GNU General Public License for more details.
  21. You should have received a copy of the GNU General Public License
  22. along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
  23. #include <windows.h>
  24. #include <stdarg.h> /* va_args */
  25. #include <malloc.h> /* alloca */
  26. #include <stdlib.h> /* getenv */
  27. #include <string.h> /* strlen */
  28. #include <ctype.h> /* isspace, isalpha */
  29. /* We don't want to include stdio.h because we are already duplicating
  30. lots of it here */
  31. extern int _snprintf (char *buffer, size_t count, const char *format, ...);
  32. /******* Mock C library routines *********************************/
  33. /* These routines are used primarily to minimize the executable size. */
  34. #define stdout GetStdHandle (STD_OUTPUT_HANDLE)
  35. #define stderr GetStdHandle (STD_ERROR_HANDLE)
  36. #if __GNUC__ + (__GNUC_MINOR__ >= 4) >= 5
  37. void fail (const char *, ...) __attribute__((noreturn));
  38. #else
  39. void fail (const char *, ...);
  40. #endif
  41. int vfprintf (HANDLE, const char *, va_list);
  42. int fprintf (HANDLE, const char *, ...);
  43. int printf (const char *, ...);
  44. void warn (const char *, ...);
  45. int
  46. vfprintf (HANDLE hnd, const char * msg, va_list args)
  47. {
  48. DWORD bytes_written;
  49. char buf[1024];
  50. wvsprintf (buf, msg, args);
  51. return WriteFile (hnd, buf, strlen (buf), &bytes_written, NULL);
  52. }
  53. int
  54. fprintf (HANDLE hnd, const char * msg, ...)
  55. {
  56. va_list args;
  57. int rc;
  58. va_start (args, msg);
  59. rc = vfprintf (hnd, msg, args);
  60. va_end (args);
  61. return rc;
  62. }
  63. int
  64. printf (const char * msg, ...)
  65. {
  66. va_list args;
  67. int rc;
  68. va_start (args, msg);
  69. rc = vfprintf (stdout, msg, args);
  70. va_end (args);
  71. return rc;
  72. }
  73. void
  74. fail (const char * msg, ...)
  75. {
  76. va_list args;
  77. va_start (args, msg);
  78. vfprintf (stderr, msg, args);
  79. va_end (args);
  80. exit (-1);
  81. }
  82. void
  83. warn (const char * msg, ...)
  84. {
  85. va_list args;
  86. va_start (args, msg);
  87. vfprintf (stderr, msg, args);
  88. va_end (args);
  89. }
  90. /******************************************************************/
  91. static char *
  92. canon_filename (char *fname)
  93. {
  94. char *p = fname;
  95. while (*p)
  96. {
  97. if (*p == '/')
  98. *p = '\\';
  99. p++;
  100. }
  101. return fname;
  102. }
  103. static const char *
  104. skip_space (const char *str)
  105. {
  106. while (isspace (*str)) str++;
  107. return str;
  108. }
  109. static const char *
  110. skip_nonspace (const char *str)
  111. {
  112. while (*str && !isspace (*str)) str++;
  113. return str;
  114. }
  115. /* This value is never changed by the code. We keep the code that
  116. supports also the value of '"', but let's allow the compiler to
  117. optimize it out, until someone actually uses that. */
  118. const int escape_char = '\\';
  119. /* Get next token from input, advancing pointer. */
  120. static int
  121. get_next_token (char * buf, const char ** pSrc)
  122. {
  123. const char * p = *pSrc;
  124. char * o = buf;
  125. p = skip_space (p);
  126. if (*p == '"')
  127. {
  128. int escape_char_run = 0;
  129. /* Go through src until an ending quote is found, unescaping
  130. quotes along the way. If the escape char is not quote, then do
  131. special handling of multiple escape chars preceding a quote
  132. char (ie. the reverse of what Emacs does to escape quotes). */
  133. p++;
  134. while (1)
  135. {
  136. if (p[0] == escape_char && escape_char != '"')
  137. {
  138. escape_char_run++;
  139. p++;
  140. continue;
  141. }
  142. else if (p[0] == '"')
  143. {
  144. while (escape_char_run > 1)
  145. {
  146. *o++ = escape_char;
  147. escape_char_run -= 2;
  148. }
  149. if (escape_char_run > 0)
  150. {
  151. /* escaped quote */
  152. *o++ = *p++;
  153. escape_char_run = 0;
  154. }
  155. else if (p[1] == escape_char && escape_char == '"')
  156. {
  157. /* quote escaped by doubling */
  158. *o++ = *p;
  159. p += 2;
  160. }
  161. else
  162. {
  163. /* The ending quote. */
  164. *o = '\0';
  165. /* Leave input pointer after token. */
  166. p++;
  167. break;
  168. }
  169. }
  170. else if (p[0] == '\0')
  171. {
  172. /* End of string, but no ending quote found. We might want to
  173. flag this as an error, but for now will consider the end as
  174. the end of the token. */
  175. if (escape_char == '\\')
  176. {
  177. /* Output literal backslashes. Note that if the
  178. token ends with an unpaired backslash, we eat it
  179. up here. But since this case invokes undefined
  180. behavior anyway, it's okay. */
  181. while (escape_char_run > 1)
  182. {
  183. *o++ = escape_char;
  184. escape_char_run -= 2;
  185. }
  186. }
  187. *o = '\0';
  188. break;
  189. }
  190. else
  191. {
  192. if (escape_char == '\\')
  193. {
  194. /* Output literal backslashes. Note that we don't
  195. treat a backslash as an escape character here,
  196. since it doesn't precede a quote. */
  197. for ( ; escape_char_run > 0; escape_char_run--)
  198. *o++ = escape_char;
  199. }
  200. *o++ = *p++;
  201. }
  202. }
  203. }
  204. else
  205. {
  206. /* Next token is delimited by whitespace. */
  207. const char * p1 = skip_nonspace (p);
  208. memcpy (o, p, p1 - p);
  209. o += (p1 - p);
  210. *o = '\0';
  211. p = p1;
  212. }
  213. *pSrc = p;
  214. return o - buf;
  215. }
  216. /* Return TRUE if PROGNAME is a batch file. */
  217. static BOOL
  218. batch_file_p (const char *progname)
  219. {
  220. const char *exts[] = {".bat", ".cmd"};
  221. int n_exts = sizeof (exts) / sizeof (char *);
  222. int i;
  223. const char *ext = strrchr (progname, '.');
  224. if (ext)
  225. {
  226. for (i = 0; i < n_exts; i++)
  227. {
  228. if (stricmp (ext, exts[i]) == 0)
  229. return TRUE;
  230. }
  231. }
  232. return FALSE;
  233. }
  234. /* Search for EXEC file in DIR. If EXEC does not have an extension,
  235. DIR is searched for EXEC with the standard extensions appended. */
  236. static int
  237. search_dir (const char *dir, const char *exec, int bufsize, char *buffer)
  238. {
  239. const char *exts[] = {".bat", ".cmd", ".exe", ".com"};
  240. int n_exts = sizeof (exts) / sizeof (char *);
  241. char *dummy;
  242. int i, rc;
  243. const char *pext = strrchr (exec, '\\');
  244. /* Does EXEC already include an extension? */
  245. if (!pext)
  246. pext = exec;
  247. pext = strchr (pext, '.');
  248. /* Search the directory for the program. */
  249. if (pext)
  250. {
  251. /* SearchPath will not append an extension if the file already
  252. has an extension, so we must append it ourselves. */
  253. char exec_ext[MAX_PATH], *p;
  254. p = strcpy (exec_ext, exec) + strlen (exec);
  255. /* Search first without any extension; if found, we are done. */
  256. rc = SearchPath (dir, exec_ext, NULL, bufsize, buffer, &dummy);
  257. if (rc > 0)
  258. return rc;
  259. /* Try the known extensions. */
  260. for (i = 0; i < n_exts; i++)
  261. {
  262. strcpy (p, exts[i]);
  263. rc = SearchPath (dir, exec_ext, NULL, bufsize, buffer, &dummy);
  264. if (rc > 0)
  265. return rc;
  266. }
  267. }
  268. else
  269. {
  270. for (i = 0; i < n_exts; i++)
  271. {
  272. rc = SearchPath (dir, exec, exts[i], bufsize, buffer, &dummy);
  273. if (rc > 0)
  274. return rc;
  275. }
  276. }
  277. return 0;
  278. }
  279. /* Return the absolute name of executable file PROG, including
  280. any file extensions. If an absolute name for PROG cannot be found,
  281. return NULL. */
  282. static char *
  283. make_absolute (const char *prog)
  284. {
  285. char absname[MAX_PATH];
  286. char dir[MAX_PATH];
  287. char curdir[MAX_PATH];
  288. char *p, *path;
  289. const char *fname;
  290. /* At least partial absolute path specified; search there. */
  291. if ((isalpha (prog[0]) && prog[1] == ':') ||
  292. (prog[0] == '\\'))
  293. {
  294. /* Split the directory from the filename. */
  295. fname = strrchr (prog, '\\');
  296. if (!fname)
  297. /* Only a drive specifier is given. */
  298. fname = prog + 2;
  299. strncpy (dir, prog, fname - prog);
  300. dir[fname - prog] = '\0';
  301. /* Search the directory for the program. */
  302. if (search_dir (dir, prog, MAX_PATH, absname) > 0)
  303. return strdup (absname);
  304. else
  305. return NULL;
  306. }
  307. if (GetCurrentDirectory (MAX_PATH, curdir) <= 0)
  308. return NULL;
  309. /* Relative path; search in current dir. */
  310. if (strpbrk (prog, "\\"))
  311. {
  312. if (search_dir (curdir, prog, MAX_PATH, absname) > 0)
  313. return strdup (absname);
  314. else
  315. return NULL;
  316. }
  317. /* Just filename; search current directory then PATH. */
  318. path = alloca (strlen (getenv ("PATH")) + strlen (curdir) + 2);
  319. strcpy (path, curdir);
  320. strcat (path, ";");
  321. strcat (path, getenv ("PATH"));
  322. while (*path)
  323. {
  324. size_t len;
  325. /* Get next directory from path. */
  326. p = path;
  327. while (*p && *p != ';') p++;
  328. /* A broken PATH could have too long directory names in it. */
  329. len = min (p - path, sizeof (dir) - 1);
  330. strncpy (dir, path, len);
  331. dir[len] = '\0';
  332. /* Search the directory for the program. */
  333. if (search_dir (dir, prog, MAX_PATH, absname) > 0)
  334. return strdup (absname);
  335. /* Move to the next directory. */
  336. path = p + 1;
  337. }
  338. return NULL;
  339. }
  340. /* Try to decode the given command line the way cmd would do it. On
  341. success, return 1 with cmdline dequoted. Otherwise, when we've
  342. found constructs only cmd can properly interpret, return 0 and
  343. leave cmdline unchanged. */
  344. static int
  345. try_dequote_cmdline (char* cmdline)
  346. {
  347. /* Dequoting can only subtract characters, so the length of the
  348. original command line is a bound on the amount of scratch space
  349. we need. This length, in turn, is bounded by the 32k
  350. CreateProcess limit. */
  351. char * old_pos = cmdline;
  352. char * new_cmdline = alloca (strlen(cmdline));
  353. char * new_pos = new_cmdline;
  354. char c;
  355. enum {
  356. NORMAL,
  357. AFTER_CARET,
  358. INSIDE_QUOTE
  359. } state = NORMAL;
  360. while ((c = *old_pos++))
  361. {
  362. switch (state)
  363. {
  364. case NORMAL:
  365. switch(c)
  366. {
  367. case '"':
  368. *new_pos++ = c;
  369. state = INSIDE_QUOTE;
  370. break;
  371. case '^':
  372. state = AFTER_CARET;
  373. break;
  374. case '<': case '>':
  375. case '&': case '|':
  376. case '(': case ')':
  377. case '%': case '!':
  378. /* We saw an unquoted shell metacharacter and we don't
  379. understand it. Bail out. */
  380. return 0;
  381. default:
  382. *new_pos++ = c;
  383. break;
  384. }
  385. break;
  386. case AFTER_CARET:
  387. *new_pos++ = c;
  388. state = NORMAL;
  389. break;
  390. case INSIDE_QUOTE:
  391. switch (c)
  392. {
  393. case '"':
  394. *new_pos++ = c;
  395. state = NORMAL;
  396. break;
  397. case '%':
  398. case '!':
  399. /* Variable substitution inside quote. Bail out. */
  400. return 0;
  401. default:
  402. *new_pos++ = c;
  403. break;
  404. }
  405. break;
  406. }
  407. }
  408. /* We were able to dequote the entire string. Copy our scratch
  409. buffer on top of the original buffer and return success. */
  410. memcpy (cmdline, new_cmdline, new_pos - new_cmdline);
  411. cmdline[new_pos - new_cmdline] = '\0';
  412. return 1;
  413. }
  414. /*****************************************************************/
  415. #if 0
  416. char ** _argv;
  417. int _argc;
  418. /* Parse commandline into argv array, allowing proper quoting of args. */
  419. void
  420. setup_argv (void)
  421. {
  422. char * cmdline = GetCommandLine ();
  423. int arg_bytes = 0;
  424. }
  425. #endif
  426. /* Information about child proc is global, to allow for automatic
  427. termination when interrupted. At the moment, only one child process
  428. can be running at any one time. */
  429. PROCESS_INFORMATION child;
  430. int interactive = TRUE;
  431. BOOL console_event_handler (DWORD);
  432. BOOL
  433. console_event_handler (DWORD event)
  434. {
  435. switch (event)
  436. {
  437. case CTRL_C_EVENT:
  438. case CTRL_BREAK_EVENT:
  439. if (!interactive)
  440. {
  441. /* Both command.com and cmd.exe have the annoying behavior of
  442. prompting "Terminate batch job (y/n)?" when interrupted
  443. while running a batch file, even if running in
  444. non-interactive (-c) mode. Try to make up for this
  445. deficiency by forcibly terminating the subprocess if
  446. running non-interactively. */
  447. if (child.hProcess &&
  448. WaitForSingleObject (child.hProcess, 500) != WAIT_OBJECT_0)
  449. TerminateProcess (child.hProcess, 0);
  450. exit (STATUS_CONTROL_C_EXIT);
  451. }
  452. break;
  453. #if 0
  454. default:
  455. /* CLOSE, LOGOFF and SHUTDOWN events - actually we don't get these
  456. under Windows 95. */
  457. fail ("cmdproxy: received %d event\n", event);
  458. if (child.hProcess)
  459. TerminateProcess (child.hProcess, 0);
  460. #endif
  461. }
  462. return TRUE;
  463. }
  464. /* Change from normal usage; return value indicates whether spawn
  465. succeeded or failed - program return code is returned separately. */
  466. static int
  467. spawn (const char *progname, char *cmdline, const char *dir, int *retcode)
  468. {
  469. BOOL success = FALSE;
  470. SECURITY_ATTRIBUTES sec_attrs;
  471. STARTUPINFO start;
  472. /* In theory, passing NULL for the environment block to CreateProcess
  473. is the same as passing the value of GetEnvironmentStrings, but
  474. doing this explicitly seems to cure problems running DOS programs
  475. in some cases. */
  476. char * envblock = GetEnvironmentStrings ();
  477. sec_attrs.nLength = sizeof (sec_attrs);
  478. sec_attrs.lpSecurityDescriptor = NULL;
  479. sec_attrs.bInheritHandle = FALSE;
  480. memset (&start, 0, sizeof (start));
  481. start.cb = sizeof (start);
  482. /* CreateProcess handles batch files as progname specially. This
  483. special handling fails when both the batch file and arguments are
  484. quoted. We pass NULL as progname to avoid the special
  485. handling. */
  486. if (progname != NULL && cmdline[0] == '"' && batch_file_p (progname))
  487. progname = NULL;
  488. if (CreateProcess (progname, cmdline, &sec_attrs, NULL, TRUE,
  489. 0, envblock, dir, &start, &child))
  490. {
  491. success = TRUE;
  492. /* wait for completion and pass on return code */
  493. WaitForSingleObject (child.hProcess, INFINITE);
  494. if (retcode)
  495. GetExitCodeProcess (child.hProcess, (DWORD *)retcode);
  496. CloseHandle (child.hThread);
  497. CloseHandle (child.hProcess);
  498. child.hProcess = NULL;
  499. }
  500. FreeEnvironmentStrings (envblock);
  501. return success;
  502. }
  503. /* Return size of current environment block. */
  504. static int
  505. get_env_size (void)
  506. {
  507. char * start = GetEnvironmentStrings ();
  508. char * tmp = start;
  509. while (tmp[0] || tmp[1])
  510. ++tmp;
  511. FreeEnvironmentStrings (start);
  512. return tmp + 2 - start;
  513. }
  514. /******* Main program ********************************************/
  515. int
  516. main (int argc, char ** argv)
  517. {
  518. int rc;
  519. int need_shell;
  520. char * cmdline;
  521. char * progname;
  522. int envsize;
  523. char **pass_through_args;
  524. int num_pass_through_args;
  525. char modname[MAX_PATH];
  526. char path[MAX_PATH];
  527. char dir[MAX_PATH];
  528. int status;
  529. interactive = TRUE;
  530. SetConsoleCtrlHandler ((PHANDLER_ROUTINE) console_event_handler, TRUE);
  531. if (!GetCurrentDirectory (sizeof (dir), dir))
  532. fail ("error: GetCurrentDirectory failed\n");
  533. /* We serve double duty: we can be called either as a proxy for the
  534. real shell (that is, because we are defined to be the user shell),
  535. or in our role as a helper application for running DOS programs.
  536. In the former case, we interpret the command line options as if we
  537. were a Unix shell, but in the latter case we simply pass our
  538. command line to CreateProcess. We know which case we are dealing
  539. with by whether argv[0] refers to ourself or to some other program.
  540. (This relies on an arcane feature of CreateProcess, where we can
  541. specify cmdproxy as the module to run, but specify a different
  542. program in the command line - the MSVC startup code sets argv[0]
  543. from the command line.) */
  544. if (!GetModuleFileName (NULL, modname, sizeof (modname)))
  545. fail ("error: GetModuleFileName failed\n");
  546. /* Change directory to location of .exe so startup directory can be
  547. deleted. */
  548. progname = strrchr (modname, '\\');
  549. *progname = '\0';
  550. SetCurrentDirectory (modname);
  551. *progname = '\\';
  552. /* Due to problems with interaction between API functions that use "OEM"
  553. codepage vs API functions that use the "ANSI" codepage, we need to
  554. make things consistent by choosing one and sticking with it. */
  555. SetConsoleCP (GetACP ());
  556. SetConsoleOutputCP (GetACP ());
  557. /* Although Emacs always sets argv[0] to an absolute pathname, we
  558. might get run in other ways as well, so convert argv[0] to an
  559. absolute name before comparing to the module name. */
  560. path[0] = '\0';
  561. /* The call to SearchPath will find argv[0] in the current
  562. directory, append ".exe" to it if needed, and also canonicalize
  563. it, to resolve references to ".", "..", etc. */
  564. status = SearchPath (NULL, argv[0], ".exe", sizeof (path), path,
  565. &progname);
  566. if (!(status > 0 && stricmp (modname, path) == 0))
  567. {
  568. if (status <= 0)
  569. {
  570. char *s;
  571. /* Make sure we have argv[0] in path[], as the failed
  572. SearchPath might not have copied it there. */
  573. strcpy (path, argv[0]);
  574. /* argv[0] could include forward slashes; convert them all
  575. to backslashes, for strrchr calls below to DTRT. */
  576. for (s = path; *s; s++)
  577. if (*s == '/')
  578. *s = '\\';
  579. }
  580. /* Perhaps MODNAME and PATH use mixed short and long file names. */
  581. if (!(GetShortPathName (modname, modname, sizeof (modname))
  582. && GetShortPathName (path, path, sizeof (path))
  583. && stricmp (modname, path) == 0))
  584. {
  585. /* Sometimes GetShortPathName fails because one or more
  586. directories leading to argv[0] have issues with access
  587. rights. In that case, at least we can compare the
  588. basenames. Note: this disregards the improbable case of
  589. invoking a program of the same name from another
  590. directory, since the chances of that other executable to
  591. be both our namesake and a 16-bit DOS application are nil. */
  592. char *p = strrchr (path, '\\');
  593. char *q = strrchr (modname, '\\');
  594. char *pdot, *qdot;
  595. if (!p)
  596. p = strchr (path, ':');
  597. if (!p)
  598. p = path;
  599. else
  600. p++;
  601. if (!q)
  602. q = strchr (modname, ':');
  603. if (!q)
  604. q = modname;
  605. else
  606. q++;
  607. pdot = strrchr (p, '.');
  608. if (!pdot || stricmp (pdot, ".exe") != 0)
  609. pdot = p + strlen (p);
  610. qdot = strrchr (q, '.');
  611. if (!qdot || stricmp (qdot, ".exe") != 0)
  612. qdot = q + strlen (q);
  613. if (pdot - p != qdot - q || strnicmp (p, q, pdot - p) != 0)
  614. {
  615. /* We are being used as a helper to run a DOS app; just
  616. pass command line to DOS app without change. */
  617. /* TODO: fill in progname. */
  618. if (spawn (NULL, GetCommandLine (), dir, &rc))
  619. return rc;
  620. fail ("Could not run %s\n", GetCommandLine ());
  621. }
  622. }
  623. }
  624. /* Process command line. If running interactively (-c or /c not
  625. specified) then spawn a real command shell, passing it the command
  626. line arguments.
  627. If not running interactively, then attempt to execute the specified
  628. command directly. If necessary, spawn a real shell to execute the
  629. command.
  630. */
  631. progname = NULL;
  632. cmdline = NULL;
  633. /* If no args, spawn real shell for interactive use. */
  634. need_shell = TRUE;
  635. interactive = TRUE;
  636. /* Ask command.com to create an environment block with a reasonable
  637. amount of free space. */
  638. envsize = get_env_size () + 300;
  639. pass_through_args = (char **) alloca (argc * sizeof (char *));
  640. num_pass_through_args = 0;
  641. while (--argc > 0)
  642. {
  643. ++argv;
  644. /* Act on switches we recognize (mostly single letter switches,
  645. except for -e); all unrecognized switches and extra args are
  646. passed on to real shell if used (only really of benefit for
  647. interactive use, but allow for batch use as well). Accept / as
  648. switch char for compatibility with cmd.exe. */
  649. if (((*argv)[0] == '-' || (*argv)[0] == '/') && (*argv)[1] != '\0')
  650. {
  651. if (((*argv)[1] == 'c' || (*argv)[1] == 'C') && ((*argv)[2] == '\0'))
  652. {
  653. if (--argc == 0)
  654. fail ("error: expecting arg for %s\n", *argv);
  655. cmdline = *(++argv);
  656. interactive = FALSE;
  657. }
  658. else if (((*argv)[1] == 'i' || (*argv)[1] == 'I') && ((*argv)[2] == '\0'))
  659. {
  660. if (cmdline)
  661. warn ("warning: %s ignored because of -c\n", *argv);
  662. }
  663. else if (((*argv)[1] == 'e' || (*argv)[1] == 'E') && ((*argv)[2] == ':'))
  664. {
  665. int requested_envsize = atoi (*argv + 3);
  666. /* Enforce a reasonable minimum size, as above. */
  667. if (requested_envsize > envsize)
  668. envsize = requested_envsize;
  669. /* For sanity, enforce a reasonable maximum. */
  670. if (envsize > 32768)
  671. envsize = 32768;
  672. }
  673. else
  674. {
  675. /* warn ("warning: unknown option %s ignored", *argv); */
  676. pass_through_args[num_pass_through_args++] = *argv;
  677. }
  678. }
  679. else
  680. break;
  681. }
  682. #if 0
  683. /* I think this is probably not useful - cmd.exe ignores extra
  684. (non-switch) args in interactive mode, and they cannot be passed on
  685. when -c was given. */
  686. /* Collect any remaining args after (initial) switches. */
  687. while (argc-- > 0)
  688. {
  689. pass_through_args[num_pass_through_args++] = *argv++;
  690. }
  691. #else
  692. /* Probably a mistake for there to be extra args; not fatal. */
  693. if (argc > 0)
  694. warn ("warning: extra args ignored after '%s'\n", argv[-1]);
  695. #endif
  696. pass_through_args[num_pass_through_args] = NULL;
  697. /* If -c option, determine if we must spawn a real shell, or if we can
  698. execute the command directly ourself. */
  699. if (cmdline)
  700. {
  701. const char *args;
  702. /* The program name is the first token of cmdline. Since
  703. filenames cannot legally contain embedded quotes, the value
  704. of escape_char doesn't matter. */
  705. args = cmdline;
  706. if (!get_next_token (path, &args))
  707. fail ("error: no program name specified.\n");
  708. canon_filename (path);
  709. progname = make_absolute (path);
  710. /* If we found the program and the rest of the command line does
  711. not contain unquoted shell metacharacters, run the program
  712. directly (if not found it might be an internal shell command,
  713. so don't fail). */
  714. if (progname != NULL && try_dequote_cmdline (cmdline))
  715. need_shell = FALSE;
  716. else
  717. progname = NULL;
  718. }
  719. pass_to_shell:
  720. if (need_shell)
  721. {
  722. char * p;
  723. int extra_arg_space = 0;
  724. int maxlen, remlen;
  725. int run_command_dot_com;
  726. progname = getenv ("COMSPEC");
  727. if (!progname)
  728. fail ("error: COMSPEC is not set\n");
  729. canon_filename (progname);
  730. progname = make_absolute (progname);
  731. if (progname == NULL || strchr (progname, '\\') == NULL)
  732. fail ("error: the program %s could not be found.\n", getenv ("COMSPEC"));
  733. /* Need to set environment size when running command.com. */
  734. run_command_dot_com =
  735. (stricmp (strrchr (progname, '\\'), "command.com") == 0);
  736. /* Work out how much extra space is required for
  737. pass_through_args. */
  738. for (argv = pass_through_args; *argv != NULL; ++argv)
  739. /* We don't expect to have to quote switches. */
  740. extra_arg_space += strlen (*argv) + 2;
  741. if (cmdline)
  742. {
  743. char * buf;
  744. /* Convert to syntax expected by cmd.exe/command.com for
  745. running non-interactively. Always quote program name in
  746. case path contains spaces (fortunately it can't contain
  747. quotes, since they are illegal in path names). */
  748. remlen = maxlen =
  749. strlen (progname) + extra_arg_space + strlen (cmdline) + 16 + 2;
  750. buf = p = alloca (maxlen + 1);
  751. /* Quote progname in case it contains spaces. */
  752. p += _snprintf (p, remlen, "\"%s\"", progname);
  753. remlen = maxlen - (p - buf);
  754. /* Include pass_through_args verbatim; these are just switches
  755. so should not need quoting. */
  756. for (argv = pass_through_args; *argv != NULL; ++argv)
  757. {
  758. p += _snprintf (p, remlen, " %s", *argv);
  759. remlen = maxlen - (p - buf);
  760. }
  761. /* Now that we know we will be invoking the shell, quote the
  762. command line after the "/c" switch as the shell expects:
  763. a single pair of quotes enclosing the entire command
  764. tail, no matter whether quotes are used in the command
  765. line, and how many of them are there. See the output of
  766. "cmd /?" for how cmd.exe treats quotes. */
  767. if (run_command_dot_com)
  768. _snprintf (p, remlen, " /e:%d /c \"%s\"", envsize, cmdline);
  769. else
  770. _snprintf (p, remlen, " /c \"%s\"", cmdline);
  771. cmdline = buf;
  772. }
  773. else
  774. {
  775. if (run_command_dot_com)
  776. {
  777. /* Provide dir arg expected by command.com when first
  778. started interactively (the "command search path"). To
  779. avoid potential problems with spaces in command dir
  780. (which cannot be quoted - command.com doesn't like it),
  781. we always use the 8.3 form. */
  782. GetShortPathName (progname, path, sizeof (path));
  783. p = strrchr (path, '\\');
  784. /* Trailing slash is acceptable, so always leave it. */
  785. *(++p) = '\0';
  786. }
  787. else
  788. path[0] = '\0';
  789. remlen = maxlen =
  790. strlen (progname) + extra_arg_space + strlen (path) + 13;
  791. cmdline = p = alloca (maxlen + 1);
  792. /* Quote progname in case it contains spaces. */
  793. p += _snprintf (p, remlen, "\"%s\" %s", progname, path);
  794. remlen = maxlen - (p - cmdline);
  795. /* Include pass_through_args verbatim; these are just switches
  796. so should not need quoting. */
  797. for (argv = pass_through_args; *argv != NULL; ++argv)
  798. {
  799. p += _snprintf (p, remlen, " %s", *argv);
  800. remlen = maxlen - (p - cmdline);
  801. }
  802. if (run_command_dot_com)
  803. _snprintf (p, remlen, " /e:%d", envsize);
  804. }
  805. }
  806. if (!progname)
  807. fail ("Internal error: program name not defined\n");
  808. if (!cmdline)
  809. cmdline = progname;
  810. if (spawn (progname, cmdline, dir, &rc))
  811. return rc;
  812. if (!need_shell)
  813. {
  814. need_shell = TRUE;
  815. goto pass_to_shell;
  816. }
  817. fail ("Could not run %s\n", progname);
  818. return 0;
  819. }