cmdproxy.c 23 KB

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