aboutsummaryrefslogtreecommitdiff
path: root/shell/ash.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--shell/ash.c2826
1 files changed, 2782 insertions, 44 deletions
diff --git a/shell/ash.c b/shell/ash.c
index 9173b8608..0038aa1e9 100644
--- a/shell/ash.c
+++ b/shell/ash.c
@@ -15,6 +15,20 @@
15 * 15 *
16 * Licensed under GPLv2 or later, see file LICENSE in this source tree. 16 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
17 */ 17 */
18
19/*
20 * MinGW notes
21 *
22 * - Environment variables from Windows will all be turned to uppercase.
23 * - PATH accepts both ; and : as separator, but can't be mixed
24 * - command without ".exe" extension is still understood as executable
25 * - shell scripts on the path are detected by the presence of '#!'
26 * - both / and \ are supported in PATH. Usually you must use /
27 * - job control doesn't work, though the jobs builtin is available
28 * - trap doesn't work for signals, only EXIT
29 * - /dev/null is supported for redirection
30 */
31
18//config:config SHELL_ASH 32//config:config SHELL_ASH
19//config: bool #hidden option 33//config: bool #hidden option
20//config: depends on !NOMMU 34//config: depends on !NOMMU
@@ -170,11 +184,36 @@
170//config: you to run the specified command or builtin, 184//config: you to run the specified command or builtin,
171//config: even when there is a function with the same name. 185//config: even when there is a function with the same name.
172//config: 186//config:
187//config:
188//config:config ASH_NOCONSOLE
189//config: bool "'noconsole' option"
190//config: default y
191//config: depends on (ASH || SH_IS_ASH || BASH_IS_ASH) && PLATFORM_MINGW32
192//config: help
193//config: Enable support for the 'noconsole' option, which attempts to
194//config: conceal the console normally associated with a command line
195//config: application. This may be useful when running a shell script
196//config: from a GUI application. Also the 'noiconify' option, which
197//config: controls whether the console is iconified or hidden.
198//config:
199//config:config ASH_GLOB_OPTIONS
200//config: bool "Globbing options"
201//config: default y
202//config: depends on (ASH || SH_IS_ASH || BASH_IS_ASH) && PLATFORM_MINGW32
203//config: help
204//config: Enable support for options to control globbing:
205//config: - 'nocaseglob' allows case-insensitive filename globbing
206//config: - 'nohiddenglob' allows hidden files to be omitted from globbing
207//config: - 'nohidsysglob' allows hidden system files to be omitted
208//config:
173//config:endif # ash options 209//config:endif # ash options
174 210
175//applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP)) 211//applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
176// APPLET_ODDNAME:name main location suid_type help 212// APPLET_ODDNAME:name main location suid_type help
177//applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash)) 213//applet:IF_SH_IS_ASH( APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
214//applet:IF_PLATFORM_MINGW32(
215//applet:IF_SH_IS_ASH( APPLET_ODDNAME(lash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
216//applet:)
178//applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash)) 217//applet:IF_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, ash))
179 218
180//kbuild:lib-$(CONFIG_SHELL_ASH) += ash.o ash_ptr_hack.o shell_common.o 219//kbuild:lib-$(CONFIG_SHELL_ASH) += ash.o ash_ptr_hack.o shell_common.o
@@ -195,7 +234,17 @@
195 234
196#define PROFILE 0 235#define PROFILE 0
197 236
237/*
238 * Only one of JOBS or JOBS_WIN32 is enabled at a time (or neither).
239 * JOBS_WIN32 doesn't enable job control, just some job-related features.
240 */
241#if ENABLE_PLATFORM_MINGW32
242#define JOBS_WIN32 ENABLE_ASH_JOB_CONTROL
243#define JOBS 0
244#else
245#define JOBS_WIN32 0
198#define JOBS ENABLE_ASH_JOB_CONTROL 246#define JOBS ENABLE_ASH_JOB_CONTROL
247#endif
199 248
200#include <fnmatch.h> 249#include <fnmatch.h>
201#include <sys/times.h> 250#include <sys/times.h>
@@ -206,6 +255,10 @@
206#else 255#else
207# define NUM_SCRIPTS 0 256# define NUM_SCRIPTS 0
208#endif 257#endif
258#if ENABLE_PLATFORM_MINGW32
259# include <conio.h>
260# include "lazyload.h"
261#endif
209 262
210/* So far, all bash compat is controlled by one config option */ 263/* So far, all bash compat is controlled by one config option */
211/* Separate defines document which part of code implements what */ 264/* Separate defines document which part of code implements what */
@@ -316,10 +369,89 @@ typedef long arith_t;
316# define unlikely(cond) (cond) 369# define unlikely(cond) (cond)
317#endif 370#endif
318 371
372#if !ENABLE_PLATFORM_MINGW32
373# define is_relative_path(path) ((path)[0] != '/')
374#endif
375
319#if !BB_MMU 376#if !BB_MMU
320# error "Do not even bother, ash will not run on NOMMU machine" 377# error "Do not even bother, ash will not run on NOMMU machine"
321#endif 378#endif
322 379
380#if ENABLE_PLATFORM_MINGW32
381# define FORKSHELL_DEBUG 0
382
383union node;
384struct strlist;
385struct job;
386
387struct forkshell {
388 /* filled by forkshell_copy() */
389 struct globals_var *gvp;
390 struct globals_misc *gmp;
391 struct tblentry **cmdtable;
392#if ENABLE_ASH_ALIAS
393 struct alias **atab;
394#endif
395#if MAX_HISTORY
396 char **history;
397 int cnt_history;
398#endif
399#if JOBS_WIN32
400 struct job *jobtab;
401 unsigned njobs;
402 struct job *curjob;
403#endif
404 /* struct parsefile *g_parsefile; */
405 HANDLE hMapFile;
406 char *old_base;
407 int size;
408# if FORKSHELL_DEBUG
409 int funcblocksize;
410 int funcstringsize;
411# endif
412 int relocatesize;
413
414 /* type of forkshell */
415 int fpid;
416
417 /* generic data, used by forkshell_child */
418 int mode;
419 int nprocs;
420#if JOBS_WIN32
421 int jpnull;
422#endif
423
424 /* optional data, used by forkshell_child */
425 int flags;
426 int fd[3];
427 union node *n;
428 char **argv;
429 char *path;
430};
431
432enum {
433 FS_OPENHERE,
434 FS_EVALBACKCMD,
435 FS_EVALSUBSHELL,
436 FS_EVALPIPE,
437 FS_SHELLEXEC
438};
439
440static struct forkshell* forkshell_prepare(struct forkshell *fs);
441static void forkshell_init(const char *idstr);
442static void *sticky_mem_start, *sticky_mem_end;
443static void sticky_free(void *p);
444# define free(p) sticky_free(p)
445#if !JOBS && !JOBS_WIN32
446#define spawn_forkshell(fs, jp, n, mode) spawn_forkshell(fs, jp, mode)
447#endif
448static void spawn_forkshell(struct forkshell *fs, struct job *jp,
449 union node *n, int mode);
450# if FORKSHELL_DEBUG
451static void forkshell_print(FILE *fp0, struct forkshell *fs, const char **notes);
452# endif
453#endif
454
323/* ============ Hash table sizes. Configurable. */ 455/* ============ Hash table sizes. Configurable. */
324 456
325#define VTABSIZE 39 457#define VTABSIZE 39
@@ -347,7 +479,11 @@ static const char *const optletters_optnames[] ALIGN_PTR = {
347 "m" "monitor", 479 "m" "monitor",
348 "n" "noexec", 480 "n" "noexec",
349/* Ditto: bash has no "set -s", "set -c" */ 481/* Ditto: bash has no "set -s", "set -c" */
482#if !ENABLE_PLATFORM_MINGW32
350 "s" "", 483 "s" "",
484#else
485 "s" "stdin",
486#endif
351 "c" "", 487 "c" "",
352 "x" "xtrace", 488 "x" "xtrace",
353 "v" "verbose", 489 "v" "verbose",
@@ -364,6 +500,18 @@ static const char *const optletters_optnames[] ALIGN_PTR = {
364 ,"\0" "nolog" 500 ,"\0" "nolog"
365 ,"\0" "debug" 501 ,"\0" "debug"
366#endif 502#endif
503#if ENABLE_PLATFORM_MINGW32
504 ,"X" "winxp"
505#endif
506#if ENABLE_ASH_NOCONSOLE
507 ,"\0" "noconsole"
508 ,"\0" "noiconify"
509#endif
510#if ENABLE_ASH_GLOB_OPTIONS
511 ,"\0" "nocaseglob"
512 ,"\0" "nohiddenglob"
513 ,"\0" "nohidsysglob"
514#endif
367}; 515};
368//bash 4.4.23 also has these opts (with these defaults): 516//bash 4.4.23 also has these opts (with these defaults):
369//braceexpand on 517//braceexpand on
@@ -406,21 +554,36 @@ struct jmploc {
406struct globals_misc { 554struct globals_misc {
407 uint8_t exitstatus; /* exit status of last command */ 555 uint8_t exitstatus; /* exit status of last command */
408 uint8_t back_exitstatus;/* exit status of backquoted command */ 556 uint8_t back_exitstatus;/* exit status of backquoted command */
557#if !ENABLE_PLATFORM_MINGW32
409 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */ 558 smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
559#endif
410 smallint inps4; /* Prevent PS4 nesting. */ 560 smallint inps4; /* Prevent PS4 nesting. */
411 int savestatus; /* exit status of last command outside traps */ 561 int savestatus; /* exit status of last command outside traps */
412 int rootpid; /* pid of main shell */ 562 int rootpid; /* pid of main shell */
413 /* shell level: 0 for the main shell, 1 for its children, and so on */ 563 /* shell level: 0 for the main shell, 1 for its children, and so on */
414 int shlvl; 564 int shlvl;
565#if ENABLE_PLATFORM_MINGW32
566 int loopnest; /* current loop nesting level */
567#endif
415#define rootshell (!shlvl) 568#define rootshell (!shlvl)
416 int errlinno; 569 int errlinno;
417 570
418 char *minusc; /* argument to -c option */ 571 char *minusc; /* argument to -c option */
572#if ENABLE_PLATFORM_MINGW32
573 char *dirarg; /* argument to -d option */
574 char *title; /* argument to -t option */
575#if ENABLE_SUW32
576 int delayexit; /* set by -N option */
577# endif
578#endif
419 579
420 char *curdir; // = nullstr; /* current working directory */ 580 char *curdir; // = nullstr; /* current working directory */
421 char *physdir; // = nullstr; /* physical working directory */ 581 char *physdir; // = nullstr; /* physical working directory */
422 582
423 char *arg0; /* value of $0 */ 583 char *arg0; /* value of $0 */
584#if ENABLE_PLATFORM_MINGW32
585 char *commandname;
586#endif
424 587
425 struct jmploc *exception_handler; 588 struct jmploc *exception_handler;
426 589
@@ -431,8 +594,10 @@ struct globals_misc {
431 * but we do read it async. 594 * but we do read it async.
432 */ 595 */
433 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */ 596 volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
597#if !ENABLE_PLATFORM_MINGW32
434 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */ 598 volatile /*sig_atomic_t*/ smallint got_sigchld; /* 1 = got SIGCHLD */
435 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */ 599 volatile /*sig_atomic_t*/ smallint pending_sig; /* last pending signal */
600#endif
436 smallint exception_type; /* kind of exception: */ 601 smallint exception_type; /* kind of exception: */
437#define EXINT 0 /* SIGINT received */ 602#define EXINT 0 /* SIGINT received */
438#define EXERROR 1 /* a generic error */ 603#define EXERROR 1 /* a generic error */
@@ -467,8 +632,21 @@ struct globals_misc {
467# define nolog optlist[16 + BASH_PIPEFAIL] 632# define nolog optlist[16 + BASH_PIPEFAIL]
468# define debug optlist[17 + BASH_PIPEFAIL] 633# define debug optlist[17 + BASH_PIPEFAIL]
469#endif 634#endif
635#if ENABLE_PLATFORM_MINGW32
636# define winxp optlist[16 + BASH_PIPEFAIL + 2*(DEBUG != 0)]
637# if ENABLE_ASH_NOCONSOLE
638# define noconsole optlist[17 + BASH_PIPEFAIL + 2*(DEBUG != 0)]
639# define noiconify optlist[18 + BASH_PIPEFAIL + 2*(DEBUG != 0)]
640# endif
641# if ENABLE_ASH_GLOB_OPTIONS
642# define nocaseglob optlist[17 + BASH_PIPEFAIL + 2*(DEBUG != 0) + 2*ENABLE_ASH_NOCONSOLE]
643# define nohiddenglob optlist[18 + BASH_PIPEFAIL + 2*(DEBUG != 0) + 2*ENABLE_ASH_NOCONSOLE]
644# define nohidsysglob optlist[19 + BASH_PIPEFAIL + 2*(DEBUG != 0) + 2*ENABLE_ASH_NOCONSOLE]
645# endif
646#endif
470 647
471 /* trap handler commands */ 648 /* trap handler commands */
649#if !ENABLE_PLATFORM_MINGW32
472 /* 650 /*
473 * Sigmode records the current value of the signal handlers for the various 651 * Sigmode records the current value of the signal handlers for the various
474 * modes. A value of zero means that the current handler is not known. 652 * modes. A value of zero means that the current handler is not known.
@@ -482,6 +660,7 @@ struct globals_misc {
482 660
483 /* indicates specified signal received */ 661 /* indicates specified signal received */
484 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */ 662 uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
663#endif
485 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */ 664 uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
486 char *trap[NSIG + 1]; 665 char *trap[NSIG + 1];
487/* trap[0] is EXIT trap, trap[NTRAP_ERR] is ERR trap, other trap[i] are signal traps */ 666/* trap[0] is EXIT trap, trap[NTRAP_ERR] is ERR trap, other trap[i] are signal traps */
@@ -510,10 +689,21 @@ extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
510#define rootpid (G_misc.rootpid ) 689#define rootpid (G_misc.rootpid )
511#define shlvl (G_misc.shlvl ) 690#define shlvl (G_misc.shlvl )
512#define errlinno (G_misc.errlinno ) 691#define errlinno (G_misc.errlinno )
692#if ENABLE_PLATFORM_MINGW32
693#define loopnest (G_misc.loopnest )
694#endif
513#define minusc (G_misc.minusc ) 695#define minusc (G_misc.minusc )
696#if ENABLE_PLATFORM_MINGW32
697#define dirarg (G_misc.dirarg )
698#define title (G_misc.title )
699#define delayexit (G_misc.delayexit )
700#endif
514#define curdir (G_misc.curdir ) 701#define curdir (G_misc.curdir )
515#define physdir (G_misc.physdir ) 702#define physdir (G_misc.physdir )
516#define arg0 (G_misc.arg0 ) 703#define arg0 (G_misc.arg0 )
704#if ENABLE_PLATFORM_MINGW32
705#define commandname (G_misc.commandname)
706#endif
517#define exception_handler (G_misc.exception_handler) 707#define exception_handler (G_misc.exception_handler)
518#define exception_type (G_misc.exception_type ) 708#define exception_type (G_misc.exception_type )
519#define suppress_int (G_misc.suppress_int ) 709#define suppress_int (G_misc.suppress_int )
@@ -530,6 +720,13 @@ extern struct globals_misc *BB_GLOBAL_CONST ash_ptr_to_globals_misc;
530#define groupinfo (G_misc.groupinfo ) 720#define groupinfo (G_misc.groupinfo )
531#define random_gen (G_misc.random_gen ) 721#define random_gen (G_misc.random_gen )
532#define backgndpid (G_misc.backgndpid ) 722#define backgndpid (G_misc.backgndpid )
723
724#if ENABLE_PLATFORM_MINGW32
725#undef got_sigchld
726#undef pending_sig
727#define pending_sig (0)
728#endif
729
533#define INIT_G_misc() do { \ 730#define INIT_G_misc() do { \
534 XZALLOC_CONST_PTR(&ash_ptr_to_globals_misc, sizeof(G_misc)); \ 731 XZALLOC_CONST_PTR(&ash_ptr_to_globals_misc, sizeof(G_misc)); \
535 savestatus = -1; \ 732 savestatus = -1; \
@@ -547,6 +744,9 @@ static void trace_printf(const char *fmt, ...);
547static void trace_vprintf(const char *fmt, va_list va); 744static void trace_vprintf(const char *fmt, va_list va);
548# define TRACE(param) trace_printf param 745# define TRACE(param) trace_printf param
549# define TRACEV(param) trace_vprintf param 746# define TRACEV(param) trace_vprintf param
747# if ENABLE_PLATFORM_MINGW32 && defined(close)
748# undef close
749# endif
550# define close(fd) do { \ 750# define close(fd) do { \
551 int dfd = (fd); \ 751 int dfd = (fd); \
552 if (close(dfd) < 0) \ 752 if (close(dfd) < 0) \
@@ -635,11 +835,18 @@ struct parsefile {
635 835
636 /* Number of outstanding calls to pungetc. */ 836 /* Number of outstanding calls to pungetc. */
637 int unget; 837 int unget;
838
839#if ENABLE_PLATFORM_MINGW32
840 /* True if a trailing CR from a previous read was left unprocessed. */
841 int cr;
842#endif
638}; 843};
639 844
640static struct parsefile basepf; /* top level input file */ 845static struct parsefile basepf; /* top level input file */
641static struct parsefile *g_parsefile = &basepf; /* current input file */ 846static struct parsefile *g_parsefile = &basepf; /* current input file */
847#if ENABLE_PLATFORM_POSIX
642static char *commandname; /* currently executing command */ 848static char *commandname; /* currently executing command */
849#endif
643 850
644 851
645/* ============ Interrupts / exceptions */ 852/* ============ Interrupts / exceptions */
@@ -696,21 +903,40 @@ raise_exception(int e)
696 * are held using the INT_OFF macro. (The test for iflag is just 903 * are held using the INT_OFF macro. (The test for iflag is just
697 * defensive programming.) 904 * defensive programming.)
698 */ 905 */
699static void raise_interrupt(void) NORETURN; 906static void raise_interrupt(void) IF_NOT_PLATFORM_MINGW32(NORETURN);
700static void 907static void
701raise_interrupt(void) 908raise_interrupt(void)
702{ 909{
910#if ENABLE_PLATFORM_MINGW32
911 /* Contrary to the comment above on Windows raise_interrupt() is
912 * called when SIGINT is trapped or ignored. We detect this here
913 * and return without doing anything. */
914 if (trap[SIGINT])
915 return;
916#endif
703 pending_int = 0; 917 pending_int = 0;
918#if !ENABLE_PLATFORM_MINGW32
704 /* Signal is not automatically unmasked after it is raised, 919 /* Signal is not automatically unmasked after it is raised,
705 * do it ourself - unmask all signals */ 920 * do it ourself - unmask all signals */
706 sigprocmask_allsigs(SIG_UNBLOCK); 921 sigprocmask_allsigs(SIG_UNBLOCK);
922#endif
707 /* pending_sig = 0; - now done in signal_handler() */ 923 /* pending_sig = 0; - now done in signal_handler() */
708 924
709 if (!(rootshell && iflag)) { 925 if (!(rootshell && iflag)) {
926#if !ENABLE_PLATFORM_MINGW32
710 /* Kill ourself with SIGINT */ 927 /* Kill ourself with SIGINT */
711 signal(SIGINT, SIG_DFL); 928 signal(SIGINT, SIG_DFL);
712 raise(SIGINT); 929 raise(SIGINT);
930#else
931 fflush_all();
932 kill(-getpid(), SIGINT);
933 _exit(SIGINT << 24);
934#endif
713 } 935 }
936#if ENABLE_PLATFORM_MINGW32
937 if (iflag)
938 write(STDOUT_FILENO, "^C", 2);
939#endif
714 /* bash: ^C even on empty command line sets $? */ 940 /* bash: ^C even on empty command line sets $? */
715 exitstatus = SIGINT + 128; 941 exitstatus = SIGINT + 128;
716 raise_exception(EXINT); 942 raise_exception(EXINT);
@@ -1998,6 +2224,18 @@ maybe_single_quote(const char *s)
1998 return single_quote(s); 2224 return single_quote(s);
1999} 2225}
2000 2226
2227#if ENABLE_PLATFORM_MINGW32
2228/* Copy path to a string on the stack long enough to allow a file extension
2229 * to be added. */
2230static char *
2231stack_add_ext_space(const char *path)
2232{
2233 char *p = growstackto(strlen(path) + 5);
2234 strcpy(p, path);
2235 return p;
2236}
2237#endif
2238
2001 2239
2002/* ============ nextopt */ 2240/* ============ nextopt */
2003 2241
@@ -2120,6 +2358,9 @@ struct localvar {
2120#else 2358#else
2121# define VDYNAMIC 0 2359# define VDYNAMIC 0
2122#endif 2360#endif
2361#if ENABLE_PLATFORM_MINGW32
2362# define VIMPORT 0x400 /* variable was imported from environment */
2363#endif
2123 2364
2124 2365
2125/* Need to be before varinit_data[] */ 2366/* Need to be before varinit_data[] */
@@ -2149,6 +2390,24 @@ static void change_seconds(const char *) FAST_FUNC;
2149static void change_realtime(const char *) FAST_FUNC; 2390static void change_realtime(const char *) FAST_FUNC;
2150#endif 2391#endif
2151 2392
2393#if ENABLE_PLATFORM_MINGW32
2394static void FAST_FUNC
2395change_terminal_mode(const char *newval UNUSED_PARAM)
2396{
2397 terminal_mode(TRUE);
2398}
2399
2400static void clearcmdentry(void);
2401static void FAST_FUNC
2402change_override_applets(const char *newval UNUSED_PARAM)
2403{
2404 clearcmdentry();
2405}
2406
2407# define LINENO_INDEX (5 + 2 * ENABLE_ASH_MAIL + ENABLE_ASH_GETOPTS)
2408# define FUNCNAME_INDEX (LINENO_INDEX + 1)
2409#endif
2410
2152static const struct { 2411static const struct {
2153 int flags; 2412 int flags;
2154 const char *var_text; 2413 const char *var_text;
@@ -2186,6 +2445,12 @@ static const struct {
2186#if ENABLE_FEATURE_EDITING_SAVEHISTORY 2445#if ENABLE_FEATURE_EDITING_SAVEHISTORY
2187 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL }, 2446 { VSTRFIXED|VTEXTFIXED|VUNSET, "HISTFILE" , NULL },
2188#endif 2447#endif
2448#if ENABLE_PLATFORM_MINGW32
2449 { VSTRFIXED|VTEXTFIXED|VUNSET, BB_SKIP_ANSI_EMULATION, change_terminal_mode },
2450 { VSTRFIXED|VTEXTFIXED|VUNSET, BB_TERMINAL_MODE, change_terminal_mode },
2451 { VSTRFIXED|VTEXTFIXED|VUNSET, BB_OVERRIDE_APPLETS, change_override_applets },
2452 { VSTRFIXED|VTEXTFIXED|VUNSET, BB_CRITICAL_ERROR_DIALOGS, change_critical_error_dialogs },
2453#endif
2189}; 2454};
2190 2455
2191struct redirtab; 2456struct redirtab;
@@ -2409,6 +2674,65 @@ bltinlookup(const char *name)
2409 return lookupvar(name); 2674 return lookupvar(name);
2410} 2675}
2411 2676
2677#if ENABLE_PLATFORM_MINGW32
2678static char *
2679fix_pathvar(const char *path, int len)
2680{
2681 char *newpath = xstrdup(path);
2682 char *p;
2683 int modified = FALSE;
2684
2685 p = newpath + len;
2686 while (*p) {
2687 if (*p != ':' && *p != ';') {
2688 /* skip drive */
2689 if (isalpha(*p) && p[1] == ':')
2690 p += 2;
2691 /* skip through path component */
2692 for (; *p != '\0' && *p != ':' && *p != ';'; ++p)
2693 continue;
2694 }
2695 /* *p is ':', ';' or '\0' here */
2696 if (*p == ':') {
2697 *p++ = ';';
2698 modified = TRUE;
2699 }
2700 else if (*p == ';') {
2701 ++p;
2702 }
2703 }
2704
2705 if (!modified) {
2706 free(newpath);
2707 newpath = NULL;
2708 }
2709 return newpath;
2710}
2711
2712#define BB_VAR_EXACT 1 /* exact match for name */
2713#define BB_VAR_ASSIGN -1 /* matches name followed by '=' */
2714
2715/* Match variables that should be placed in the environment immediately
2716 * they're exported and removed immediately they're no longer exported */
2717static int
2718is_bb_var(const char *s)
2719{
2720 const char *p;
2721 int len;
2722
2723 for (p = bbvar; *p; p += len + 1) {
2724 len = strlen(p);
2725 if (strncmp(s, p, len) == 0) {
2726 if (s[len] == '\0')
2727 return BB_VAR_EXACT;
2728 else if (s[len] == '=')
2729 return BB_VAR_ASSIGN;
2730 }
2731 }
2732 return FALSE;
2733}
2734#endif
2735
2412/* 2736/*
2413 * Same as setvar except that the variable and value are passed in 2737 * Same as setvar except that the variable and value are passed in
2414 * the first argument as name=value. Since the first argument will 2738 * the first argument as name=value. Since the first argument will
@@ -2420,6 +2744,26 @@ static struct var *
2420setvareq(char *s, int flags) 2744setvareq(char *s, int flags)
2421{ 2745{
2422 struct var *vp, **vpp; 2746 struct var *vp, **vpp;
2747#if ENABLE_PLATFORM_MINGW32
2748 const char *paths = "PATH=\0""CDPATH=\0""MANPATH=\0";
2749 const char *p;
2750 int len;
2751
2752 for (p = paths; *p; p += len + 1) {
2753 len = strlen(p);
2754 if (strncmp(s, p, len) == 0) {
2755 char *newpath = fix_pathvar(s, len);
2756 if (newpath) {
2757 if ((flags & (VTEXTFIXED|VSTACK|VNOSAVE)) == VNOSAVE)
2758 free(s);
2759 flags |= VNOSAVE;
2760 flags &= ~(VTEXTFIXED|VSTACK);
2761 s = newpath;
2762 }
2763 break;
2764 }
2765 }
2766#endif
2423 2767
2424 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1)); 2768 flags |= (VEXPORT & (((unsigned) (1 - aflag)) - 1));
2425 vpp = findvar(s); 2769 vpp = findvar(s);
@@ -2444,6 +2788,11 @@ setvareq(char *s, int flags)
2444 if (!(vp->flags & (VTEXTFIXED|VSTACK))) 2788 if (!(vp->flags & (VTEXTFIXED|VSTACK)))
2445 free((char*)vp->var_text); 2789 free((char*)vp->var_text);
2446 2790
2791#if ENABLE_PLATFORM_MINGW32
2792 if ((flags & VUNSET) && (vp->flags & VEXPORT) &&
2793 is_bb_var(s) == BB_VAR_EXACT)
2794 unsetenv(s);
2795#endif
2447 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) { 2796 if (((flags & (VEXPORT|VREADONLY|VSTRFIXED|VUNSET)) | (vp->flags & VSTRFIXED)) == VUNSET) {
2448 *vpp = vp->next; 2797 *vpp = vp->next;
2449 free(vp); 2798 free(vp);
@@ -2473,6 +2822,10 @@ setvareq(char *s, int flags)
2473 s = ckstrdup(s); 2822 s = ckstrdup(s);
2474 vp->var_text = s; 2823 vp->var_text = s;
2475 vp->flags = flags; 2824 vp->flags = flags;
2825#if ENABLE_PLATFORM_MINGW32
2826 if ((flags & VEXPORT) && is_bb_var(s) == BB_VAR_ASSIGN)
2827 putenv(s);
2828#endif
2476 2829
2477 out: 2830 out:
2478 return vp; 2831 return vp;
@@ -2594,6 +2947,65 @@ listvars(int on, int off, struct strlist *lp, char ***end)
2594 return grabstackstr(ep); 2947 return grabstackstr(ep);
2595} 2948}
2596 2949
2950#if ENABLE_PLATFORM_MINGW32
2951/* Adjust directory separator in variables imported from the environment */
2952static void
2953setwinxp(int on)
2954{
2955 static smallint is_winxp = 1;
2956 struct var **vpp;
2957 struct var *vp;
2958
2959 if (on == is_winxp)
2960 return;
2961 is_winxp = on;
2962
2963 for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) {
2964 for (vp = *vpp; vp; vp = vp->next) {
2965 if ((vp->flags & VIMPORT)) {
2966 char *end = strchr(vp->var_text, '=');
2967 if (!end || is_prefixed_with(vp->var_text, "COMSPEC=") ||
2968 is_prefixed_with(vp->var_text, "SYSTEMROOT="))
2969 continue;
2970 if (!on)
2971 bs_to_slash(end + 1);
2972 else
2973 slash_to_bs(end + 1);
2974 }
2975 }
2976 }
2977}
2978
2979# if ENABLE_ASH_NOCONSOLE
2980/*
2981 * Console state is either:
2982 * 0 normal
2983 * 1 iconified/hidden
2984 * 2 unknown
2985 */
2986static int console_state(void)
2987{
2988 DECLARE_PROC_ADDR(BOOL, ShowWindow, HWND, int);
2989
2990 if (INIT_PROC_ADDR(user32.dll, ShowWindow)) {
2991 BOOL visible = IsWindowVisible(GetConsoleWindow());
2992 BOOL iconified = IsIconic(GetConsoleWindow());
2993
2994 return !visible || iconified;
2995 }
2996 return 2;
2997}
2998
2999static void hide_console(int hide)
3000{
3001 // Switch console state if it's known and isn't the required state
3002 if (console_state() == !hide)
3003 ShowWindow(GetConsoleWindow(), hide ?
3004 (noiconify ? SW_HIDE : SW_MINIMIZE) : SW_NORMAL);
3005}
3006# endif
3007#endif
3008
2597 3009
2598/* ============ Path search helper */ 3010/* ============ Path search helper */
2599static const char * 3011static const char *
@@ -2637,7 +3049,7 @@ static const char *pathopt; /* set by padvance */
2637static int 3049static int
2638padvance_magic(const char **path, const char *name, int magic) 3050padvance_magic(const char **path, const char *name, int magic)
2639{ 3051{
2640 const char *term = "%:"; 3052 const char *term = "%"PATH_SEP_STR;
2641 const char *lpathopt; 3053 const char *lpathopt;
2642 const char *p; 3054 const char *p;
2643 char *q; 3055 char *q;
@@ -2654,14 +3066,14 @@ padvance_magic(const char **path, const char *name, int magic)
2654 if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) { 3066 if (*start == '%' && (p = legal_pathopt(start + 1, term, magic))) {
2655 lpathopt = start + 1; 3067 lpathopt = start + 1;
2656 start = p; 3068 start = p;
2657 term = ":"; 3069 term = PATH_SEP_STR;
2658 } 3070 }
2659 3071
2660 len = strcspn(start, term); 3072 len = strcspn(start, term);
2661 p = start + len; 3073 p = start + len;
2662 3074
2663 if (*p == '%') { 3075 if (*p == '%') {
2664 size_t extra = strchrnul(p, ':') - p; 3076 size_t extra = strchrnul(p, PATH_SEP) - p;
2665 3077
2666 if (legal_pathopt(p + 1, term, magic)) 3078 if (legal_pathopt(p + 1, term, magic))
2667 lpathopt = p + 1; 3079 lpathopt = p + 1;
@@ -2672,14 +3084,18 @@ padvance_magic(const char **path, const char *name, int magic)
2672 } 3084 }
2673 3085
2674 pathopt = lpathopt; 3086 pathopt = lpathopt;
2675 *path = *p == ':' ? p + 1 : NULL; 3087 *path = *p == PATH_SEP ? p + 1 : NULL;
2676 3088
2677 /* "2" is for '/' and '\0' */ 3089 /* "2" is for '/' and '\0' */
2678 qlen = len + strlen(name) + 2; 3090 /* reserve space for suffix on WIN32 */
3091 qlen = len + strlen(name) + 2 IF_PLATFORM_MINGW32(+ 4);
2679 q = growstackto(qlen); 3092 q = growstackto(qlen);
2680 3093
2681 if (len) { 3094 if (len) {
2682 q = mempcpy(q, start, len); 3095 q = mempcpy(q, start, len);
3096#if ENABLE_PLATFORM_MINGW32
3097 if (q[-1] != '/' && q[-1] != '\\')
3098#endif
2683 *q++ = '/'; 3099 *q++ = '/';
2684 } 3100 }
2685 strcpy(q, name); 3101 strcpy(q, name);
@@ -2770,6 +3186,7 @@ setprompt_if(smallint do_set, int whichprompt)
2770 3186
2771#define CD_PHYSICAL 1 3187#define CD_PHYSICAL 1
2772#define CD_PRINT 2 3188#define CD_PRINT 2
3189#define CD_PRINT_ALL 4
2773 3190
2774static int 3191static int
2775cdopt(void) 3192cdopt(void)
@@ -2778,7 +3195,14 @@ cdopt(void)
2778 int i, j; 3195 int i, j;
2779 3196
2780 j = 'L'; 3197 j = 'L';
3198#if ENABLE_PLATFORM_MINGW32
3199 while ((i = nextopt("LPa")) != '\0') {
3200 if (i == 'a')
3201 flags |= CD_PRINT_ALL;
3202 else
3203#else
2781 while ((i = nextopt("LP")) != '\0') { 3204 while ((i = nextopt("LP")) != '\0') {
3205#endif
2782 if (i != j) { 3206 if (i != j) {
2783 flags ^= CD_PHYSICAL; 3207 flags ^= CD_PHYSICAL;
2784 j = i; 3208 j = i;
@@ -2795,6 +3219,130 @@ cdopt(void)
2795static const char * 3219static const char *
2796updatepwd(const char *dir) 3220updatepwd(const char *dir)
2797{ 3221{
3222#if ENABLE_PLATFORM_MINGW32
3223 /*
3224 * Due to Windows drive notion, getting pwd is a completely
3225 * different thing. Handle it in a separate routine
3226 */
3227
3228 char *new;
3229 char *p;
3230 char *cdcomppath;
3231 const char *lim;
3232 int len;
3233 char buffer[PATH_MAX];
3234 /*
3235 * There are five cases that make some kind of sense
3236 *
3237 * Absolute paths:
3238 * c:/path
3239 * //host/share
3240 *
3241 * Relative to current working directory of other drive:
3242 * c:path
3243 *
3244 * Relative to current root (drive/share):
3245 * /path
3246 *
3247 * Relative to current working directory of current root (drive/share):
3248 * path
3249 */
3250 enum {ABS_DRIVE, ABS_SHARE, REL_OTHER, REL_ROOT, REL_CWD} target;
3251
3252 /* skip multiple leading separators unless dir is a UNC path */
3253 if (is_dir_sep(*dir) && unc_root_len(dir) == 0) {
3254 while (is_dir_sep(dir[1]))
3255 ++dir;
3256 }
3257
3258 len = strlen(dir);
3259 if (len >= 2 && has_dos_drive_prefix(dir))
3260 target = len >= 3 && is_dir_sep(dir[2]) ? ABS_DRIVE : REL_OTHER;
3261 else if (unc_root_len(dir) != 0)
3262 target = ABS_SHARE;
3263 else if (is_dir_sep(*dir))
3264 target = REL_ROOT;
3265 else
3266 target = REL_CWD;
3267
3268 cdcomppath = sstrdup(dir);
3269 STARTSTACKSTR(new);
3270
3271 switch (target) {
3272 case REL_OTHER:
3273 /* c:path */
3274 if (get_drive_cwd(dir, buffer, PATH_MAX) == NULL)
3275 return 0;
3276 new = stack_putstr(buffer, new);
3277 len = 2;
3278 cdcomppath += len;
3279 dir += len;
3280 break;
3281 case REL_CWD:
3282 case REL_ROOT:
3283 /* path or /path */
3284 len = root_len(curdir);
3285 if (len == 0)
3286 return 0;
3287 new = target == REL_CWD ? stack_putstr(curdir, new) :
3288 stnputs(curdir, len, new);
3289 break;
3290 default:
3291 /* //host/share or c:/path */
3292 len = root_len(dir);
3293 if (len == 0)
3294 return 0;
3295 new = stnputs(dir, len, new);
3296 cdcomppath += len;
3297 dir += len;
3298 break;
3299 }
3300
3301 new = makestrspace(strlen(dir) + 2, new);
3302 lim = (char *)stackblock() + len + 1;
3303
3304 if (!is_dir_sep(*dir)) {
3305 if (!is_dir_sep(new[-1]))
3306 USTPUTC('/', new);
3307 if (new > lim && is_dir_sep(*lim))
3308 lim++;
3309 } else {
3310 USTPUTC('/', new);
3311 cdcomppath++;
3312 if (is_dir_sep(dir[1]) && !is_dir_sep(dir[2])) {
3313 USTPUTC('/', new);
3314 cdcomppath++;
3315 lim++;
3316 }
3317 }
3318 p = strtok(cdcomppath, "/\\");
3319 while (p) {
3320 switch (*p) {
3321 case '.':
3322 if (p[1] == '.' && p[2] == '\0') {
3323 while (new > lim) {
3324 STUNPUTC(new);
3325 if (is_dir_sep(new[-1]))
3326 break;
3327 }
3328 break;
3329 }
3330 if (p[1] == '\0')
3331 break;
3332 /* fall through */
3333 default:
3334 new = stack_putstr(p, new);
3335 USTPUTC('/', new);
3336 }
3337 p = strtok(NULL, "/\\");
3338 }
3339 if (new > lim)
3340 STUNPUTC(new);
3341 *new = 0;
3342 strip_dot_space((char *)stackblock());
3343 fix_path_case((char *)stackblock());
3344 return bs_to_slash((char *)stackblock());
3345#else
2798 char *new; 3346 char *new;
2799 char *p; 3347 char *p;
2800 char *cdcomppath; 3348 char *cdcomppath;
@@ -2848,6 +3396,7 @@ updatepwd(const char *dir)
2848 STUNPUTC(new); 3396 STUNPUTC(new);
2849 *new = 0; 3397 *new = 0;
2850 return stackblock(); 3398 return stackblock();
3399#endif
2851} 3400}
2852 3401
2853/* 3402/*
@@ -2943,7 +3492,7 @@ cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2943 } 3492 }
2944 if (!dest) 3493 if (!dest)
2945 dest = nullstr; 3494 dest = nullstr;
2946 if (*dest == '/') 3495 if (!is_relative_path(dest))
2947 goto step6; 3496 goto step6;
2948 if (*dest == '.') { 3497 if (*dest == '.') {
2949 c = dest[1]; 3498 c = dest[1];
@@ -2966,7 +3515,7 @@ cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2966 p = stalloc(len); 3515 p = stalloc(len);
2967 3516
2968 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) { 3517 if (stat(p, &statb) >= 0 && S_ISDIR(statb.st_mode)) {
2969 if (c && c != ':') 3518 if (c && c != PATH_SEP)
2970 flags |= CD_PRINT; 3519 flags |= CD_PRINT;
2971 docd: 3520 docd:
2972 if (!docd(p, flags)) 3521 if (!docd(p, flags))
@@ -2988,6 +3537,26 @@ cdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2988 return 0; 3537 return 0;
2989} 3538}
2990 3539
3540#if ENABLE_PLATFORM_MINGW32
3541static void
3542print_all_cwd(void)
3543{
3544 FILE *mnt;
3545 struct mntent *entry;
3546 char buffer[PATH_MAX];
3547
3548 mnt = setmntent(bb_path_mtab_file, "r");
3549 if (mnt) {
3550 while ((entry=getmntent(mnt)) != NULL) {
3551 entry->mnt_dir[2] = '\0';
3552 if (get_drive_cwd(entry->mnt_dir, buffer, PATH_MAX) != NULL)
3553 out1fmt("%s\n", buffer);
3554 }
3555 endmntent(mnt);
3556 }
3557}
3558#endif
3559
2991static int FAST_FUNC 3560static int FAST_FUNC
2992pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM) 3561pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2993{ 3562{
@@ -2995,6 +3564,12 @@ pwdcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
2995 const char *dir = curdir; 3564 const char *dir = curdir;
2996 3565
2997 flags = cdopt(); 3566 flags = cdopt();
3567#if ENABLE_PLATFORM_MINGW32
3568 if (flags & CD_PRINT_ALL) {
3569 print_all_cwd();
3570 return 0;
3571 }
3572#endif
2998 if (flags) { 3573 if (flags) {
2999 if (physdir == nullstr) 3574 if (physdir == nullstr)
3000 setpwd(dir, 0); 3575 setpwd(dir, 0);
@@ -3623,7 +4198,12 @@ unaliascmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
3623struct procstat { 4198struct procstat {
3624 pid_t ps_pid; /* process id */ 4199 pid_t ps_pid; /* process id */
3625 int ps_status; /* last process status from wait() */ 4200 int ps_status; /* last process status from wait() */
4201#if ENABLE_PLATFORM_POSIX || JOBS_WIN32
3626 char *ps_cmd; /* text of command being run */ 4202 char *ps_cmd; /* text of command being run */
4203#endif
4204#if ENABLE_PLATFORM_MINGW32
4205 HANDLE ps_proc;
4206#endif
3627}; 4207};
3628 4208
3629struct job { 4209struct job {
@@ -3639,8 +4219,10 @@ struct job {
3639#define JOBDONE 2 /* all procs are completed */ 4219#define JOBDONE 2 /* all procs are completed */
3640 unsigned 4220 unsigned
3641 state: 8, 4221 state: 8,
3642#if JOBS 4222#if JOBS || ENABLE_PLATFORM_MINGW32
3643 sigint: 1, /* job was killed by SIGINT */ 4223 sigint: 1, /* job was killed by SIGINT */
4224#endif
4225#if JOBS
3644 jobctl: 1, /* job running under job control */ 4226 jobctl: 1, /* job running under job control */
3645#endif 4227#endif
3646 waited: 1, /* true if this entry has been waited for */ 4228 waited: 1, /* true if this entry has been waited for */
@@ -3650,17 +4232,23 @@ struct job {
3650}; 4232};
3651 4233
3652static struct job *makejob(/*union node *,*/ int); 4234static struct job *makejob(/*union node *,*/ int);
4235#if !ENABLE_PLATFORM_MINGW32
3653static int forkshell(struct job *, union node *, int); 4236static int forkshell(struct job *, union node *, int);
4237#endif
3654static int waitforjob(struct job *); 4238static int waitforjob(struct job *);
3655 4239
3656#if !JOBS 4240#if !JOBS && !JOBS_WIN32
3657enum { doing_jobctl = 0 }; 4241enum { doing_jobctl = 0 };
3658#define setjobctl(on) do {} while (0) 4242#define setjobctl(on) do {} while (0)
3659#else 4243#elif JOBS_WIN32
4244static smallint doing_jobctl; //references:8
4245#define setjobctl(on) do { if (rootshell) doing_jobctl = on; } while (0)
4246#else /* JOBS */
3660static smallint doing_jobctl; //references:8 4247static smallint doing_jobctl; //references:8
3661static void setjobctl(int); 4248static void setjobctl(int);
3662#endif 4249#endif
3663 4250
4251#if !ENABLE_PLATFORM_MINGW32
3664/* 4252/*
3665 * Ignore a signal. 4253 * Ignore a signal.
3666 */ 4254 */
@@ -3687,7 +4275,7 @@ signal_handler(int signo)
3687 return; 4275 return;
3688 } 4276 }
3689#if ENABLE_FEATURE_EDITING 4277#if ENABLE_FEATURE_EDITING
3690 bb_got_signal = signo; /* for read_line_input: "we got a signal" */ 4278 bb_got_signal = signo; /* for read_line_input / read builtin: "we got a signal" */
3691#endif 4279#endif
3692 gotsig[signo - 1] = 1; 4280 gotsig[signo - 1] = 1;
3693 pending_sig = signo; 4281 pending_sig = signo;
@@ -3809,6 +4397,10 @@ setsignal(int signo)
3809 4397
3810 sigaction_set(signo, &act); 4398 sigaction_set(signo, &act);
3811} 4399}
4400#else
4401#define setsignal(s)
4402#define ignoresig(s)
4403#endif
3812 4404
3813/* mode flags for set_curjob */ 4405/* mode flags for set_curjob */
3814#define CUR_DELETE 2 4406#define CUR_DELETE 2
@@ -3942,7 +4534,7 @@ set_curjob(struct job *jp, unsigned mode)
3942 } 4534 }
3943} 4535}
3944 4536
3945#if JOBS || DEBUG 4537#if JOBS || ENABLE_PLATFORM_MINGW32 || DEBUG
3946static int 4538static int
3947jobno(const struct job *jp) 4539jobno(const struct job *jp)
3948{ 4540{
@@ -3960,7 +4552,9 @@ static struct job *
3960getjob(const char *name, int getctl) 4552getjob(const char *name, int getctl)
3961{ 4553{
3962 struct job *jp; 4554 struct job *jp;
4555#if ENABLE_PLATFORM_POSIX || JOBS_WIN32
3963 struct job *found; 4556 struct job *found;
4557#endif
3964 const char *err_msg = "%s: no such job"; 4558 const char *err_msg = "%s: no such job";
3965 unsigned num; 4559 unsigned num;
3966 int c; 4560 int c;
@@ -4005,6 +4599,7 @@ getjob(const char *name, int getctl)
4005 } 4599 }
4006 } 4600 }
4007 4601
4602#if ENABLE_PLATFORM_POSIX || JOBS_WIN32
4008 found = NULL; 4603 found = NULL;
4009 while (jp) { 4604 while (jp) {
4010 if (*p == '?' 4605 if (*p == '?'
@@ -4021,6 +4616,9 @@ getjob(const char *name, int getctl)
4021 if (!found) 4616 if (!found)
4022 goto err; 4617 goto err;
4023 jp = found; 4618 jp = found;
4619#else
4620 goto err;
4621#endif
4024 4622
4025 gotit: 4623 gotit:
4026#if JOBS 4624#if JOBS
@@ -4039,14 +4637,18 @@ getjob(const char *name, int getctl)
4039static void 4637static void
4040freejob(struct job *jp) 4638freejob(struct job *jp)
4041{ 4639{
4640#if ENABLE_PLATFORM_POSIX || JOBS_WIN32
4042 struct procstat *ps; 4641 struct procstat *ps;
4043 int i; 4642 int i;
4643#endif
4044 4644
4045 INT_OFF; 4645 INT_OFF;
4646#if ENABLE_PLATFORM_POSIX || JOBS_WIN32
4046 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) { 4647 for (i = jp->nprocs, ps = jp->ps; --i >= 0; ps++) {
4047 if (ps->ps_cmd != nullstr) 4648 if (ps->ps_cmd != nullstr)
4048 free(ps->ps_cmd); 4649 free(ps->ps_cmd);
4049 } 4650 }
4651#endif
4050 if (jp->ps != &jp->ps0) 4652 if (jp->ps != &jp->ps0)
4051 free(jp->ps); 4653 free(jp->ps);
4052 jp->used = 0; 4654 jp->used = 0;
@@ -4139,7 +4741,9 @@ setjobctl(int on)
4139 ttyfd = fd; 4741 ttyfd = fd;
4140 doing_jobctl = on; 4742 doing_jobctl = on;
4141} 4743}
4744#endif
4142 4745
4746#if JOBS || JOBS_WIN32
4143static int FAST_FUNC 4747static int FAST_FUNC
4144killcmd(int argc, char **argv) 4748killcmd(int argc, char **argv)
4145{ 4749{
@@ -4169,8 +4773,10 @@ killcmd(int argc, char **argv)
4169 * sh -c 'true|sleep 1 & sleep 2; kill %1' 4773 * sh -c 'true|sleep 1 & sleep 2; kill %1'
4170 */ 4774 */
4171 n = jp->nprocs; /* can't be 0 (I hope) */ 4775 n = jp->nprocs; /* can't be 0 (I hope) */
4776#if !ENABLE_PLATFORM_MINGW32
4172 if (jp->jobctl) 4777 if (jp->jobctl)
4173 n = 1; 4778 n = 1;
4779#endif
4174 dst = alloca(n * sizeof(int)*4); 4780 dst = alloca(n * sizeof(int)*4);
4175 argv[i] = dst; 4781 argv[i] = dst;
4176 for (j = 0; j < n; j++) { 4782 for (j = 0; j < n; j++) {
@@ -4185,7 +4791,11 @@ killcmd(int argc, char **argv)
4185 * leading space. Needed to not confuse 4791 * leading space. Needed to not confuse
4186 * negative pids with "kill -SIGNAL_NO" syntax 4792 * negative pids with "kill -SIGNAL_NO" syntax
4187 */ 4793 */
4794#if !ENABLE_PLATFORM_MINGW32
4188 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid); 4795 dst += sprintf(dst, jp->jobctl ? " -%u" : " %u", (int)ps->ps_pid);
4796#else
4797 dst += sprintf(dst, " -%u", (int)ps->ps_pid);
4798#endif
4189 } 4799 }
4190 *dst = '\0'; 4800 *dst = '\0';
4191 } 4801 }
@@ -4193,7 +4803,9 @@ killcmd(int argc, char **argv)
4193 } 4803 }
4194 return kill_main(argc, argv); 4804 return kill_main(argc, argv);
4195} 4805}
4806#endif
4196 4807
4808#if JOBS
4197static void 4809static void
4198showpipe(struct job *jp /*, FILE *out*/) 4810showpipe(struct job *jp /*, FILE *out*/)
4199{ 4811{
@@ -4298,6 +4910,65 @@ sprint_status48(char *os, int status, int sigonly)
4298 return s - os; 4910 return s - os;
4299} 4911}
4300 4912
4913#if ENABLE_PLATFORM_MINGW32
4914static BOOL WINAPI ctrl_handler(DWORD dwCtrlType)
4915{
4916 if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT) {
4917# if ENABLE_FEATURE_EDITING
4918 bb_got_signal = SIGINT; /* for read_line_input: "we got a signal" */
4919# endif
4920 if (!suppress_int && !(rootshell && iflag))
4921 raise_interrupt();
4922 pending_int = 1;
4923 return TRUE;
4924 }
4925 return FALSE;
4926}
4927
4928/*
4929 * Windows does not know about parent-child relationship
4930 * They don't support waitpid(-1)
4931 */
4932static pid_t
4933waitpid_child(int *status, int wait_flags)
4934{
4935 struct job *jb;
4936 int pid_nr = 0;
4937 static HANDLE *proclist = NULL;
4938 static int pid_max = 0;
4939 pid_t pid = -1;
4940 DWORD win_status, idx;
4941 int i;
4942
4943 for (jb = curjob; jb; jb = jb->prev_job) {
4944 if (jb->state != JOBDONE) {
4945 if (pid_nr + jb->nprocs > pid_max) {
4946 pid_max = pid_nr + jb->nprocs;
4947 proclist = ckrealloc(proclist, sizeof(*proclist) * pid_max);
4948 }
4949
4950 for (i = 0; i < jb->nprocs; ++i) {
4951 if (jb->ps[i].ps_proc) {
4952 proclist[pid_nr++] = jb->ps[i].ps_proc;
4953 }
4954 }
4955 }
4956 }
4957
4958 if (pid_nr) {
4959 idx = WaitForMultipleObjects(pid_nr, proclist, FALSE,
4960 wait_flags & WNOHANG ? 0 : INFINITE);
4961 if (idx < pid_nr) {
4962 GetExitCodeProcess(proclist[idx], &win_status);
4963 *status = exit_code_to_wait_status(win_status);
4964 pid = GetProcessId(proclist[idx]);
4965 }
4966 }
4967 return pid;
4968}
4969#define waitpid(p, s, f) waitpid_child(s, f)
4970#endif
4971
4301#define DOWAIT_NONBLOCK 0 4972#define DOWAIT_NONBLOCK 0
4302#define DOWAIT_BLOCK 1 4973#define DOWAIT_BLOCK 1
4303#define DOWAIT_BLOCK_OR_SIG 2 4974#define DOWAIT_BLOCK_OR_SIG 2
@@ -4308,6 +4979,7 @@ sprint_status48(char *os, int status, int sigonly)
4308static int 4979static int
4309waitproc(int block, int *status) 4980waitproc(int block, int *status)
4310{ 4981{
4982#if !ENABLE_PLATFORM_MINGW32
4311 sigset_t oldmask; 4983 sigset_t oldmask;
4312 int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG; 4984 int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
4313 int err; 4985 int err;
@@ -4338,6 +5010,11 @@ waitproc(int block, int *status)
4338 } while (got_sigchld); 5010 } while (got_sigchld);
4339 5011
4340 return err; 5012 return err;
5013#else
5014 int flags = block == DOWAIT_BLOCK ? 0 : WNOHANG;
5015 *status = 0;
5016 return waitpid(-1, status, flags);
5017#endif
4341} 5018}
4342 5019
4343static int 5020static int
@@ -4394,6 +5071,10 @@ waitone(int block, struct job *job)
4394 jobno(jp), pid, ps->ps_status, status)); 5071 jobno(jp), pid, ps->ps_status, status));
4395 ps->ps_status = status; 5072 ps->ps_status = status;
4396 thisjob = jp; 5073 thisjob = jp;
5074#if ENABLE_PLATFORM_MINGW32
5075 CloseHandle(ps->ps_proc);
5076 ps->ps_proc = NULL;
5077#endif
4397 } 5078 }
4398 if (ps->ps_status == -1) 5079 if (ps->ps_status == -1)
4399 jobstate = JOBRUNNING; 5080 jobstate = JOBRUNNING;
@@ -4456,6 +5137,7 @@ waitone(int block, struct job *job)
4456static int 5137static int
4457dowait(int block, struct job *jp) 5138dowait(int block, struct job *jp)
4458{ 5139{
5140#if !ENABLE_PLATFORM_MINGW32
4459 smallint gotchld = *(volatile smallint *)&got_sigchld; 5141 smallint gotchld = *(volatile smallint *)&got_sigchld;
4460 int rpid; 5142 int rpid;
4461 int pid; 5143 int pid;
@@ -4477,9 +5159,17 @@ dowait(int block, struct job *jp)
4477 } while (pid >= 0); 5159 } while (pid >= 0);
4478 5160
4479 return rpid; 5161 return rpid;
5162#else
5163 int pid = 1;
5164
5165 while (jp ? jp->state == JOBRUNNING : pid > 0)
5166 pid = waitone(block, jp);
5167
5168 return pid;
5169#endif
4480} 5170}
4481 5171
4482#if JOBS 5172#if JOBS || JOBS_WIN32
4483static void 5173static void
4484showjob(struct job *jp, int mode) 5174showjob(struct job *jp, int mode)
4485{ 5175{
@@ -4494,7 +5184,7 @@ showjob(struct job *jp, int mode)
4494 5184
4495 if (mode & SHOW_ONLY_PGID) { /* jobs -p */ 5185 if (mode & SHOW_ONLY_PGID) { /* jobs -p */
4496 /* just output process (group) id of pipeline */ 5186 /* just output process (group) id of pipeline */
4497 fprintf(out, "%d\n", ps->ps_pid); 5187 fprintf(out, "%"PID_FMT"d\n", ps->ps_pid);
4498 return; 5188 return;
4499 } 5189 }
4500 5190
@@ -4507,7 +5197,7 @@ showjob(struct job *jp, int mode)
4507 s[col - 3] = '-'; 5197 s[col - 3] = '-';
4508 5198
4509 if (mode & SHOW_PIDS) 5199 if (mode & SHOW_PIDS)
4510 col += fmtstr(s + col, 16, "%d ", ps->ps_pid); 5200 col += fmtstr(s + col, 16, "%"PID_FMT"d ", ps->ps_pid);
4511 5201
4512 psend = ps + jp->nprocs; 5202 psend = ps + jp->nprocs;
4513 5203
@@ -4516,8 +5206,10 @@ showjob(struct job *jp, int mode)
4516 col += sizeof("Running") - 1; 5206 col += sizeof("Running") - 1;
4517 } else { 5207 } else {
4518 int status = psend[-1].ps_status; 5208 int status = psend[-1].ps_status;
5209#if !ENABLE_PLATFORM_MINGW32
4519 if (jp->state == JOBSTOPPED) 5210 if (jp->state == JOBSTOPPED)
4520 status = jp->stopstatus; 5211 status = jp->stopstatus;
5212#endif
4521 col += sprint_status48(s + col, status, 0); 5213 col += sprint_status48(s + col, status, 0);
4522 } 5214 }
4523 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */ 5215 /* By now, "[JOBID]* [maybe PID] STATUS" is printed */
@@ -4536,14 +5228,18 @@ showjob(struct job *jp, int mode)
4536 s[0] = '\0'; 5228 s[0] = '\0';
4537 col = 33; 5229 col = 33;
4538 if (mode & SHOW_PIDS) 5230 if (mode & SHOW_PIDS)
4539 col = fmtstr(s, 48, "\n%*c%d ", indent_col, ' ', ps->ps_pid) - 1; 5231 col = fmtstr(s, 48, "\n%*c%"PID_FMT"d ", indent_col, ' ', ps->ps_pid) - 1;
4540 start: 5232 start:
5233#if ENABLE_PLATFORM_POSIX || JOBS_WIN32
4541 fprintf(out, "%s%*c%s%s", 5234 fprintf(out, "%s%*c%s%s",
4542 s, 5235 s,
4543 33 - col >= 0 ? 33 - col : 0, ' ', 5236 33 - col >= 0 ? 33 - col : 0, ' ',
4544 ps == jp->ps ? "" : "| ", 5237 ps == jp->ps ? "" : "| ",
4545 ps->ps_cmd 5238 ps->ps_cmd
4546 ); 5239 );
5240#else
5241 fprintf(out, "%s", s);
5242#endif
4547 } while (++ps != psend); 5243 } while (++ps != psend);
4548 newline_and_flush(out); 5244 newline_and_flush(out);
4549 5245
@@ -4628,7 +5324,7 @@ getstatus(struct job *job)
4628 { 5324 {
4629 /* XXX: limits number of signals */ 5325 /* XXX: limits number of signals */
4630 retval = WTERMSIG(status); 5326 retval = WTERMSIG(status);
4631#if JOBS 5327#if JOBS || ENABLE_PLATFORM_MINGW32
4632 if (retval == SIGINT) 5328 if (retval == SIGINT)
4633 job->sigint = 1; 5329 job->sigint = 1;
4634#endif 5330#endif
@@ -4800,7 +5496,7 @@ makejob(/*union node *node,*/ int nprocs)
4800 break; 5496 break;
4801 if (jp->state != JOBDONE || !jp->waited) 5497 if (jp->state != JOBDONE || !jp->waited)
4802 continue; 5498 continue;
4803#if JOBS 5499#if JOBS || JOBS_WIN32
4804 if (doing_jobctl) 5500 if (doing_jobctl)
4805 continue; 5501 continue;
4806#endif 5502#endif
@@ -4826,7 +5522,7 @@ makejob(/*union node *node,*/ int nprocs)
4826 return jp; 5522 return jp;
4827} 5523}
4828 5524
4829#if JOBS 5525#if JOBS || JOBS_WIN32
4830/* 5526/*
4831 * Return a string identifying a command (to be printed by the 5527 * Return a string identifying a command (to be printed by the
4832 * jobs command). 5528 * jobs command).
@@ -5168,6 +5864,7 @@ clear_traps(void)
5168 INT_ON; 5864 INT_ON;
5169} 5865}
5170 5866
5867#if !ENABLE_PLATFORM_MINGW32
5171/* Lives far away from here, needed for forkchild */ 5868/* Lives far away from here, needed for forkchild */
5172static void closescript(void); 5869static void closescript(void);
5173 5870
@@ -5294,14 +5991,22 @@ forkchild(struct job *jp, union node *n, int mode)
5294 for (jp = curjob; jp; jp = jp->prev_job) 5991 for (jp = curjob; jp; jp = jp->prev_job)
5295 freejob(jp); 5992 freejob(jp);
5296} 5993}
5994#endif
5297 5995
5298/* Called after fork(), in parent */ 5996/* Called after fork(), in parent */
5299#if !JOBS 5997#if !JOBS && !JOBS_WIN32
5300#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid) 5998#define forkparent(jp, n, mode, pid) forkparent(jp, mode, pid)
5301#endif 5999#endif
5302static void 6000static void
6001#if !ENABLE_PLATFORM_MINGW32
5303forkparent(struct job *jp, union node *n, int mode, pid_t pid) 6002forkparent(struct job *jp, union node *n, int mode, pid_t pid)
6003#else
6004forkparent(struct job *jp, union node *n, int mode, HANDLE proc)
6005#endif
5304{ 6006{
6007#if ENABLE_PLATFORM_MINGW32
6008 pid_t pid = GetProcessId(proc);
6009#endif
5305 TRACE(("In parent shell: child = %d\n", pid)); 6010 TRACE(("In parent shell: child = %d\n", pid));
5306 if (!jp) /* jp is NULL when called by openhere() for heredoc support */ 6011 if (!jp) /* jp is NULL when called by openhere() for heredoc support */
5307 return; 6012 return;
@@ -5320,19 +6025,29 @@ forkparent(struct job *jp, union node *n, int mode, pid_t pid)
5320 if (mode == FORK_BG) { 6025 if (mode == FORK_BG) {
5321 backgndpid = pid; /* set $! */ 6026 backgndpid = pid; /* set $! */
5322 set_curjob(jp, CUR_RUNNING); 6027 set_curjob(jp, CUR_RUNNING);
6028#if ENABLE_PLATFORM_MINGW32
6029 if (iflag && jp && jp->nprocs == 0)
6030 fprintf(stderr, "[%d] %"PID_FMT"d\n", jobno(jp), pid);
6031#endif
5323 } 6032 }
5324 if (jp) { 6033 if (jp) {
5325 struct procstat *ps = &jp->ps[jp->nprocs++]; 6034 struct procstat *ps = &jp->ps[jp->nprocs++];
5326 ps->ps_pid = pid; 6035 ps->ps_pid = pid;
5327 ps->ps_status = -1; 6036 ps->ps_status = -1;
6037#if ENABLE_PLATFORM_POSIX || JOBS_WIN32
5328 ps->ps_cmd = nullstr; 6038 ps->ps_cmd = nullstr;
5329#if JOBS 6039#endif
6040#if ENABLE_PLATFORM_MINGW32
6041 ps->ps_proc = proc;
6042#endif
6043#if JOBS || JOBS_WIN32
5330 if (doing_jobctl && n) 6044 if (doing_jobctl && n)
5331 ps->ps_cmd = commandtext(n); 6045 ps->ps_cmd = commandtext(n);
5332#endif 6046#endif
5333 } 6047 }
5334} 6048}
5335 6049
6050#if !ENABLE_PLATFORM_MINGW32
5336/* jp and n are NULL when called by openhere() for heredoc support */ 6051/* jp and n are NULL when called by openhere() for heredoc support */
5337static int 6052static int
5338forkshell(struct job *jp, union node *n, int mode) 6053forkshell(struct job *jp, union node *n, int mode)
@@ -5355,6 +6070,7 @@ forkshell(struct job *jp, union node *n, int mode)
5355 } 6070 }
5356 return pid; 6071 return pid;
5357} 6072}
6073#endif
5358 6074
5359/* 6075/*
5360 * Wait for job to finish. 6076 * Wait for job to finish.
@@ -5418,6 +6134,10 @@ waitforjob(struct job *jp)
5418 return exitstatus; 6134 return exitstatus;
5419 6135
5420 st = getstatus(jp); 6136 st = getstatus(jp);
6137#if ENABLE_PLATFORM_MINGW32
6138 if (!jp->sigint && iflag && rootshell)
6139 pending_int = 0;
6140#endif
5421#if JOBS 6141#if JOBS
5422 if (jp->jobctl) { 6142 if (jp->jobctl) {
5423 xtcsetpgrp(ttyfd, rootpid); 6143 xtcsetpgrp(ttyfd, rootpid);
@@ -5443,6 +6163,7 @@ waitforjob(struct job *jp)
5443/* 6163/*
5444 * return 1 if there are stopped jobs, otherwise 0 6164 * return 1 if there are stopped jobs, otherwise 0
5445 */ 6165 */
6166#if !ENABLE_PLATFORM_MINGW32
5446static int 6167static int
5447stoppedjobs(void) 6168stoppedjobs(void)
5448{ 6169{
@@ -5461,6 +6182,17 @@ stoppedjobs(void)
5461 out: 6182 out:
5462 return retval; 6183 return retval;
5463} 6184}
6185#else
6186static int
6187stoppedjobs(void)
6188{
6189 if (iflag && curjob) {
6190 out2str("You have background jobs.\n");
6191 return 1;
6192 }
6193 return 0;
6194}
6195#endif
5464 6196
5465 6197
5466/* 6198/*
@@ -5485,6 +6217,7 @@ openhere(union node *redir)
5485 char *p; 6217 char *p;
5486 int pip[2]; 6218 int pip[2];
5487 size_t len = 0; 6219 size_t len = 0;
6220 IF_PLATFORM_MINGW32(struct forkshell fs);
5488 6221
5489 if (pipe(pip) < 0) 6222 if (pipe(pip) < 0)
5490 ash_msg_and_raise_perror("can't create pipe"); 6223 ash_msg_and_raise_perror("can't create pipe");
@@ -5501,6 +6234,14 @@ openhere(union node *redir)
5501 goto out; 6234 goto out;
5502 } 6235 }
5503 6236
6237#if ENABLE_PLATFORM_MINGW32
6238 memset(&fs, 0, sizeof(fs));
6239 fs.fpid = FS_OPENHERE;
6240 fs.fd[0] = pip[0];
6241 fs.fd[1] = pip[1];
6242 fs.path = p;
6243 spawn_forkshell(&fs, NULL, NULL, FORK_NOJOB);
6244#else
5504 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) { 6245 if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
5505 /* child */ 6246 /* child */
5506 close(pip[0]); 6247 close(pip[0]);
@@ -5512,6 +6253,7 @@ openhere(union node *redir)
5512 xwrite(pip[1], p, len); 6253 xwrite(pip[1], p, len);
5513 _exit_SUCCESS(); 6254 _exit_SUCCESS();
5514 } 6255 }
6256#endif
5515 out: 6257 out:
5516 close(pip[1]); 6258 close(pip[1]);
5517 return pip[0]; 6259 return pip[0];
@@ -5589,6 +6331,9 @@ openredirect(union node *redir)
5589 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666); 6331 f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666);
5590 if (f < 0) 6332 if (f < 0)
5591 goto ecreate; 6333 goto ecreate;
6334#if ENABLE_PLATFORM_MINGW32
6335 lseek(f, 0, SEEK_END);
6336#endif
5592 break; 6337 break;
5593 } 6338 }
5594 6339
@@ -5799,6 +6544,12 @@ save_fd_on_redirect(int fd, int avoid_fd, struct redirtab *sq)
5799 if (fd == preverrout_fd) 6544 if (fd == preverrout_fd)
5800 preverrout_fd = new_fd; 6545 preverrout_fd = new_fd;
5801 6546
6547#if ENABLE_PLATFORM_MINGW32 && !defined(_UCRT)
6548 // Workaround for problems with stderr in MSVCRT
6549 if (fd == fileno(stderr))
6550 setvbuf(stderr, NULL, _IONBF, 0);
6551#endif
6552
5802 return 0; /* "we did not close fd" */ 6553 return 0; /* "we did not close fd" */
5803} 6554}
5804 6555
@@ -6152,6 +6903,9 @@ ifsbreakup(char *string, struct arglist *arglist)
6152 const char *ifs, *realifs; 6903 const char *ifs, *realifs;
6153 int ifsspc; 6904 int ifsspc;
6154 int nulonly; 6905 int nulonly;
6906#if ENABLE_PLATFORM_MINGW32
6907 int lshift = 0;
6908#endif
6155 6909
6156 start = string; 6910 start = string;
6157 if (ifslastp != NULL) { 6911 if (ifslastp != NULL) {
@@ -6162,7 +6916,33 @@ ifsbreakup(char *string, struct arglist *arglist)
6162 do { 6916 do {
6163 int afternul; 6917 int afternul;
6164 6918
6919#if ENABLE_PLATFORM_MINGW32
6920 /* Adjust region offsets for left-shifted string. */
6921 ifsp->begoff -= lshift;
6922 ifsp->endoff -= lshift;
6923#endif
6165 p = string + ifsp->begoff; 6924 p = string + ifsp->begoff;
6925#if ENABLE_PLATFORM_MINGW32
6926 if (ifsp->endoff > ifsp->begoff + 1) {
6927 /* Transform CRLF to LF. Skip regions having zero or
6928 * one characters: they can't contain CRLF. If the
6929 * region shrinks shift the rest of the string left. */
6930 int oldlen = ifsp->endoff - ifsp->begoff;
6931 int newlen = remove_cr(p, oldlen);
6932 int delta = oldlen - newlen;
6933
6934 if (delta > 0) {
6935 char *t = string + ifsp->endoff;
6936 char *s = string + ifsp->endoff - delta;
6937
6938 while (*t)
6939 *s++ = *t++;
6940 *s = '\0';
6941 lshift += delta;
6942 ifsp->endoff -= delta;
6943 }
6944 }
6945#endif
6166 afternul = nulonly; 6946 afternul = nulonly;
6167 nulonly = ifsp->nulonly; 6947 nulonly = ifsp->nulonly;
6168 ifs = nulonly ? nullstr : realifs; 6948 ifs = nulonly ? nullstr : realifs;
@@ -6607,6 +7387,7 @@ evalbackcmd(union node *n, struct backcmd *result
6607 const int ip = 0; 7387 const int ip = 0;
6608 const int ic = 1; 7388 const int ic = 1;
6609#endif 7389#endif
7390 IF_PLATFORM_MINGW32(struct forkshell fs);
6610 7391
6611 result->fd = -1; 7392 result->fd = -1;
6612 result->buf = NULL; 7393 result->buf = NULL;
@@ -6620,6 +7401,15 @@ evalbackcmd(union node *n, struct backcmd *result
6620 ash_msg_and_raise_perror("can't create pipe"); 7401 ash_msg_and_raise_perror("can't create pipe");
6621 /* process substitution uses NULL job, like openhere() */ 7402 /* process substitution uses NULL job, like openhere() */
6622 jp = (ctl == CTLBACKQ) ? makejob(/*n,*/ 1) : NULL; 7403 jp = (ctl == CTLBACKQ) ? makejob(/*n,*/ 1) : NULL;
7404#if ENABLE_PLATFORM_MINGW32
7405 memset(&fs, 0, sizeof(fs));
7406 fs.fpid = FS_EVALBACKCMD;
7407 fs.n = n;
7408 fs.fd[0] = pip[0];
7409 fs.fd[1] = pip[1];
7410 fs.fd[2] = ctl;
7411 spawn_forkshell(&fs, jp, n, FORK_NOJOB);
7412#else
6623 if (forkshell(jp, n, FORK_NOJOB) == 0) { 7413 if (forkshell(jp, n, FORK_NOJOB) == 0) {
6624 /* child */ 7414 /* child */
6625 FORCE_INT_ON; 7415 FORCE_INT_ON;
@@ -6643,6 +7433,7 @@ evalbackcmd(union node *n, struct backcmd *result
6643 evaltreenr(n, EV_EXIT); 7433 evaltreenr(n, EV_EXIT);
6644 /* NOTREACHED */ 7434 /* NOTREACHED */
6645 } 7435 }
7436#endif
6646 /* parent */ 7437 /* parent */
6647#if BASH_PROCESS_SUBST 7438#if BASH_PROCESS_SUBST
6648 if (ctl != CTLBACKQ) { 7439 if (ctl != CTLBACKQ) {
@@ -6721,8 +7512,14 @@ expbackq(union node *cmd, int flag IF_BASH_PROCESS_SUBST(, int ctl))
6721 7512
6722 /* Eat all trailing newlines */ 7513 /* Eat all trailing newlines */
6723 dest = expdest; 7514 dest = expdest;
6724 for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';) 7515 for (; dest > ((char *)stackblock() + startloc) && dest[-1] == '\n';) {
6725 STUNPUTC(dest); 7516 STUNPUTC(dest);
7517#if ENABLE_PLATFORM_MINGW32
7518 if (dest > ((char *)stackblock() + startloc) && dest[-1] == '\r') {
7519 STUNPUTC(dest);
7520 }
7521#endif
7522 }
6726 expdest = dest; 7523 expdest = dest;
6727 7524
6728 if (!(flag & EXP_QUOTED)) 7525 if (!(flag & EXP_QUOTED))
@@ -7869,6 +8666,26 @@ expandmeta(struct strlist *str /*, int flag*/)
7869#else 8666#else
7870/* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */ 8667/* ENABLE_ASH_INTERNAL_GLOB: Homegrown globbing code. (dash also has both, uses homegrown one.) */
7871 8668
8669#if ENABLE_ASH_GLOB_OPTIONS
8670static int FAST_FUNC
8671ash_accept_glob(const char *name)
8672{
8673 struct stat st;
8674
8675 if (nohiddenglob || nohidsysglob) {
8676 if (!lstat(name, &st)) {
8677 if ((st.st_attr & FILE_ATTRIBUTE_HIDDEN)) {
8678 if (nohiddenglob ||
8679 (st.st_attr & FILE_ATTRIBUTE_SYSTEM)) {
8680 return FALSE;
8681 }
8682 }
8683 }
8684 }
8685 return TRUE;
8686}
8687#endif
8688
7872/* 8689/*
7873 * Do metacharacter (i.e. *, ?, [...]) expansion. 8690 * Do metacharacter (i.e. *, ?, [...]) expansion.
7874 */ 8691 */
@@ -7896,6 +8713,10 @@ expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7896 8713
7897 metaflag = 0; 8714 metaflag = 0;
7898 start = name; 8715 start = name;
8716#if ENABLE_PLATFORM_MINGW32
8717 if (expdir_len == 0 && has_dos_drive_prefix(start) && start[2] != '/')
8718 start += 2;
8719#endif
7899 for (p = name; esc = 0, *p; p += esc + 1) { 8720 for (p = name; esc = 0, *p; p += esc + 1) {
7900 if (*p == '*' || *p == '?') 8721 if (*p == '*' || *p == '?')
7901 metaflag = 1; 8722 metaflag = 1;
@@ -7970,8 +8791,16 @@ expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7970 while (!pending_int && (dp = readdir(dirp)) != NULL) { 8791 while (!pending_int && (dp = readdir(dirp)) != NULL) {
7971 if (dp->d_name[0] == '.' && !matchdot) 8792 if (dp->d_name[0] == '.' && !matchdot)
7972 continue; 8793 continue;
8794#if ENABLE_ASH_GLOB_OPTIONS
8795# undef pmatch
8796# define pmatch(a, b) !fnmatch((a), (b), nocaseglob ? FNM_CASEFOLD : 0)
8797#endif
7973 if (pmatch(start, dp->d_name)) { 8798 if (pmatch(start, dp->d_name)) {
7974 if (atend) { 8799 if (atend) {
8800#if ENABLE_ASH_GLOB_OPTIONS
8801 if (!ash_accept_glob(dp->d_name))
8802 continue;
8803#endif
7975 strcpy(enddir, dp->d_name); 8804 strcpy(enddir, dp->d_name);
7976 addfname(expdir); 8805 addfname(expdir);
7977 } else { 8806 } else {
@@ -7999,6 +8828,10 @@ expmeta(exp_t *exp, char *name, unsigned name_len, unsigned expdir_len)
7999 endname[-esc - 1] = esc ? '\\' : '/'; 8828 endname[-esc - 1] = esc ? '\\' : '/';
8000#undef expdir 8829#undef expdir
8001#undef expdir_max 8830#undef expdir_max
8831#if ENABLE_ASH_GLOB_OPTIONS
8832# undef pmatch
8833# define pmatch(a, b) !fnmatch((a), (b), 0)
8834#endif
8002} 8835}
8003 8836
8004static struct strlist * 8837static struct strlist *
@@ -8271,14 +9104,40 @@ static int builtinloc = -1; /* index in path of %builtin, or -1 */
8271 9104
8272 9105
8273static void 9106static void
9107#if ENABLE_PLATFORM_MINGW32
9108tryexec(IF_FEATURE_SH_STANDALONE(int applet_no, const char *path, int noexec,)
9109 const char *cmd, char **argv, char **envp)
9110#else
8274tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp) 9111tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, char **envp)
9112#endif
8275{ 9113{
9114#if ENABLE_PLATFORM_MINGW32 && ENABLE_FEATURE_SH_STANDALONE
9115 interp_t interp;
9116#endif
8276#if ENABLE_FEATURE_SH_STANDALONE 9117#if ENABLE_FEATURE_SH_STANDALONE
8277 if (applet_no >= 0) { 9118 if (applet_no >= 0) {
9119# if ENABLE_PLATFORM_MINGW32
9120 /* Treat all applets as NOEXEC, including the shell itself
9121 * if we were called from forkshell_shellexec(). */
9122 run_noexec:
9123 if (applet_main[applet_no] != ash_main || noexec) {
9124 /* mingw-w64's getopt() uses __argv[0] as the program name */
9125 __argv[0] = (char *)cmd;
9126 /* 'which' wants to know if it was invoked from a standalone
9127 * shell. 'Which' in argv[0] indicates this. */
9128 if (strcmp(argv[0], "which") == 0) {
9129 argv[0] = (char *)"Which";
9130 }
9131# else
8278 if (APPLET_IS_NOEXEC(applet_no)) { 9132 if (APPLET_IS_NOEXEC(applet_no)) {
9133# endif
9134#if !ENABLE_PLATFORM_MINGW32 || !defined(_UCRT)
9135 /* If building for UCRT move this up into shellexec() to
9136 * work around a bug. */
8279 clearenv(); 9137 clearenv();
8280 while (*envp) 9138 while (*envp)
8281 putenv(*envp++); 9139 putenv(*envp++);
9140#endif
8282 popredir(/*drop:*/ 1); 9141 popredir(/*drop:*/ 1);
8283 run_noexec_applet_and_exit(applet_no, cmd, argv); 9142 run_noexec_applet_and_exit(applet_no, cmd, argv);
8284 } 9143 }
@@ -8289,6 +9148,44 @@ tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, c
8289 } 9148 }
8290#endif 9149#endif
8291 9150
9151#if ENABLE_PLATFORM_MINGW32
9152 /* Workaround for libtool, which assumes the host is an MSYS2
9153 * environment and requires special-case escaping for cmd.exe.
9154 * https://github.com/skeeto/w64devkit/issues/50 */
9155 if (string_array_len(argv) >= 3 &&
9156 strcmp(argv[0], "cmd") == 0 &&
9157 strcmp(argv[1], "//c") == 0 &&
9158 strcmp(argv[2], "echo") == 0) {
9159 argv[1]++; /* drop extra slash */
9160 }
9161
9162 /* cmd was allocated on the stack with room for an extension */
9163 add_win32_extension((char *)cmd);
9164
9165# if ENABLE_FEATURE_SH_STANDALONE
9166 /* If the command is a script with an interpreter which is an
9167 * applet, we can run it as if it were a noexec applet. */
9168 if (parse_interpreter(cmd, &interp)) {
9169 applet_no = find_applet_by_name_for_sh(interp.name, path);
9170 if (applet_no >= 0) {
9171 argv[0] = (char *)cmd;
9172 /* evalcommand()/spawn_forkshell() add two elements before argv */
9173 if (interp.opts) {
9174 argv--;
9175 argv[0] = (char *)interp.opts;
9176 }
9177 argv--;
9178 cmd = argv[0] = (char *)interp.name;
9179 /* Identify the index of the script file in argv */
9180 set_interp(1 + (interp.opts != NULL));
9181 goto run_noexec;
9182 }
9183 }
9184# endif
9185
9186 execve(cmd, argv, envp);
9187 /* skip POSIX-mandated retry on ENOEXEC */
9188#else /* !ENABLE_PLATFORM_MINGW32 */
8292 repeat: 9189 repeat:
8293#ifdef SYSV 9190#ifdef SYSV
8294 do { 9191 do {
@@ -8324,15 +9221,23 @@ tryexec(IF_FEATURE_SH_STANDALONE(int applet_no,) const char *cmd, char **argv, c
8324 argv[0] = (char*) "ash"; 9221 argv[0] = (char*) "ash";
8325 goto repeat; 9222 goto repeat;
8326 } 9223 }
9224#endif /* !ENABLE_PLATFORM_MINGW32 */
8327} 9225}
8328 9226
9227#if !ENABLE_PLATFORM_MINGW32 || !ENABLE_FEATURE_SH_STANDALONE
9228# define shellexec(prg, a, pth, i, n) shellexec(prg, a, pth, i)
9229#endif
9230
8329/* 9231/*
8330 * Exec a program. Never returns. If you change this routine, you may 9232 * Exec a program. Never returns. If you change this routine, you may
8331 * have to change the find_command routine as well. 9233 * have to change the find_command routine as well.
8332 * argv[-1] must exist and be writable! See tryexec() for why. 9234 * argv[-1] must exist and be writable! See tryexec() for why.
8333 */ 9235 */
8334static void shellexec(char *prog, char **argv, const char *path, int idx) NORETURN; 9236static struct builtincmd *find_builtin(const char *name);
8335static void shellexec(char *prog, char **argv, const char *path, int idx) 9237static void shellexec(char *prog, char **argv, const char *path, int idx,
9238 int noexec) NORETURN;
9239static void shellexec(char *prog, char **argv, const char *path, int idx,
9240 int noexec)
8336{ 9241{
8337 char *cmdname; 9242 char *cmdname;
8338 int e; 9243 int e;
@@ -8341,12 +9246,30 @@ static void shellexec(char *prog, char **argv, const char *path, int idx)
8341 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */ 9246 int applet_no = -1; /* used only by FEATURE_SH_STANDALONE */
8342 9247
8343 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL); 9248 envp = listvars(VEXPORT, VUNSET, /*strlist:*/ NULL, /*end:*/ NULL);
9249#if ENABLE_FEATURE_SH_STANDALONE && ENABLE_PLATFORM_MINGW32 && defined(_UCRT)
9250 /* Avoid UCRT bug by updating parent's environment and passing a
9251 * NULL environment pointer to execve(). */
9252 clearenv();
9253 while (*envp)
9254 putenv(*envp++);
9255 envp = NULL;
9256#endif
9257#if !ENABLE_PLATFORM_MINGW32
8344 if (strchr(prog, '/') != NULL 9258 if (strchr(prog, '/') != NULL
9259#else
9260 if (has_path(prog)
9261#endif
8345#if ENABLE_FEATURE_SH_STANDALONE 9262#if ENABLE_FEATURE_SH_STANDALONE
8346 || (applet_no = find_applet_by_name(prog)) >= 0 9263 || (applet_no = find_applet_by_name_for_sh(prog, path)) >= 0
8347#endif 9264#endif
8348 ) { 9265 ) {
9266#if ENABLE_PLATFORM_MINGW32
9267 char *progext = stack_add_ext_space(prog);
9268 tryexec(IF_FEATURE_SH_STANDALONE(applet_no, path, noexec,)
9269 progext, argv, envp);
9270#else
8349 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp); 9271 tryexec(IF_FEATURE_SH_STANDALONE(applet_no,) prog, argv, envp);
9272#endif
8350 if (applet_no >= 0) { 9273 if (applet_no >= 0) {
8351 /* We tried execing ourself, but it didn't work. 9274 /* We tried execing ourself, but it didn't work.
8352 * Maybe /proc/self/exe doesn't exist? 9275 * Maybe /proc/self/exe doesn't exist?
@@ -8355,13 +9278,33 @@ static void shellexec(char *prog, char **argv, const char *path, int idx)
8355 goto try_PATH; 9278 goto try_PATH;
8356 } 9279 }
8357 e = errno; 9280 e = errno;
9281#if ENABLE_PLATFORM_MINGW32
9282 if (unix_path(prog)) {
9283 const char *name = bb_basename(prog);
9284# if ENABLE_FEATURE_SH_STANDALONE
9285 if ((applet_no = find_applet_by_name_for_sh(name, path)) >= 0) {
9286 tryexec(applet_no, path, noexec, name, argv, envp);
9287 e = errno;
9288 }
9289# endif
9290 if (!find_builtin(name)) {
9291 argv[0] = (char *)name;
9292 goto try_PATH;
9293 }
9294 }
9295#endif
8358 } else { 9296 } else {
8359 try_PATH: 9297 try_PATH:
8360 e = ENOENT; 9298 e = ENOENT;
8361 while (padvance(&path, argv[0]) >= 0) { 9299 while (padvance(&path, argv[0]) >= 0) {
8362 cmdname = stackblock(); 9300 cmdname = stackblock();
8363 if (--idx < 0 && pathopt == NULL) { 9301 if (--idx < 0 && pathopt == NULL) {
9302#if ENABLE_PLATFORM_MINGW32
9303 tryexec(IF_FEATURE_SH_STANDALONE(-1, path, noexec,)
9304 cmdname, argv, envp);
9305#else
8364 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp); 9306 tryexec(IF_FEATURE_SH_STANDALONE(-1,) cmdname, argv, envp);
9307#endif
8365 if (errno != ENOENT && errno != ENOTDIR) 9308 if (errno != ENOENT && errno != ENOTDIR)
8366 e = errno; 9309 e = errno;
8367 } 9310 }
@@ -8400,6 +9343,9 @@ printentry(struct tblentry *cmdp)
8400 padvance(&path, cmdp->cmdname); 9343 padvance(&path, cmdp->cmdname);
8401 } while (--idx >= 0); 9344 } while (--idx >= 0);
8402 name = stackblock(); 9345 name = stackblock();
9346#if ENABLE_PLATFORM_MINGW32
9347 add_win32_extension(name);
9348#endif
8403 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr)); 9349 out1fmt("%s%s\n", name, (cmdp->rehash ? "*" : nullstr));
8404} 9350}
8405 9351
@@ -8600,7 +9546,7 @@ changepath(const char *newval)
8600 bltin = idx; 9546 bltin = idx;
8601 break; 9547 break;
8602 } 9548 }
8603 new = strchr(new, ':'); 9549 new = strchr(new, PATH_SEP);
8604 if (!new) 9550 if (!new)
8605 break; 9551 break;
8606 idx++; 9552 idx++;
@@ -8777,14 +9723,37 @@ describe_command(char *command, const char *path, int describe_command_verbose)
8777 case CMDNORMAL: { 9723 case CMDNORMAL: {
8778 int j = entry.u.index; 9724 int j = entry.u.index;
8779 char *p; 9725 char *p;
9726#if ENABLE_PLATFORM_MINGW32 && ENABLE_FEATURE_SH_STANDALONE
9727 if (j < -1) {
9728 p = (char *)bb_basename(command);
9729 if (describe_command_verbose) {
9730 out1fmt(" is a builtin applet");
9731 } else {
9732 out1str(applet_to_exe(p));
9733 }
9734 break;
9735 }
9736#endif
8780 if (j < 0) { 9737 if (j < 0) {
9738#if ENABLE_PLATFORM_MINGW32
9739 p = stack_add_ext_space(command);
9740#else
8781 p = command; 9741 p = command;
9742#endif
8782 } else { 9743 } else {
9744#if ENABLE_PLATFORM_MINGW32
9745 if (unix_path(command))
9746 command = (char *)bb_basename(command);
9747#endif
8783 do { 9748 do {
8784 padvance(&path, command); 9749 padvance(&path, command);
8785 } while (--j >= 0); 9750 } while (--j >= 0);
8786 p = stackblock(); 9751 p = stackblock();
8787 } 9752 }
9753#if ENABLE_PLATFORM_MINGW32
9754 add_win32_extension(p);
9755 bs_to_slash(p);
9756#endif
8788 if (describe_command_verbose) { 9757 if (describe_command_verbose) {
8789 out1fmt(" is %s", p); 9758 out1fmt(" is %s", p);
8790 } else { 9759 } else {
@@ -8940,6 +9909,15 @@ commandcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
8940/*static int funcstringsize; // size of strings in node */ 9909/*static int funcstringsize; // size of strings in node */
8941static void *funcblock; /* block to allocate function from */ 9910static void *funcblock; /* block to allocate function from */
8942static char *funcstring_end; /* end of block to allocate strings from */ 9911static char *funcstring_end; /* end of block to allocate strings from */
9912#if ENABLE_PLATFORM_MINGW32
9913static int fs_size;
9914static void *fs_start;
9915# if FORKSHELL_DEBUG
9916static void *fs_funcstring;
9917static const char **annot;
9918static char *annot_free;
9919# endif
9920#endif
8943 9921
8944static const uint8_t nodesize[N_NUMBER] ALIGN1 = { 9922static const uint8_t nodesize[N_NUMBER] ALIGN1 = {
8945 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)), 9923 [NCMD ] = SHELL_ALIGN(sizeof(struct ncmd)),
@@ -9072,14 +10050,79 @@ calcsize(int funcblocksize, union node *n)
9072} 10050}
9073 10051
9074static char * 10052static char *
9075nodeckstrdup(char *s) 10053nodeckstrdup(const char *s)
9076{ 10054{
10055#if ENABLE_PLATFORM_MINGW32
10056 if(!s)
10057 return NULL;
10058#endif
9077 funcstring_end -= SHELL_ALIGN(strlen(s) + 1); 10059 funcstring_end -= SHELL_ALIGN(strlen(s) + 1);
9078 return strcpy(funcstring_end, s); 10060 return strcpy(funcstring_end, s);
9079} 10061}
9080 10062
9081static union node *copynode(union node *); 10063static union node *copynode(union node *);
9082 10064
10065#if ENABLE_PLATFORM_MINGW32
10066# if FORKSHELL_DEBUG
10067# define MARK_PTR(dst,note,flag) forkshell_mark_ptr((void *)&dst, note, flag)
10068# else
10069# define MARK_PTR(dst,note,flag) forkshell_mark_ptr((void *)&dst)
10070# endif
10071
10072#define NO_FREE 0
10073#define FREE 1
10074
10075#if FORKSHELL_DEBUG
10076static void forkshell_mark_ptr(void *dst, const char *note, int flag)
10077#else
10078static void forkshell_mark_ptr(void *dst)
10079#endif
10080{
10081 char *lrelocate = (char *)fs_start + fs_size;
10082 int index = ((char *)dst - (char *)fs_start)/sizeof(char *);
10083
10084 lrelocate[index/8] |= 1 << (index % 8);
10085
10086#if FORKSHELL_DEBUG
10087 if (dst < fs_start || dst >= fs_funcstring) {
10088 fprintf(stderr, "dst (%p) out of range (%p %p)\n",
10089 dst, fs_start, fs_funcstring);
10090 }
10091 if (annot) {
10092 if (annot[index]) {
10093 fprintf(stderr, "duplicate annotation: %s %s\n",
10094 annot[index], note);
10095 }
10096 annot[index] = note;
10097 annot_free[index] = flag;
10098 }
10099#endif
10100}
10101
10102# define SAVE_PTR(dst,note,flag) { \
10103 if (fs_size) { \
10104 MARK_PTR(dst,note,flag); \
10105 } \
10106}
10107# define SAVE_PTR2(dst1,note1,flag1,dst2,note2,flag2) { \
10108 if (fs_size) { \
10109 MARK_PTR(dst1,note1,flag1); \
10110 MARK_PTR(dst2,note2,flag2); \
10111 } \
10112}
10113# define SAVE_PTR3(dst1,note1,flag1,dst2,note2,flag2,dst3,note3,flag3) { \
10114 if (fs_size) { \
10115 MARK_PTR(dst1,note1,flag1); \
10116 MARK_PTR(dst2,note2,flag2); \
10117 MARK_PTR(dst3,note3,flag3); \
10118 } \
10119}
10120#else
10121# define SAVE_PTR(dst,note,flag)
10122# define SAVE_PTR2(dst1,note1,flag1,dst2,note2,flag2)
10123# define SAVE_PTR3(dst1,note1,flag1,dst2,note2,flag2,dst3,note3,flag3)
10124#endif
10125
9083static struct nodelist * 10126static struct nodelist *
9084copynodelist(struct nodelist *lp) 10127copynodelist(struct nodelist *lp)
9085{ 10128{
@@ -9091,6 +10134,8 @@ copynodelist(struct nodelist *lp)
9091 *lpp = funcblock; 10134 *lpp = funcblock;
9092 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist)); 10135 funcblock = (char *) funcblock + SHELL_ALIGN(sizeof(struct nodelist));
9093 (*lpp)->n = copynode(lp->n); 10136 (*lpp)->n = copynode(lp->n);
10137 SAVE_PTR2((*lpp)->n, "(*lpp)->next", NO_FREE,
10138 (*lpp)->next, "(*lpp)->next", NO_FREE);
9094 lp = lp->next; 10139 lp = lp->next;
9095 lpp = &(*lpp)->next; 10140 lpp = &(*lpp)->next;
9096 } 10141 }
@@ -9114,10 +10159,14 @@ copynode(union node *n)
9114 new->ncmd.args = copynode(n->ncmd.args); 10159 new->ncmd.args = copynode(n->ncmd.args);
9115 new->ncmd.assign = copynode(n->ncmd.assign); 10160 new->ncmd.assign = copynode(n->ncmd.assign);
9116 new->ncmd.linno = n->ncmd.linno; 10161 new->ncmd.linno = n->ncmd.linno;
10162 SAVE_PTR3(new->ncmd.redirect, "ncmd.redirect", NO_FREE,
10163 new->ncmd.args, "ncmd.args", NO_FREE,
10164 new->ncmd.assign, "ncmd.assign", NO_FREE);
9117 break; 10165 break;
9118 case NPIPE: 10166 case NPIPE:
9119 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist); 10167 new->npipe.cmdlist = copynodelist(n->npipe.cmdlist);
9120 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd; 10168 new->npipe.pipe_backgnd = n->npipe.pipe_backgnd;
10169 SAVE_PTR(new->npipe.cmdlist, "npipe.cmdlist", NO_FREE);
9121 break; 10170 break;
9122 case NREDIR: 10171 case NREDIR:
9123 case NBACKGND: 10172 case NBACKGND:
@@ -9125,6 +10174,8 @@ copynode(union node *n)
9125 new->nredir.redirect = copynode(n->nredir.redirect); 10174 new->nredir.redirect = copynode(n->nredir.redirect);
9126 new->nredir.n = copynode(n->nredir.n); 10175 new->nredir.n = copynode(n->nredir.n);
9127 new->nredir.linno = n->nredir.linno; 10176 new->nredir.linno = n->nredir.linno;
10177 SAVE_PTR2(new->nredir.redirect, "nredir.redirect", NO_FREE,
10178 new->nredir.n, "nredir.n", NO_FREE);
9128 break; 10179 break;
9129 case NAND: 10180 case NAND:
9130 case NOR: 10181 case NOR:
@@ -9133,37 +10184,58 @@ copynode(union node *n)
9133 case NUNTIL: 10184 case NUNTIL:
9134 new->nbinary.ch2 = copynode(n->nbinary.ch2); 10185 new->nbinary.ch2 = copynode(n->nbinary.ch2);
9135 new->nbinary.ch1 = copynode(n->nbinary.ch1); 10186 new->nbinary.ch1 = copynode(n->nbinary.ch1);
10187 SAVE_PTR2(new->nbinary.ch1, "nbinary.ch1", NO_FREE,
10188 new->nbinary.ch2, "nbinary.ch2", NO_FREE);
9136 break; 10189 break;
9137 case NIF: 10190 case NIF:
9138 new->nif.elsepart = copynode(n->nif.elsepart); 10191 new->nif.elsepart = copynode(n->nif.elsepart);
9139 new->nif.ifpart = copynode(n->nif.ifpart); 10192 new->nif.ifpart = copynode(n->nif.ifpart);
9140 new->nif.test = copynode(n->nif.test); 10193 new->nif.test = copynode(n->nif.test);
10194 SAVE_PTR3(new->nif.elsepart, "nif.elsepart", NO_FREE,
10195 new->nif.ifpart, "nif.ifpart", NO_FREE,
10196 new->nif.test, "nif.test", NO_FREE);
9141 break; 10197 break;
9142 case NFOR: 10198 case NFOR:
9143 new->nfor.var = nodeckstrdup(n->nfor.var); 10199 new->nfor.var = nodeckstrdup(n->nfor.var);
9144 new->nfor.body = copynode(n->nfor.body); 10200 new->nfor.body = copynode(n->nfor.body);
9145 new->nfor.args = copynode(n->nfor.args); 10201 new->nfor.args = copynode(n->nfor.args);
9146 new->nfor.linno = n->nfor.linno; 10202 new->nfor.linno = n->nfor.linno;
10203 SAVE_PTR3(new->nfor.var,
10204 xasprintf("nfor.var '%s'", n->nfor.var ?: "NULL"), FREE,
10205 new->nfor.body, "nfor.body", NO_FREE,
10206 new->nfor.args, "nfor.args", NO_FREE);
9147 break; 10207 break;
9148 case NCASE: 10208 case NCASE:
9149 new->ncase.cases = copynode(n->ncase.cases); 10209 new->ncase.cases = copynode(n->ncase.cases);
9150 new->ncase.expr = copynode(n->ncase.expr); 10210 new->ncase.expr = copynode(n->ncase.expr);
9151 new->ncase.linno = n->ncase.linno; 10211 new->ncase.linno = n->ncase.linno;
10212 SAVE_PTR2(new->ncase.cases, "ncase.cases", NO_FREE,
10213 new->ncase.expr, "ncase.expr", NO_FREE);
9152 break; 10214 break;
9153 case NCLIST: 10215 case NCLIST:
9154 new->nclist.body = copynode(n->nclist.body); 10216 new->nclist.body = copynode(n->nclist.body);
9155 new->nclist.pattern = copynode(n->nclist.pattern); 10217 new->nclist.pattern = copynode(n->nclist.pattern);
9156 new->nclist.next = copynode(n->nclist.next); 10218 new->nclist.next = copynode(n->nclist.next);
10219 SAVE_PTR3(new->nclist.body, "nclist.body", NO_FREE,
10220 new->nclist.pattern, "nclist.pattern", NO_FREE,
10221 new->nclist.next, "nclist.next", NO_FREE);
9157 break; 10222 break;
9158 case NDEFUN: 10223 case NDEFUN:
9159 new->ndefun.body = copynode(n->ndefun.body); 10224 new->ndefun.body = copynode(n->ndefun.body);
9160 new->ndefun.text = nodeckstrdup(n->ndefun.text); 10225 new->ndefun.text = nodeckstrdup(n->ndefun.text);
9161 new->ndefun.linno = n->ndefun.linno; 10226 new->ndefun.linno = n->ndefun.linno;
10227 SAVE_PTR2(new->ndefun.body, "ndefun.body", NO_FREE,
10228 new->ndefun.text,
10229 xasprintf("ndefun.text '%s'", n->ndefun.text ?: "NULL"), FREE);
9162 break; 10230 break;
9163 case NARG: 10231 case NARG:
9164 new->narg.backquote = copynodelist(n->narg.backquote); 10232 new->narg.backquote = copynodelist(n->narg.backquote);
9165 new->narg.text = nodeckstrdup(n->narg.text); 10233 new->narg.text = nodeckstrdup(n->narg.text);
9166 new->narg.next = copynode(n->narg.next); 10234 new->narg.next = copynode(n->narg.next);
10235 SAVE_PTR3(new->narg.backquote, "narg.backquote", NO_FREE,
10236 new->narg.text,
10237 xasprintf("narg.text '%s'", n->narg.text ?: "NULL"), FREE,
10238 new->narg.next, "narg.next", NO_FREE);
9167 break; 10239 break;
9168 case NTO: 10240 case NTO:
9169#if BASH_REDIR_OUTPUT 10241#if BASH_REDIR_OUTPUT
@@ -9176,6 +10248,8 @@ copynode(union node *n)
9176 new->nfile.fname = copynode(n->nfile.fname); 10248 new->nfile.fname = copynode(n->nfile.fname);
9177 new->nfile.fd = n->nfile.fd; 10249 new->nfile.fd = n->nfile.fd;
9178 new->nfile.next = copynode(n->nfile.next); 10250 new->nfile.next = copynode(n->nfile.next);
10251 SAVE_PTR2(new->nfile.fname, "nfile.fname", NO_FREE,
10252 new->nfile.next, "nfile.next", NO_FREE);
9179 break; 10253 break;
9180 case NTOFD: 10254 case NTOFD:
9181 case NFROMFD: 10255 case NFROMFD:
@@ -9183,15 +10257,20 @@ copynode(union node *n)
9183 new->ndup.dupfd = n->ndup.dupfd; 10257 new->ndup.dupfd = n->ndup.dupfd;
9184 new->ndup.fd = n->ndup.fd; 10258 new->ndup.fd = n->ndup.fd;
9185 new->ndup.next = copynode(n->ndup.next); 10259 new->ndup.next = copynode(n->ndup.next);
10260 SAVE_PTR2(new->ndup.vname, "ndup.vname", NO_FREE,
10261 new->ndup.next, "ndup.next", NO_FREE);
9186 break; 10262 break;
9187 case NHERE: 10263 case NHERE:
9188 case NXHERE: 10264 case NXHERE:
9189 new->nhere.doc = copynode(n->nhere.doc); 10265 new->nhere.doc = copynode(n->nhere.doc);
9190 new->nhere.fd = n->nhere.fd; 10266 new->nhere.fd = n->nhere.fd;
9191 new->nhere.next = copynode(n->nhere.next); 10267 new->nhere.next = copynode(n->nhere.next);
10268 SAVE_PTR2(new->nhere.doc, "nhere.doc", NO_FREE,
10269 new->nhere.next, "nhere.next", NO_FREE);
9192 break; 10270 break;
9193 case NNOT: 10271 case NNOT:
9194 new->nnot.com = copynode(n->nnot.com); 10272 new->nnot.com = copynode(n->nnot.com);
10273 SAVE_PTR(new->nnot.com, "nnot.com", NO_FREE);
9195 break; 10274 break;
9196 }; 10275 };
9197 new->type = n->type; 10276 new->type = n->type;
@@ -9212,6 +10291,7 @@ copyfunc(union node *n)
9212 f = ckzalloc(blocksize /* + funcstringsize */); 10291 f = ckzalloc(blocksize /* + funcstringsize */);
9213 funcblock = (char *) f + offsetof(struct funcnode, n); 10292 funcblock = (char *) f + offsetof(struct funcnode, n);
9214 funcstring_end = (char *) f + blocksize; 10293 funcstring_end = (char *) f + blocksize;
10294 IF_PLATFORM_MINGW32(fs_size = 0);
9215 copynode(n); 10295 copynode(n);
9216 /* f->count = 0; - ckzalloc did it */ 10296 /* f->count = 0; - ckzalloc did it */
9217 return f; 10297 return f;
@@ -9239,12 +10319,15 @@ defun(union node *func)
9239#define SKIPFUNCDEF (1 << 3) 10319#define SKIPFUNCDEF (1 << 3)
9240static smallint evalskip; /* set to SKIPxxx if we are skipping commands */ 10320static smallint evalskip; /* set to SKIPxxx if we are skipping commands */
9241static int skipcount; /* number of levels to skip */ 10321static int skipcount; /* number of levels to skip */
10322#if ENABLE_PLATFORM_POSIX
9242static int loopnest; /* current loop nesting level */ 10323static int loopnest; /* current loop nesting level */
10324#endif
9243static int funcline; /* starting line number of current function, or 0 if not in a function */ 10325static int funcline; /* starting line number of current function, or 0 if not in a function */
9244 10326
9245/* Forward decl way out to parsing code - dotrap needs it */ 10327/* Forward decl way out to parsing code - dotrap needs it */
9246static int evalstring(char *s, int flags); 10328static int evalstring(char *s, int flags);
9247 10329
10330#if !ENABLE_PLATFORM_MINGW32
9248/* Called to execute a trap. 10331/* Called to execute a trap.
9249 * Single callsite - at the end of evaltree(). 10332 * Single callsite - at the end of evaltree().
9250 * If we return non-zero, evaltree raises EXEXIT exception. 10333 * If we return non-zero, evaltree raises EXEXIT exception.
@@ -9303,6 +10386,45 @@ dotrap(void)
9303 savestatus = last_status; 10386 savestatus = last_status;
9304 TRACE(("dotrap returns\n")); 10387 TRACE(("dotrap returns\n"));
9305} 10388}
10389#else
10390static void
10391dotrap(void)
10392{
10393 int status, last_status;
10394 char *p;
10395
10396 if (!pending_int)
10397 return;
10398
10399 status = savestatus;
10400 last_status = status;
10401 if (status < 0) {
10402 status = exitstatus;
10403 savestatus = status;
10404 }
10405 pending_int = 0;
10406 barrier();
10407
10408 TRACE(("dotrap entered\n"));
10409 if (evalskip) {
10410 pending_int = 1;
10411 return;
10412 }
10413
10414 p = trap[SIGINT];
10415 if (p) {
10416 TRACE(("sig %d is active, will run handler '%s'\n", SIGINT, p));
10417 trap_depth++;
10418 evalstring(p, 0);
10419 trap_depth--;
10420 if (evalskip != SKIPFUNC)
10421 exitstatus = status;
10422 }
10423
10424 savestatus = last_status;
10425 TRACE(("dotrap returns\n"));
10426}
10427#endif
9306 10428
9307/* forward declarations - evaluation is fairly recursive business... */ 10429/* forward declarations - evaluation is fairly recursive business... */
9308static int evalloop(union node *, int); 10430static int evalloop(union node *, int);
@@ -9588,19 +10710,36 @@ evalcase(union node *n, int flags)
9588static int 10710static int
9589evalsubshell(union node *n, int flags) 10711evalsubshell(union node *n, int flags)
9590{ 10712{
10713 IF_PLATFORM_MINGW32(struct forkshell fs;)
9591 struct job *jp; 10714 struct job *jp;
9592 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */ 10715 int backgnd = (n->type == NBACKGND); /* FORK_BG(1) if yes, else FORK_FG(0) */
9593 int status; 10716 int status;
9594 10717
9595 errlinno = lineno = n->nredir.linno; 10718 errlinno = lineno = n->nredir.linno;
9596 10719
10720#if ENABLE_PLATFORM_MINGW32
10721 if (!backgnd && (flags & EV_EXIT) && !may_have_traps) {
10722 expredir(n->nredir.redirect);
10723 redirect(n->nredir.redirect, 0);
10724 evaltreenr(n->nredir.n, flags);
10725 /* never returns */
10726 }
10727#else
9597 expredir(n->nredir.redirect); 10728 expredir(n->nredir.redirect);
9598 if (!backgnd && (flags & EV_EXIT) && !may_have_traps) 10729 if (!backgnd && (flags & EV_EXIT) && !may_have_traps)
9599 goto nofork; 10730 goto nofork;
10731#endif
9600 INT_OFF; 10732 INT_OFF;
9601 if (backgnd == FORK_FG) 10733 if (backgnd == FORK_FG)
9602 get_tty_state(); 10734 get_tty_state();
9603 jp = makejob(/*n,*/ 1); 10735 jp = makejob(/*n,*/ 1);
10736#if ENABLE_PLATFORM_MINGW32
10737 memset(&fs, 0, sizeof(fs));
10738 fs.fpid = FS_EVALSUBSHELL;
10739 fs.n = n;
10740 fs.flags = flags;
10741 spawn_forkshell(&fs, jp, n, backgnd);
10742#else
9604 if (forkshell(jp, n, backgnd) == 0) { 10743 if (forkshell(jp, n, backgnd) == 0) {
9605 /* child */ 10744 /* child */
9606 INT_ON; 10745 INT_ON;
@@ -9612,6 +10751,7 @@ evalsubshell(union node *n, int flags)
9612 evaltreenr(n->nredir.n, flags); 10751 evaltreenr(n->nredir.n, flags);
9613 /* never returns */ 10752 /* never returns */
9614 } 10753 }
10754#endif
9615 /* parent */ 10755 /* parent */
9616 status = 0; 10756 status = 0;
9617 if (backgnd == FORK_FG) 10757 if (backgnd == FORK_FG)
@@ -9692,6 +10832,7 @@ expredir(union node *n)
9692static int 10832static int
9693evalpipe(union node *n, int flags) 10833evalpipe(union node *n, int flags)
9694{ 10834{
10835 IF_PLATFORM_MINGW32(struct forkshell fs;)
9695 struct job *jp; 10836 struct job *jp;
9696 struct nodelist *lp; 10837 struct nodelist *lp;
9697 int pipelen; 10838 int pipelen;
@@ -9718,6 +10859,16 @@ evalpipe(union node *n, int flags)
9718 ash_msg_and_raise_perror("can't create pipe"); 10859 ash_msg_and_raise_perror("can't create pipe");
9719 } 10860 }
9720 } 10861 }
10862#if ENABLE_PLATFORM_MINGW32
10863 memset(&fs, 0, sizeof(fs));
10864 fs.fpid = FS_EVALPIPE;
10865 fs.flags = flags;
10866 fs.n = lp->n;
10867 fs.fd[0] = pip[0];
10868 fs.fd[1] = pip[1];
10869 fs.fd[2] = prevfd;
10870 spawn_forkshell(&fs, jp, lp->n, n->npipe.pipe_backgnd);
10871#else
9721 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) { 10872 if (forkshell(jp, lp->n, n->npipe.pipe_backgnd) == 0) {
9722 /* child */ 10873 /* child */
9723 INT_ON; 10874 INT_ON;
@@ -9735,6 +10886,7 @@ evalpipe(union node *n, int flags)
9735 evaltreenr(lp->n, flags); 10886 evaltreenr(lp->n, flags);
9736 /* never returns */ 10887 /* never returns */
9737 } 10888 }
10889#endif
9738 /* parent */ 10890 /* parent */
9739 if (prevfd >= 0) 10891 if (prevfd >= 0)
9740 close(prevfd); 10892 close(prevfd);
@@ -9792,6 +10944,9 @@ setinteractive(int on)
9792 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP); 10944 line_input_state = new_line_input_t(FOR_SHELL | WITH_PATH_LOOKUP);
9793# if ENABLE_FEATURE_TAB_COMPLETION 10945# if ENABLE_FEATURE_TAB_COMPLETION
9794 line_input_state->get_exe_name = ash_command_name; 10946 line_input_state->get_exe_name = ash_command_name;
10947# if ENABLE_ASH_GLOB_OPTIONS
10948 line_input_state->sh_accept_glob = ash_accept_glob;
10949# endif
9795# endif 10950# endif
9796# if EDITING_HAS_sh_get_var 10951# if EDITING_HAS_sh_get_var
9797 line_input_state->sh_get_var = lookupvar; 10952 line_input_state->sh_get_var = lookupvar;
@@ -9819,6 +10974,12 @@ optschanged(void)
9819#else 10974#else
9820 viflag = 0; /* forcibly keep the option off */ 10975 viflag = 0; /* forcibly keep the option off */
9821#endif 10976#endif
10977#if ENABLE_ASH_NOCONSOLE
10978 hide_console(noconsole);
10979#endif
10980#if ENABLE_PLATFORM_MINGW32
10981 setwinxp(winxp);
10982#endif
9822} 10983}
9823 10984
9824struct localvar_list { 10985struct localvar_list {
@@ -9838,6 +10999,9 @@ poplocalvars(int keep)
9838 struct localvar_list *ll; 10999 struct localvar_list *ll;
9839 struct localvar *lvp, *next; 11000 struct localvar *lvp, *next;
9840 struct var *vp; 11001 struct var *vp;
11002#if ENABLE_PLATFORM_MINGW32
11003 int var_type;
11004#endif
9841 11005
9842 INT_OFF; 11006 INT_OFF;
9843 ll = localvar_stack; 11007 ll = localvar_stack;
@@ -9880,6 +11044,17 @@ poplocalvars(int keep)
9880 free((char*)vp->var_text); 11044 free((char*)vp->var_text);
9881 vp->flags = lvp->flags; 11045 vp->flags = lvp->flags;
9882 vp->var_text = lvp->text; 11046 vp->var_text = lvp->text;
11047#if ENABLE_PLATFORM_MINGW32
11048 var_type = is_bb_var(lvp->text);
11049 if (var_type == BB_VAR_ASSIGN && (lvp->flags & VEXPORT))
11050 putenv(lvp->text);
11051 else if (var_type) {
11052 char *var = xstrdup(lvp->text);
11053 *strchrnul(var, '=') = '\0';
11054 unsetenv(var);
11055 free(var);
11056 }
11057#endif
9883 } 11058 }
9884 free(lvp); 11059 free(lvp);
9885 } 11060 }
@@ -10102,7 +11277,7 @@ execcmd(int argc UNUSED_PARAM, char **argv)
10102 prog = argv[0]; 11277 prog = argv[0];
10103 if (optionarg) 11278 if (optionarg)
10104 argv[0] = optionarg; 11279 argv[0] = optionarg;
10105 shellexec(prog, argv, pathval(), 0); 11280 shellexec(prog, argv, pathval(), 0, FALSE);
10106 /* NOTREACHED */ 11281 /* NOTREACHED */
10107 } 11282 }
10108 return 0; 11283 return 0;
@@ -10155,6 +11330,9 @@ static int readcmd(int, char **) FAST_FUNC;
10155static int setcmd(int, char **) FAST_FUNC; 11330static int setcmd(int, char **) FAST_FUNC;
10156static int shiftcmd(int, char **) FAST_FUNC; 11331static int shiftcmd(int, char **) FAST_FUNC;
10157static int timescmd(int, char **) FAST_FUNC; 11332static int timescmd(int, char **) FAST_FUNC;
11333#if ENABLE_PLATFORM_MINGW32
11334static int titlecmd(int, char **) FAST_FUNC;
11335#endif
10158static int trapcmd(int, char **) FAST_FUNC; 11336static int trapcmd(int, char **) FAST_FUNC;
10159static int umaskcmd(int, char **) FAST_FUNC; 11337static int umaskcmd(int, char **) FAST_FUNC;
10160static int unsetcmd(int, char **) FAST_FUNC; 11338static int unsetcmd(int, char **) FAST_FUNC;
@@ -10227,7 +11405,7 @@ static const struct builtincmd builtintab[] = {
10227#if MAX_HISTORY 11405#if MAX_HISTORY
10228 { BUILTIN_NOSPEC "history" , historycmd }, 11406 { BUILTIN_NOSPEC "history" , historycmd },
10229#endif 11407#endif
10230#if JOBS 11408#if JOBS || JOBS_WIN32
10231 { BUILTIN_REGULAR "jobs" , jobscmd }, 11409 { BUILTIN_REGULAR "jobs" , jobscmd },
10232 { BUILTIN_REGULAR "kill" , killcmd }, 11410 { BUILTIN_REGULAR "kill" , killcmd },
10233#endif 11411#endif
@@ -10254,6 +11432,9 @@ static const struct builtincmd builtintab[] = {
10254 { BUILTIN_REGULAR "test" , testcmd }, 11432 { BUILTIN_REGULAR "test" , testcmd },
10255#endif 11433#endif
10256 { BUILTIN_SPEC_REG "times" , timescmd }, 11434 { BUILTIN_SPEC_REG "times" , timescmd },
11435#if ENABLE_PLATFORM_MINGW32
11436 { BUILTIN_REGULAR "title" , titlecmd },
11437#endif
10257 { BUILTIN_SPEC_REG "trap" , trapcmd }, 11438 { BUILTIN_SPEC_REG "trap" , trapcmd },
10258 { BUILTIN_REGULAR "true" , truecmd }, 11439 { BUILTIN_REGULAR "true" , truecmd },
10259 { BUILTIN_REGULAR "type" , typecmd }, 11440 { BUILTIN_REGULAR "type" , typecmd },
@@ -10272,7 +11453,7 @@ static const struct builtincmd builtintab[] = {
10272 /* [ */ 1 * ENABLE_ASH_TEST + \ 11453 /* [ */ 1 * ENABLE_ASH_TEST + \
10273 /* [[ */ 1 * BASH_TEST2 + \ 11454 /* [[ */ 1 * BASH_TEST2 + \
10274 /* alias */ 1 * ENABLE_ASH_ALIAS + \ 11455 /* alias */ 1 * ENABLE_ASH_ALIAS + \
10275 /* bg */ 1 * ENABLE_ASH_JOB_CONTROL + \ 11456 /* bg */ 1 * JOBS + \
10276 /* break cd cddir */ 3) 11457 /* break cd cddir */ 3)
10277#define EVALCMD (COMMANDCMD + \ 11458#define EVALCMD (COMMANDCMD + \
10278 /* command */ 1 * ENABLE_ASH_CMDCMD + \ 11459 /* command */ 1 * ENABLE_ASH_CMDCMD + \
@@ -10353,6 +11534,7 @@ bltincmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
10353 * as POSIX mandates */ 11534 * as POSIX mandates */
10354 return back_exitstatus; 11535 return back_exitstatus;
10355} 11536}
11537
10356static int 11538static int
10357evalcommand(union node *cmd, int flags) 11539evalcommand(union node *cmd, int flags)
10358{ 11540{
@@ -10452,9 +11634,19 @@ evalcommand(union node *cmd, int flags)
10452 11634
10453 localvar_stop = pushlocalvars(vlocal); 11635 localvar_stop = pushlocalvars(vlocal);
10454 11636
11637#if ENABLE_PLATFORM_MINGW32
11638# if ENABLE_FEATURE_SH_STANDALONE
11639 /* Reserve two extra spots at the front for shellexec. */
11640 nargv = stalloc(sizeof(char *) * (argc + 3));
11641 argv = nargv = nargv + 2;
11642# else
11643 argv = nargv = stalloc(sizeof(char *) * (argc + 1));
11644# endif
11645#else
10455 /* Reserve one extra spot at the front for shellexec. */ 11646 /* Reserve one extra spot at the front for shellexec. */
10456 nargv = stalloc(sizeof(char *) * (argc + 2)); 11647 nargv = stalloc(sizeof(char *) * (argc + 2));
10457 argv = ++nargv; 11648 argv = ++nargv;
11649#endif
10458 for (sp = arglist.list; sp; sp = sp->next) { 11650 for (sp = arglist.list; sp; sp = sp->next) {
10459 TRACE(("evalcommand arg: %s\n", sp->text)); 11651 TRACE(("evalcommand arg: %s\n", sp->text));
10460 *nargv++ = sp->text; 11652 *nargv++ = sp->text;
@@ -10563,9 +11755,11 @@ evalcommand(union node *cmd, int flags)
10563 11755
10564 default: { 11756 default: {
10565 11757
11758//TODO: find a better solution for Windows on ARM than ignoring NOFORK
10566#if ENABLE_FEATURE_SH_STANDALONE \ 11759#if ENABLE_FEATURE_SH_STANDALONE \
10567 && ENABLE_FEATURE_SH_NOFORK \ 11760 && ENABLE_FEATURE_SH_NOFORK \
10568 && NUM_APPLETS > 1 11761 && NUM_APPLETS > 1 \
11762 && !(defined(_ARM64_) && !defined(_UCRT) && ENABLE_PLATFORM_MINGW32)
10569/* (1) BUG: if variables are set, we need to fork, or save/restore them 11763/* (1) BUG: if variables are set, we need to fork, or save/restore them
10570 * around run_nofork_applet() call. 11764 * around run_nofork_applet() call.
10571 * (2) Should this check also be done in forkshell()? 11765 * (2) Should this check also be done in forkshell()?
@@ -10575,6 +11769,9 @@ evalcommand(union node *cmd, int flags)
10575 int applet_no = (- cmdentry.u.index - 2); 11769 int applet_no = (- cmdentry.u.index - 2);
10576 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) { 11770 if (applet_no >= 0 && APPLET_IS_NOFORK(applet_no)) {
10577 char **sv_environ; 11771 char **sv_environ;
11772#if ENABLE_PLATFORM_MINGW32
11773 char *sv_argv0;
11774#endif
10578 11775
10579 INT_OFF; 11776 INT_OFF;
10580 sv_environ = environ; 11777 sv_environ = environ;
@@ -10587,8 +11784,16 @@ evalcommand(union node *cmd, int flags)
10587 * and/or wait for user input ineligible for NOFORK: 11784 * and/or wait for user input ineligible for NOFORK:
10588 * for example, "yes" or "rm" (rm -i waits for input). 11785 * for example, "yes" or "rm" (rm -i waits for input).
10589 */ 11786 */
11787#if ENABLE_PLATFORM_MINGW32
11788 sv_argv0 = __argv[0];
11789 argv[0] = (char *)bb_basename(argv[0]);
11790 __argv[0] = argv[0];
11791#endif
10590 exitstatus = run_nofork_applet(applet_no, argv); 11792 exitstatus = run_nofork_applet(applet_no, argv);
10591 environ = sv_environ; 11793 environ = sv_environ;
11794#if ENABLE_PLATFORM_MINGW32
11795 __argv[0] = sv_argv0;
11796#endif
10592 /* 11797 /*
10593 * Try enabling NOFORK for "yes" applet. 11798 * Try enabling NOFORK for "yes" applet.
10594 * ^C _will_ stop it (write returns EINTR), 11799 * ^C _will_ stop it (write returns EINTR),
@@ -10606,6 +11811,22 @@ evalcommand(union node *cmd, int flags)
10606 * in a script or a subshell does not need forking, 11811 * in a script or a subshell does not need forking,
10607 * we can just exec it. 11812 * we can just exec it.
10608 */ 11813 */
11814#if ENABLE_PLATFORM_MINGW32
11815 if (!(flags & EV_EXIT) || may_have_traps IF_SUW32(|| delayexit)) {
11816 /* No, forking off a child is necessary */
11817 struct forkshell fs;
11818
11819 INT_OFF;
11820 memset(&fs, 0, sizeof(fs));
11821 fs.fpid = FS_SHELLEXEC;
11822 fs.argv = argv;
11823 fs.path = (char*)path;
11824 fs.fd[0] = cmdentry.u.index;
11825 jp = makejob(/*cmd,*/ 1);
11826 spawn_forkshell(&fs, jp, cmd, FORK_FG);
11827 break;
11828 }
11829#else
10609 if (!(flags & EV_EXIT) || may_have_traps) { 11830 if (!(flags & EV_EXIT) || may_have_traps) {
10610 /* No, forking off a child is necessary */ 11831 /* No, forking off a child is necessary */
10611 INT_OFF; 11832 INT_OFF;
@@ -10619,7 +11840,8 @@ evalcommand(union node *cmd, int flags)
10619 FORCE_INT_ON; 11840 FORCE_INT_ON;
10620 /* fall through to exec'ing external program */ 11841 /* fall through to exec'ing external program */
10621 } 11842 }
10622 shellexec(argv[0], argv, path, cmdentry.u.index); 11843#endif
11844 shellexec(argv[0], argv, path, cmdentry.u.index, FALSE);
10623 /* NOTREACHED */ 11845 /* NOTREACHED */
10624 } /* default */ 11846 } /* default */
10625 case CMDBUILTIN: 11847 case CMDBUILTIN:
@@ -10831,6 +12053,54 @@ static void popstring(void)
10831 INT_ON; 12053 INT_ON;
10832} 12054}
10833 12055
12056#if ENABLE_PLATFORM_MINGW32
12057/*
12058 * Wrapper around nonblock_immune_read() to remove CRs, but only from
12059 * CRLF pairs. The tricky part is handling a CR at the end of the buffer.
12060 */
12061static inline ssize_t
12062nonblock_immune_wrapper(struct parsefile *pf, char *buffer, size_t count)
12063{
12064 int nr, injected_cr;
12065
12066 // Inject unprocessed CR from previous read into the buffer.
12067 if (pf->cr)
12068 *buffer = '\r';
12069 retry:
12070 nr = nonblock_immune_read(pf->pf_fd, buffer + pf->cr, count - pf->cr);
12071 if (nr < 0)
12072 return nr;
12073
12074 injected_cr = pf->cr;
12075 nr += pf->cr;
12076 pf->cr = 0;
12077
12078 if (nr > 0) {
12079 nr = remove_cr(buffer, nr);
12080 // remove_cr() won't reduce size to zero, so [nr - 1] is OK.
12081 if (buffer[nr - 1] == '\r') {
12082 if (nr > 1) {
12083 // Ignore trailing CR for now: we'll deal with it later.
12084 pf->cr = 1;
12085 --nr;
12086 } else if (injected_cr) { // nr == 1
12087 // Buffer only contains an injected CR. This means the
12088 // read returned EOF. Return the buffer as-is. The
12089 // next call will detect EOF.
12090 } else {
12091 // Buffer only contains a CR from the most recent read.
12092 // Try another read, treating the CR as injected. We'll
12093 // either get more characters or EOF. Either way we
12094 // won't end up here again.
12095 pf->cr = 1;
12096 goto retry;
12097 }
12098 }
12099 }
12100 return nr;
12101}
12102#endif
12103
10834static int 12104static int
10835preadfd(void) 12105preadfd(void)
10836{ 12106{
@@ -10841,7 +12111,11 @@ preadfd(void)
10841#if ENABLE_FEATURE_EDITING 12111#if ENABLE_FEATURE_EDITING
10842 /* retry: */ 12112 /* retry: */
10843 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO) 12113 if (!iflag || g_parsefile->pf_fd != STDIN_FILENO)
12114#if ENABLE_PLATFORM_MINGW32
12115 nr = nonblock_immune_wrapper(g_parsefile, buf, IBUFSIZ - 1);
12116#else
10844 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1); 12117 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
12118#endif
10845 else { 12119 else {
10846# if ENABLE_ASH_IDLE_TIMEOUT 12120# if ENABLE_ASH_IDLE_TIMEOUT
10847 int timeout = -1; 12121 int timeout = -1;
@@ -10880,12 +12154,21 @@ preadfd(void)
10880 INT_ON; /* here non-blocked SIGINT will longjmp */ 12154 INT_ON; /* here non-blocked SIGINT will longjmp */
10881 if (nr == 0) { 12155 if (nr == 0) {
10882 /* ^C pressed, "convert" to SIGINT */ 12156 /* ^C pressed, "convert" to SIGINT */
12157# if !ENABLE_PLATFORM_MINGW32
10883 write(STDOUT_FILENO, "^C\n", 3); 12158 write(STDOUT_FILENO, "^C\n", 3);
10884 raise(SIGINT); /* here non-blocked SIGINT will longjmp */ 12159 raise(SIGINT); /* here non-blocked SIGINT will longjmp */
10885 /* raise(SIGINT) did not work! (e.g. if SIGINT 12160 /* raise(SIGINT) did not work! (e.g. if SIGINT
10886 * is SIG_IGNed on startup, it stays SIG_IGNed) 12161 * is SIG_IGNed on startup, it stays SIG_IGNed)
10887 */ 12162 */
12163# else
12164 raise_interrupt();
12165 write(STDOUT_FILENO, "^C\n", 3);
12166# endif
10888 if (trap[SIGINT]) { 12167 if (trap[SIGINT]) {
12168# if ENABLE_PLATFORM_MINGW32
12169 pending_int = 1;
12170 dotrap();
12171# endif
10889 empty_line_input: 12172 empty_line_input:
10890 buf[0] = '\n'; 12173 buf[0] = '\n';
10891 buf[1] = '\0'; 12174 buf[1] = '\0';
@@ -10914,7 +12197,11 @@ preadfd(void)
10914 } 12197 }
10915 } 12198 }
10916#else 12199#else
12200# if ENABLE_PLATFORM_MINGW32
12201 nr = nonblock_immune_wrapper(g_parsefile, buf, IBUFSIZ - 1);
12202# else
10917 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1); 12203 nr = nonblock_immune_read(g_parsefile->pf_fd, buf, IBUFSIZ - 1);
12204# endif
10918#endif 12205#endif
10919 12206
10920#if 0 /* disabled: nonblock_immune_read() handles this problem */ 12207#if 0 /* disabled: nonblock_immune_read() handles this problem */
@@ -11213,6 +12500,7 @@ popallfiles(void)
11213 unwindfiles(&basepf); 12500 unwindfiles(&basepf);
11214} 12501}
11215 12502
12503#if !ENABLE_PLATFORM_MINGW32
11216/* 12504/*
11217 * Close the file(s) that the shell is reading commands from. Called 12505 * Close the file(s) that the shell is reading commands from. Called
11218 * after a fork is done. 12506 * after a fork is done.
@@ -11226,6 +12514,7 @@ closescript(void)
11226 g_parsefile->pf_fd = 0; 12514 g_parsefile->pf_fd = 0;
11227 } 12515 }
11228} 12516}
12517#endif
11229 12518
11230/* 12519/*
11231 * Like setinputfile, but takes an open file descriptor. Call this with 12520 * Like setinputfile, but takes an open file descriptor. Call this with
@@ -11462,8 +12751,19 @@ options(int *login_sh)
11462 int val; 12751 int val;
11463 int c; 12752 int c;
11464 12753
11465 if (login_sh != NULL) /* if we came from startup code */ 12754#if ENABLE_ASH_NOCONSOLE
12755 noconsole = console_state();
12756#endif
12757 if (login_sh != NULL) { /* if we came from startup code */
11466 minusc = NULL; 12758 minusc = NULL;
12759#if ENABLE_PLATFORM_MINGW32
12760 dirarg = NULL;
12761 title = NULL;
12762# if ENABLE_SUW32
12763 delayexit = 0;
12764# endif
12765#endif
12766 }
11467 while ((p = *argptr) != NULL) { 12767 while ((p = *argptr) != NULL) {
11468 c = *p++; 12768 c = *p++;
11469 if (c != '-' && c != '+') 12769 if (c != '-' && c != '+')
@@ -11493,6 +12793,31 @@ options(int *login_sh)
11493 cflag = 1; 12793 cflag = 1;
11494 continue; 12794 continue;
11495 } 12795 }
12796#if ENABLE_PLATFORM_MINGW32
12797 /* Undocumented flags;
12798 * -d force current directory
12799 * -t title to display in console window
12800 * -N prompt user before exit
12801 * Must appear before -s or -c. */
12802 if (c == 'd' && val == 1) {
12803 if (*argptr == NULL)
12804 ash_msg_and_raise_error(bb_msg_requires_arg, "-d");
12805 dirarg = *argptr++;
12806 continue;
12807 }
12808 if (c == 't' && val == 1) {
12809 if (*argptr == NULL)
12810 ash_msg_and_raise_error(bb_msg_requires_arg, "-t");
12811 title = *argptr++;
12812 continue;
12813 }
12814# if ENABLE_SUW32
12815 if (c == 'N' && val == 1) {
12816 delayexit = 1;
12817 continue;
12818 }
12819# endif
12820#endif
11496 if (c == 's') { /* -s, +s */ 12821 if (c == 's') { /* -s, +s */
11497 sflag = 1; 12822 sflag = 1;
11498 continue; 12823 continue;
@@ -13528,6 +14853,9 @@ evalstring(char *s, int flags)
13528 int status; 14853 int status;
13529 14854
13530 s = sstrdup(s); 14855 s = sstrdup(s);
14856#if ENABLE_PLATFORM_MINGW32
14857 remove_cr(s, strlen(s)+1);
14858#endif
13531 setinputstring(s); 14859 setinputstring(s);
13532 setstackmark(&smark); 14860 setstackmark(&smark);
13533 14861
@@ -13615,7 +14943,7 @@ cmdloop(int top)
13615 int skip; 14943 int skip;
13616 14944
13617 setstackmark(&smark); 14945 setstackmark(&smark);
13618#if JOBS 14946#if JOBS || JOBS_WIN32
13619 if (doing_jobctl) 14947 if (doing_jobctl)
13620 showjobs(SHOW_CHANGED|SHOW_STDERR); 14948 showjobs(SHOW_CHANGED|SHOW_STDERR);
13621#endif 14949#endif
@@ -13623,6 +14951,9 @@ cmdloop(int top)
13623 if (iflag && top) { 14951 if (iflag && top) {
13624 inter++; 14952 inter++;
13625 chkmail(); 14953 chkmail();
14954#if ENABLE_PLATFORM_MINGW32
14955 terminal_mode(TRUE);
14956#endif
13626 } 14957 }
13627 n = parsecmd(inter); 14958 n = parsecmd(inter);
13628#if DEBUG 14959#if DEBUG
@@ -13646,8 +14977,10 @@ cmdloop(int top)
13646 } else { 14977 } else {
13647 int i; 14978 int i;
13648 14979
14980#if !ENABLE_PLATFORM_MINGW32
13649 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */ 14981 /* job_warning can only be 2,1,0. Here 2->1, 1/0->0 */
13650 job_warning >>= 1; 14982 job_warning >>= 1;
14983#endif
13651 numeof = 0; 14984 numeof = 0;
13652 i = evaltree(n, 0); 14985 i = evaltree(n, 0);
13653 if (n) 14986 if (n)
@@ -13677,7 +15010,7 @@ find_dot_file(char *basename)
13677 int len; 15010 int len;
13678 15011
13679 /* don't try this for absolute or relative paths */ 15012 /* don't try this for absolute or relative paths */
13680 if (strchr(basename, '/')) 15013 if (strchr(basename, '/') IF_PLATFORM_MINGW32(|| strchr(basename, '\\')))
13681 return basename; 15014 return basename;
13682 15015
13683 path = pathval(); 15016 path = pathval();
@@ -13842,6 +15175,7 @@ find_command(char *name, struct cmdentry *entry, int act, const char *path)
13842 struct builtincmd *bcmd; 15175 struct builtincmd *bcmd;
13843 int len; 15176 int len;
13844 15177
15178#if !ENABLE_PLATFORM_MINGW32
13845 /* If name contains a slash, don't use PATH or hash table */ 15179 /* If name contains a slash, don't use PATH or hash table */
13846 if (strchr(name, '/') != NULL) { 15180 if (strchr(name, '/') != NULL) {
13847 entry->u.index = -1; 15181 entry->u.index = -1;
@@ -13861,6 +15195,35 @@ find_command(char *name, struct cmdentry *entry, int act, const char *path)
13861 entry->cmdtype = CMDNORMAL; 15195 entry->cmdtype = CMDNORMAL;
13862 return; 15196 return;
13863 } 15197 }
15198#else /* ENABLE_PLATFORM_MINGW32 */
15199 /* If name contains a slash or drive prefix, don't use PATH or hash table */
15200 if (has_path(name)) {
15201 entry->u.index = -1;
15202 entry->cmdtype = CMDNORMAL;
15203 fullname = stack_add_ext_space(name);
15204 if (add_win32_extension(fullname)) {
15205 return;
15206 } else if (unix_path(name)) {
15207 name = (char *)bb_basename(name);
15208 if (
15209# if ENABLE_FEATURE_SH_STANDALONE
15210 find_applet_by_name_for_sh(name, path) >= 0 ||
15211# endif
15212 !find_builtin(bb_basename(name))
15213 ) {
15214 act |= DO_NOFUNC;
15215 } else if (act & DO_ABS) {
15216 entry->cmdtype = CMDUNKNOWN;
15217 return;
15218 }
15219 } else if (act & DO_ABS) {
15220 entry->cmdtype = CMDUNKNOWN;
15221 return;
15222 } else {
15223 return;
15224 }
15225 }
15226#endif /* ENABLE_PLATFORM_MINGW32 */
13864 15227
13865/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */ 15228/* #if ENABLE_FEATURE_SH_STANDALONE... moved after builtin check */
13866 15229
@@ -13915,7 +15278,7 @@ find_command(char *name, struct cmdentry *entry, int act, const char *path)
13915 15278
13916#if ENABLE_FEATURE_SH_STANDALONE 15279#if ENABLE_FEATURE_SH_STANDALONE
13917 { 15280 {
13918 int applet_no = find_applet_by_name(name); 15281 int applet_no = find_applet_by_name_for_sh(name, path);
13919 if (applet_no >= 0) { 15282 if (applet_no >= 0) {
13920 entry->cmdtype = CMDNORMAL; 15283 entry->cmdtype = CMDNORMAL;
13921 entry->u.index = -2 - applet_no; 15284 entry->u.index = -2 - applet_no;
@@ -13954,12 +15317,15 @@ find_command(char *name, struct cmdentry *entry, int act, const char *path)
13954 } 15317 }
13955 } 15318 }
13956 /* if rehash, don't redo absolute path names */ 15319 /* if rehash, don't redo absolute path names */
13957 if (fullname[0] == '/' && idx <= prev) { 15320 if (!is_relative_path(fullname) && idx <= prev) {
13958 if (idx < prev) 15321 if (idx < prev)
13959 continue; 15322 continue;
13960 TRACE(("searchexec \"%s\": no change\n", name)); 15323 TRACE(("searchexec \"%s\": no change\n", name));
13961 goto success; 15324 goto success;
13962 } 15325 }
15326#if ENABLE_PLATFORM_MINGW32
15327 add_win32_extension(fullname);
15328#endif
13963 while (stat(fullname, &statb) < 0) { 15329 while (stat(fullname, &statb) < 0) {
13964#ifdef SYSV 15330#ifdef SYSV
13965 if (errno == EINTR) 15331 if (errno == EINTR)
@@ -14098,19 +15464,45 @@ trapcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14098 if (LONE_DASH(action)) 15464 if (LONE_DASH(action))
14099 action = NULL; 15465 action = NULL;
14100 else { 15466 else {
15467#if !ENABLE_PLATFORM_MINGW32
14101 if (action[0]) /* not NULL and not "" and not "-" */ 15468 if (action[0]) /* not NULL and not "" and not "-" */
14102 may_have_traps = 1; 15469 may_have_traps = 1;
15470#endif
14103 action = ckstrdup(action); 15471 action = ckstrdup(action);
14104 } 15472 }
14105 } 15473 }
14106 free(trap[signo]); 15474 free(trap[signo]);
14107 trap[signo] = action; 15475 trap[signo] = action;
15476#if ENABLE_PLATFORM_MINGW32
15477 if (signo == SIGINT) {
15478 // trap '' INT disables Ctrl-C, anything else enables it
15479 if (action && action[0] == '\0') {
15480 SetConsoleCtrlHandler(NULL, TRUE);
15481# if ENABLE_FEATURE_EDITING
15482 if (line_input_state) {
15483 line_input_state->flags |= IGNORE_CTRL_C;
15484 }
15485# endif
15486 } else {
15487 SetConsoleCtrlHandler(NULL, FALSE);
15488# if ENABLE_FEATURE_EDITING
15489 if (line_input_state) {
15490 line_input_state->flags &= ~IGNORE_CTRL_C;
15491 }
15492# endif
15493 }
15494 }
15495#else
14108 if (signo != 0 && signo < NSIG) 15496 if (signo != 0 && signo < NSIG)
14109 setsignal(signo); 15497 setsignal(signo);
15498#endif
14110 INT_ON; 15499 INT_ON;
14111 next: 15500 next:
14112 ap++; 15501 ap++;
14113 } 15502 }
15503#if ENABLE_PLATFORM_MINGW32
15504 may_have_traps = trap[SIGINT] && trap[SIGINT][0] != '\0';
15505#endif
14114 return exitcode; 15506 return exitcode;
14115} 15507}
14116 15508
@@ -14139,10 +15531,12 @@ helpcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14139 { 15531 {
14140 const char *a = applet_names; 15532 const char *a = applet_names;
14141 while (*a) { 15533 while (*a) {
14142 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a); 15534 if (prefer_applet(a, pathval())) {
14143 if (col > 60) { 15535 col += out1fmt("%c%s", ((col == 0) ? '\t' : ' '), a);
14144 out1fmt("\n"); 15536 if (col > 60) {
14145 col = 0; 15537 out1fmt("\n");
15538 col = 0;
15539 }
14146 } 15540 }
14147 while (*a++ != '\0') 15541 while (*a++ != '\0')
14148 continue; 15542 continue;
@@ -14204,7 +15598,24 @@ exportcmd(int argc UNUSED_PARAM, char **argv)
14204 } else { 15598 } else {
14205 vp = *findvar(name); 15599 vp = *findvar(name);
14206 if (vp) { 15600 if (vp) {
15601#if ENABLE_PLATFORM_MINGW32
15602 if (is_bb_var(name) == BB_VAR_EXACT) {
15603 if (flag_off == ~VEXPORT)
15604 unsetenv(name);
15605 else if (flag == VEXPORT && !(vp->flags & VUNSET))
15606 putenv(vp->var_text);
15607 }
15608#endif
14207 vp->flags = ((vp->flags | flag) & flag_off); 15609 vp->flags = ((vp->flags | flag) & flag_off);
15610#if ENABLE_PLATFORM_MINGW32
15611 /* Unexporting a variable imported from the
15612 * environment restores its original value and
15613 * removes the VIMPORT flag. */
15614 if ((vp->flags & VIMPORT) && (flag_off == ~VEXPORT)) {
15615 vp->flags &= ~VIMPORT;
15616 p = getenv(name);
15617 } else
15618#endif
14208 continue; 15619 continue;
14209 } 15620 }
14210 } 15621 }
@@ -14295,6 +15706,21 @@ timescmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14295 return 0; 15706 return 0;
14296} 15707}
14297 15708
15709#if ENABLE_PLATFORM_MINGW32
15710static int FAST_FUNC
15711titlecmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
15712{
15713 if (*argptr == NULL) {
15714 char buffer[256];
15715 if (get_title(buffer, sizeof(buffer)))
15716 puts(buffer);
15717 } else {
15718 set_title(*argptr);
15719 }
15720 return 0;
15721}
15722#endif
15723
14298#if ENABLE_FEATURE_SH_MATH 15724#if ENABLE_FEATURE_SH_MATH
14299/* 15725/*
14300 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell. 15726 * The let builtin. Partially stolen from GNU Bash, the Bourne Again SHell.
@@ -14387,6 +15813,7 @@ readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14387 r = shell_builtin_read(&params); 15813 r = shell_builtin_read(&params);
14388 INT_ON; 15814 INT_ON;
14389 15815
15816#if !ENABLE_PLATFORM_MINGW32
14390 if ((uintptr_t)r == 1 && errno == EINTR) { 15817 if ((uintptr_t)r == 1 && errno == EINTR) {
14391 /* To get SIGCHLD: sleep 1 & read x; echo $x 15818 /* To get SIGCHLD: sleep 1 & read x; echo $x
14392 * Correct behavior is to not exit "read" 15819 * Correct behavior is to not exit "read"
@@ -14395,6 +15822,34 @@ readcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14395 goto again; 15822 goto again;
14396 } 15823 }
14397 15824
15825 if ((uintptr_t)r == 2) /* -t SEC timeout? */
15826 /* bash: "The exit status is greater than 128 if the timeout is exceeded." */
15827 /* The actual value observed with bash 5.2.15: */
15828 return 128 + SIGALRM;
15829#else /* ENABLE_PLATFORM_MINGW32 */
15830 if ((uintptr_t)r == 2) {
15831 /* Timeout, return 128 + SIGALRM */
15832 return 142;
15833 } else if ((uintptr_t)r == 3) {
15834 /* ^C pressed, propagate event */
15835 if (trap[SIGINT]) {
15836 write(STDOUT_FILENO, "^C", 2);
15837 pending_int = 1;
15838 dotrap();
15839 if (!(rootshell && iflag))
15840 return (uintptr_t)0;
15841 else
15842 goto again;
15843 } else if (iflag) {
15844 raise_interrupt();
15845 } else {
15846 GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
15847 exitshell();
15848 }
15849 return (uintptr_t)r;
15850 }
15851#endif
15852
14398 if ((uintptr_t)r > 1) 15853 if ((uintptr_t)r > 1)
14399 ash_msg_and_raise_error(r); 15854 ash_msg_and_raise_error(r);
14400 15855
@@ -14455,6 +15910,9 @@ umaskcmd(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
14455 if (!isdigit(modestr[0])) 15910 if (!isdigit(modestr[0]))
14456 mask ^= 0777; 15911 mask ^= 0777;
14457 umask(mask); 15912 umask(mask);
15913#if ENABLE_PLATFORM_MINGW32
15914 setvareq(xasprintf("BB_UMASK=0%o", mask), VEXPORT|VNOSAVE);
15915#endif
14458 } 15916 }
14459 return 0; 15917 return 0;
14460} 15918}
@@ -14520,8 +15978,25 @@ exitshell(void)
14520 char *p; 15978 char *p;
14521 15979
14522#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT 15980#if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
14523 save_history(line_input_state); /* may be NULL */ 15981 if (line_input_state) {
15982 const char *hp;
15983# if ENABLE_FEATURE_SH_HISTFILESIZE
15984// in bash:
15985// HISTFILESIZE controls the on-disk history file size (in lines, 0=no history):
15986// "When this variable is assigned a value, the history file is truncated, if necessary"
15987// but we do it only at exit, not on assignment:
15988 /* Use HISTFILESIZE to limit file size */
15989 hp = lookupvar("HISTFILESIZE");
15990 if (hp)
15991 line_input_state->max_history = size_from_HISTFILESIZE(hp);
15992# endif
15993 /* HISTFILE: "If unset, the command history is not saved when a shell exits." */
15994 hp = lookupvar("HISTFILE");
15995 line_input_state->hist_file = hp;
15996 save_history(line_input_state); /* no-op if hist_file is NULL or "" */
15997 }
14524#endif 15998#endif
15999
14525 savestatus = exitstatus; 16000 savestatus = exitstatus;
14526 TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus)); 16001 TRACE(("pid %d, exitshell(%d)\n", getpid(), savestatus));
14527 if (setjmp(loc.loc)) 16002 if (setjmp(loc.loc))
@@ -14538,6 +16013,13 @@ exitshell(void)
14538 /*free(p); - we'll exit soon */ 16013 /*free(p); - we'll exit soon */
14539 } 16014 }
14540 out: 16015 out:
16016#if ENABLE_SUW32
16017 if (delayexit) {
16018#define EXIT_MSG "Press any key to exit..."
16019 console_write(EXIT_MSG, sizeof(EXIT_MSG) - 1);
16020 _getch();
16021 }
16022#endif
14541 exitreset(); 16023 exitreset();
14542 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}". 16024 /* dash wraps setjobctl(0) in "if (setjmp(loc.loc) == 0) {...}".
14543 * our setjobctl(0) does not panic if tcsetpgrp fails inside it. 16025 * our setjobctl(0) does not panic if tcsetpgrp fails inside it.
@@ -14548,22 +16030,97 @@ exitshell(void)
14548 /* NOTREACHED */ 16030 /* NOTREACHED */
14549} 16031}
14550 16032
16033#if ENABLE_PLATFORM_MINGW32
16034/* We need to see if HOME is *really* unset */
16035# undef getenv
16036static void setvar_if_unset(const char *key, const char *value)
16037{
16038 if (!getenv(key) || getuid() == 0)
16039 setvar(key, value, VEXPORT);
16040}
16041#endif
16042
14551/* Don't inline: conserve stack of caller from having our locals too */ 16043/* Don't inline: conserve stack of caller from having our locals too */
14552static NOINLINE void 16044static NOINLINE void
14553init(void) 16045init(void)
14554{ 16046{
16047#if ENABLE_PLATFORM_MINGW32
16048 int import = 0;
16049#else
14555 /* we will never free this */ 16050 /* we will never free this */
14556 basepf.next_to_pgetc = basepf.buf = ckzalloc(IBUFSIZ); 16051 basepf.next_to_pgetc = basepf.buf = ckzalloc(IBUFSIZ);
14557 basepf.linno = 1; 16052 basepf.linno = 1;
14558 16053
14559 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */ 16054 sigmode[SIGCHLD - 1] = S_DFL; /* ensure we install handler even if it is SIG_IGNed */
14560 setsignal(SIGCHLD); 16055 setsignal(SIGCHLD);
16056#endif
14561 16057
14562 { 16058 {
14563 char **envp; 16059 char **envp;
14564 const char *p; 16060 const char *p;
14565 16061
14566 initvar(); 16062 initvar();
16063
16064#if ENABLE_PLATFORM_MINGW32
16065 /*
16066 * case insensitive env names from Windows world
16067 *
16068 * Some standard env names such as PATH is named Path and so on
16069 * ash itself is case sensitive, so "Path" will confuse it, as
16070 * MSVC getenv() is case insensitive.
16071 *
16072 * We may end up having both Path and PATH. Then Path will be chosen
16073 * because it appears first.
16074 */
16075 if (windows_env()) {
16076 /*
16077 * If we get here it's because the environment suggests we
16078 * haven't been invoked from an earlier instance of BusyBox.
16079 */
16080 char *start, *end;
16081 struct passwd *pw;
16082
16083 /* mintty sets HOME: unset it */
16084 const char *tty = getenv("TERM_PROGRAM");
16085 if (tty && strcmp(tty, "mintty") == 0) {
16086 unsetenv("HOME");
16087 }
16088
16089 import = VIMPORT;
16090 for (envp = environ; envp && *envp; envp++) {
16091 if (!(end=strchr(*envp, '=')))
16092 continue;
16093
16094 /* check for invalid characters in name */
16095 start = (char *)endofname(*envp);
16096 if (*start != '=') {
16097 /* Make a copy of the original variable */
16098 setvareq(xstrdup(*envp), VEXPORT|VNOSAVE);
16099
16100 /* Replace invalid characters with underscores */
16101 for (; start < end; start++) {
16102 if (!isalnum(*start)) {
16103 *start = '_';
16104 }
16105 }
16106 }
16107
16108 /* make all variable names uppercase */
16109 for (start = *envp;start < end;start++)
16110 *start = toupper(*start);
16111 }
16112
16113 /* Initialise some variables normally set at login, but
16114 * only if someone hasn't already set them or we're root. */
16115 pw = getpwuid(getuid());
16116 if (pw) {
16117 setvar_if_unset("USER", pw->pw_name);
16118 setvar_if_unset("LOGNAME", pw->pw_name);
16119 setvar_if_unset("HOME", pw->pw_dir);
16120 }
16121 setvar_if_unset("SHELL", DEFAULT_SHELL);
16122 }
16123#endif
14567 for (envp = environ; envp && *envp; envp++) { 16124 for (envp = environ; envp && *envp; envp++) {
14568/* Used to have 16125/* Used to have
14569 * p = endofname(*envp); 16126 * p = endofname(*envp);
@@ -14577,7 +16134,11 @@ init(void)
14577 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this 16134 * os.execv("ash", [ 'ash', '-c', 'env | grep test-test' ]) # breaks this
14578 */ 16135 */
14579 if (strchr(*envp, '=')) { 16136 if (strchr(*envp, '=')) {
16137#if !ENABLE_PLATFORM_MINGW32
14580 setvareq(*envp, VEXPORT|VTEXTFIXED); 16138 setvareq(*envp, VEXPORT|VTEXTFIXED);
16139#else
16140 setvareq(*envp, VEXPORT|import);
16141#endif
14581 } 16142 }
14582 } 16143 }
14583 16144
@@ -14628,7 +16189,11 @@ procargs(char **argv)
14628 int login_sh; 16189 int login_sh;
14629 16190
14630 xargv = argv; 16191 xargv = argv;
16192#if ENABLE_PLATFORM_MINGW32
16193 login_sh = applet_name[0] == 'l';
16194#else
14631 login_sh = xargv[0] && xargv[0][0] == '-'; 16195 login_sh = xargv[0] && xargv[0][0] == '-';
16196#endif
14632#if NUM_SCRIPTS > 0 16197#if NUM_SCRIPTS > 0
14633 if (minusc) 16198 if (minusc)
14634 goto setarg0; 16199 goto setarg0;
@@ -14652,7 +16217,9 @@ procargs(char **argv)
14652 } 16217 }
14653 if (iflag == 2 /* no explicit -i given */ 16218 if (iflag == 2 /* no explicit -i given */
14654 && sflag == 1 /* -s given (or implied) */ 16219 && sflag == 1 /* -s given (or implied) */
16220#if !ENABLE_PLATFORM_MINGW32
14655 && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */ 16221 && !minusc /* bash compat: ash -sc 'echo $-' is not interactive (dash is) */
16222#endif
14656 && isatty(0) && isatty(1) /* we are on tty */ 16223 && isatty(0) && isatty(1) /* we are on tty */
14657 ) { 16224 ) {
14658 iflag = 1; 16225 iflag = 1;
@@ -14672,6 +16239,9 @@ procargs(char **argv)
14672 goto setarg0; 16239 goto setarg0;
14673 } else if (!sflag) { 16240 } else if (!sflag) {
14674 setinputfile(*xargv, 0); 16241 setinputfile(*xargv, 0);
16242#if ENABLE_PLATFORM_MINGW32
16243 bs_to_slash(*xargv);
16244#endif
14675 setarg0: 16245 setarg0:
14676 arg0 = *xargv++; 16246 arg0 = *xargv++;
14677 commandname = arg0; 16247 commandname = arg0;
@@ -14695,8 +16265,10 @@ procargs(char **argv)
14695 * NB: must do it before setting up signals (in optschanged()) 16265 * NB: must do it before setting up signals (in optschanged())
14696 * and reading .profile etc (after we return from here): 16266 * and reading .profile etc (after we return from here):
14697 */ 16267 */
16268#if !ENABLE_PLATFORM_MINGW32
14698 if (iflag) 16269 if (iflag)
14699 signal(SIGHUP, SIG_DFL); 16270 signal(SIGHUP, SIG_DFL);
16271#endif
14700 16272
14701 optschanged(); 16273 optschanged();
14702 16274
@@ -14741,9 +16313,25 @@ int ash_main(int argc UNUSED_PARAM, char **argv)
14741 struct stackmark smark; 16313 struct stackmark smark;
14742 int login_sh; 16314 int login_sh;
14743 16315
16316#if ENABLE_PLATFORM_MINGW32
16317 INIT_G_memstack();
16318
16319 /* from init() */
16320 basepf.next_to_pgetc = basepf.buf = ckzalloc(IBUFSIZ);
16321 basepf.linno = 1;
16322
16323 if (argc == 3 && !strcmp(argv[1], "--fs")) {
16324 forkshell_init(argv[2]);
16325 /* only reached in case of error */
16326 bb_error_msg_and_die("forkshell failed");
16327 }
16328#endif
16329
14744 /* Initialize global data */ 16330 /* Initialize global data */
14745 INIT_G_misc(); 16331 INIT_G_misc();
16332#if !ENABLE_PLATFORM_MINGW32
14746 INIT_G_memstack(); 16333 INIT_G_memstack();
16334#endif
14747 INIT_G_var(); 16335 INIT_G_var();
14748#if ENABLE_ASH_ALIAS 16336#if ENABLE_ASH_ALIAS
14749 INIT_G_alias(); 16337 INIT_G_alias();
@@ -14789,6 +16377,10 @@ int ash_main(int argc UNUSED_PARAM, char **argv)
14789 init(); 16377 init();
14790 setstackmark(&smark); 16378 setstackmark(&smark);
14791 16379
16380#if ENABLE_PLATFORM_MINGW32
16381 SetConsoleCtrlHandler(ctrl_handler, TRUE);
16382#endif
16383
14792#if NUM_SCRIPTS > 0 16384#if NUM_SCRIPTS > 0
14793 if (argc < 0) 16385 if (argc < 0)
14794 /* Non-NULL minusc tells procargs that an embedded script is being run */ 16386 /* Non-NULL minusc tells procargs that an embedded script is being run */
@@ -14800,11 +16392,45 @@ int ash_main(int argc UNUSED_PARAM, char **argv)
14800 trace_puts_args(argv); 16392 trace_puts_args(argv);
14801#endif 16393#endif
14802 16394
16395#if ENABLE_PLATFORM_MINGW32
16396 if (!dirarg && !login_sh && iflag) {
16397 char *cwd = getcwd(NULL, 0);
16398 if (cwd) {
16399 chdir(cwd);
16400 setpwd(NULL, 0);
16401 free(cwd);
16402 }
16403 }
16404
16405 if (title)
16406 set_title(title);
16407#endif
16408
14803 if (login_sh) { 16409 if (login_sh) {
14804 const char *hp; 16410 const char *hp;
14805 16411
16412#if ENABLE_PLATFORM_MINGW32
16413 if (!dirarg) {
16414 hp = lookupvar("HOME");
16415 if (hp == NULL || *hp == '\0')
16416 hp = xgetpwuid(getuid())->pw_dir;
16417 chdir(hp);
16418 setpwd(NULL, 0);
16419 }
16420#endif
16421
14806 state = 1; 16422 state = 1;
16423#if ENABLE_PLATFORM_MINGW32
16424 hp = concat_path_file(get_system_drive(), "/etc/profile");
16425 read_profile(hp);
16426 free((void *)hp);
16427
16428 hp = exe_relative_path("/etc/profile");
16429 read_profile(hp);
16430 free((void *)hp);
16431#else
14807 read_profile("/etc/profile"); 16432 read_profile("/etc/profile");
16433#endif
14808 state1: 16434 state1:
14809 state = 2; 16435 state = 2;
14810 hp = lookupvar("HOME"); 16436 hp = lookupvar("HOME");
@@ -14813,10 +16439,18 @@ int ash_main(int argc UNUSED_PARAM, char **argv)
14813 } 16439 }
14814 state2: 16440 state2:
14815 state = 3; 16441 state = 3;
16442#if ENABLE_PLATFORM_MINGW32
16443 if (dirarg) {
16444 chdir(dirarg);
16445 setpwd(NULL, 0);
16446 }
16447#endif
14816 if (iflag 16448 if (iflag
16449#if ENABLE_PLATFORM_POSIX
14817#ifndef linux 16450#ifndef linux
14818 && getuid() == geteuid() && getgid() == getegid() 16451 && getuid() == geteuid() && getgid() == getegid()
14819#endif 16452#endif
16453#endif
14820 ) { 16454 ) {
14821 const char *shinit = lookupvar("ENV"); 16455 const char *shinit = lookupvar("ENV");
14822 if (shinit != NULL && *shinit != '\0') 16456 if (shinit != NULL && *shinit != '\0')
@@ -14841,7 +16475,11 @@ int ash_main(int argc UNUSED_PARAM, char **argv)
14841 // ash -sc 'echo $-' 16475 // ash -sc 'echo $-'
14842 // continue reading input from stdin after running 'echo'. 16476 // continue reading input from stdin after running 'echo'.
14843 // bash does not do this: it prints "hBcs" and exits. 16477 // bash does not do this: it prints "hBcs" and exits.
16478#if !ENABLE_PLATFORM_MINGW32
14844 evalstring(minusc, EV_EXIT); 16479 evalstring(minusc, EV_EXIT);
16480#else
16481 evalstring(minusc, sflag ? 0 : EV_EXIT);
16482#endif
14845 } 16483 }
14846 16484
14847 if (sflag || minusc == NULL) { 16485 if (sflag || minusc == NULL) {
@@ -14862,7 +16500,12 @@ int ash_main(int argc UNUSED_PARAM, char **argv)
14862 if (hp) 16500 if (hp)
14863 line_input_state->hist_file = xstrdup(hp); 16501 line_input_state->hist_file = xstrdup(hp);
14864# if ENABLE_FEATURE_SH_HISTFILESIZE 16502# if ENABLE_FEATURE_SH_HISTFILESIZE
14865 hp = lookupvar("HISTFILESIZE"); 16503 hp = lookupvar("HISTSIZE");
16504 /* Using HISTFILESIZE above to limit max_history would be WRONG:
16505 * users may set HISTFILESIZE=0 in their profile scripts
16506 * to prevent _saving_ of history files, but still want to have
16507 * non-zero history limit for in-memory list.
16508 */
14866 line_input_state->max_history = size_from_HISTFILESIZE(hp); 16509 line_input_state->max_history = size_from_HISTFILESIZE(hp);
14867# endif 16510# endif
14868 } 16511 }
@@ -14884,6 +16527,1101 @@ int ash_main(int argc UNUSED_PARAM, char **argv)
14884 /* NOTREACHED */ 16527 /* NOTREACHED */
14885} 16528}
14886 16529
16530#if ENABLE_PLATFORM_MINGW32
16531static void
16532forkshell_openhere(struct forkshell *fs)
16533{
16534 const char *p = fs->path;
16535 size_t len = strlen(p);
16536 int pip[2];
16537
16538 pip[0] = fs->fd[0];
16539 pip[1] = fs->fd[1];
16540
16541 TRACE(("ash: subshell: %s\n",__PRETTY_FUNCTION__));
16542
16543 close(pip[0]);
16544 ignoresig(SIGINT); //signal(SIGINT, SIG_IGN);
16545 ignoresig(SIGQUIT); //signal(SIGQUIT, SIG_IGN);
16546 ignoresig(SIGHUP); //signal(SIGHUP, SIG_IGN);
16547 ignoresig(SIGTSTP); //signal(SIGTSTP, SIG_IGN);
16548 signal(SIGPIPE, SIG_DFL);
16549 xwrite(pip[1], p, len);
16550 _exit_SUCCESS();
16551}
16552
16553static void
16554forkshell_evalbackcmd(struct forkshell *fs)
16555{
16556#if BASH_PROCESS_SUBST
16557 /* determine end of pipe used by parent (ip) and child (ic) */
16558 const int ctl = fs->fd[2];
16559 const int ip = (ctl == CTLTOPROC);
16560 const int ic = !(ctl == CTLTOPROC);
16561#else
16562 const int ip = 0;
16563 const int ic = 1;
16564#endif
16565 union node *n = fs->n;
16566 int pip[2];
16567
16568 pip[ip] = fs->fd[ip];
16569 pip[ic] = fs->fd[ic];
16570
16571 FORCE_INT_ON;
16572 close(pip[ip]);
16573 if (pip[ic] != ic) {
16574 /*close(ic);*/
16575 dup2_or_raise(pip[ic], ic);
16576 close(pip[ic]);
16577 }
16578 eflag = 0;
16579 ifsfree();
16580 evaltreenr(n, EV_EXIT);
16581 /* NOTREACHED */
16582}
16583
16584static void
16585forkshell_evalsubshell(struct forkshell *fs)
16586{
16587 union node *n = fs->n;
16588 int flags = fs->flags;
16589
16590 TRACE(("ash: subshell: %s\n",__PRETTY_FUNCTION__));
16591 INT_ON;
16592 flags |= EV_EXIT;
16593 if (fs->mode)
16594 flags &= ~EV_TESTED;
16595 expredir(n->nredir.redirect);
16596 redirect(n->nredir.redirect, 0);
16597 evaltreenr(n->nredir.n, flags);
16598 /* never returns */
16599}
16600
16601static void
16602forkshell_evalpipe(struct forkshell *fs)
16603{
16604 union node *n = fs->n;
16605 int flags = fs->flags;
16606 int prevfd = fs->fd[2];
16607 int pip[2] = {fs->fd[0], fs->fd[1]};
16608
16609 TRACE(("ash: subshell: %s\n",__PRETTY_FUNCTION__));
16610 INT_ON;
16611 if (pip[1] >= 0) {
16612 close(pip[0]);
16613 }
16614 if (prevfd > 0) {
16615 dup2(prevfd, 0);
16616 close(prevfd);
16617 }
16618 if (pip[1] > 1) {
16619 dup2(pip[1], 1);
16620 close(pip[1]);
16621 }
16622 evaltreenr(n, flags);
16623}
16624
16625static void
16626forkshell_shellexec(struct forkshell *fs)
16627{
16628 int idx = fs->fd[0];
16629 char **argv = fs->argv;
16630 char *path = fs->path;
16631
16632 FORCE_INT_ON;
16633 shellexec(argv[0], argv, path, idx, TRUE);
16634}
16635
16636static void
16637forkshell_child(struct forkshell *fs)
16638{
16639 switch ( fs->fpid ) {
16640 case FS_OPENHERE:
16641 forkshell_openhere(fs);
16642 break;
16643 case FS_EVALBACKCMD:
16644 forkshell_evalbackcmd(fs);
16645 break;
16646 case FS_EVALSUBSHELL:
16647 forkshell_evalsubshell(fs);
16648 break;
16649 case FS_EVALPIPE:
16650 forkshell_evalpipe(fs);
16651 break;
16652 case FS_SHELLEXEC:
16653 forkshell_shellexec(fs);
16654 break;
16655 }
16656}
16657
16658/*
16659 * Reinitialise the builtin environment variables in varinit. Their
16660 * current settings have been copied from the parent in vartab. Look
16661 * these up using the names from varinit_data, copy the details from
16662 * vartab to varinit and replace the old copy in vartab with the new
16663 * one in varinit.
16664 *
16665 * Also reinitialise the function pointers and line number variable.
16666 */
16667static void
16668reinitvar(void)
16669{
16670 int i;
16671 const char *name;
16672 struct var **old;
16673
16674 for (i=0; i<ARRAY_SIZE(varinit); ++i) {
16675 if (i == LINENO_INDEX)
16676 name = "LINENO=";
16677 else if (i == FUNCNAME_INDEX)
16678 name = "FUNCNAME=";
16679 else
16680 name = varinit_data[i].var_text;
16681 if ((old = findvar(name)) != NULL) {
16682 varinit[i] = **old;
16683 *old = varinit+i;
16684 }
16685 varinit[i].var_func = varinit_data[i].var_func;
16686 }
16687 vlineno.var_text = linenovar;
16688 vfuncname.var_text = funcnamevar;
16689}
16690
16691static void
16692spawn_forkshell(struct forkshell *fs, struct job *jp, union node *n, int mode)
16693{
16694 struct forkshell *new;
16695 char buf[32];
16696 const char *argv[] = { "sh", "--fs", NULL, NULL };
16697 intptr_t ret;
16698
16699 new = forkshell_prepare(fs);
16700 if (new == NULL)
16701 goto fail;
16702
16703 new->mode = mode;
16704 new->nprocs = jp == NULL ? 0 : jp->nprocs;
16705#if JOBS_WIN32
16706 new->jpnull = jp == NULL;
16707#endif
16708 sprintf(buf, "%p", new->hMapFile);
16709 argv[2] = buf;
16710 ret = spawnve(P_NOWAIT, bb_busybox_exec_path, (char *const *)argv, NULL);
16711 CloseHandle(new->hMapFile);
16712 UnmapViewOfFile(new);
16713 if (ret == -1) {
16714 fail:
16715 if (jp)
16716 freejob(jp);
16717 ash_msg_and_raise_error("unable to spawn shell");
16718 }
16719 forkparent(jp, n, mode, (HANDLE)ret);
16720}
16721
16722/*
16723 * forkshell_prepare() and friends
16724 *
16725 * The sequence is as follows:
16726 * - funcblocksize is initialized
16727 * - forkshell_size(fs) is called to calculate the exact memory needed
16728 * - a new struct is allocated
16729 * - funcblock, funcstring, relocate are initialized from the new block
16730 * - forkshell_copy(fs) is called to copy recursively everything over
16731 * it will record all relocations along the way
16732 *
16733 * When this memory is mapped elsewhere, pointer fixup will be needed
16734 */
16735
16736/* redefine without test that fs_size is nonzero */
16737#undef SAVE_PTR
16738#undef SAVE_PTR2
16739#undef SAVE_PTR3
16740#define SAVE_PTR(dst,note,flag) {MARK_PTR(dst,note,flag);}
16741
16742static int align_len(const char *s)
16743{
16744 return s ? SHELL_ALIGN(strlen(s)+1) : 0;
16745}
16746
16747struct datasize {
16748 int funcblocksize;
16749 int funcstringsize;
16750};
16751
16752#define SLIST_SIZE_BEGIN(name,type) \
16753static struct datasize \
16754name(struct datasize ds, type *p) \
16755{ \
16756 while (p) { \
16757 ds.funcblocksize += sizeof(type);
16758 /* do something here with p */
16759#define SLIST_SIZE_END() \
16760 p = p->next; \
16761 } \
16762 return ds; \
16763}
16764
16765#define SLIST_COPY_BEGIN(name,type) \
16766static type * \
16767name(type *vp) \
16768{ \
16769 type *start; \
16770 type **vpp; \
16771 vpp = &start; \
16772 while (vp) { \
16773 *vpp = funcblock; \
16774 funcblock = (char *) funcblock + sizeof(type);
16775 /* do something here with vpp and vp */
16776#define SLIST_COPY_END() \
16777 SAVE_PTR((*vpp)->next, "(*vpp)->next", NO_FREE); \
16778 vp = vp->next; \
16779 vpp = &(*vpp)->next; \
16780 } \
16781 *vpp = NULL; \
16782 return start; \
16783}
16784
16785/*
16786 * struct var
16787 */
16788SLIST_SIZE_BEGIN(var_size,struct var)
16789ds.funcstringsize += align_len(p->var_text);
16790SLIST_SIZE_END()
16791
16792SLIST_COPY_BEGIN(var_copy,struct var)
16793(*vpp)->var_text = nodeckstrdup(vp->var_text);
16794(*vpp)->flags = vp->flags;
16795(*vpp)->var_func = NULL;
16796SAVE_PTR((*vpp)->var_text, xasprintf("(*vpp)->var_text '%s'", vp->var_text ?: "NULL"), FREE);
16797SLIST_COPY_END()
16798
16799/*
16800 * struct tblentry
16801 */
16802static struct datasize
16803tblentry_size(struct datasize ds, struct tblentry *tep)
16804{
16805 while (tep) {
16806 ds.funcblocksize += sizeof(struct tblentry) + align_len(tep->cmdname);
16807 /* CMDBUILTIN, e->param.cmd needs no pointer relocation */
16808 if (tep->cmdtype == CMDFUNCTION) {
16809 ds.funcblocksize += offsetof(struct funcnode, n);
16810 ds.funcblocksize = calcsize(ds.funcblocksize, &tep->param.func->n);
16811 }
16812 tep = tep->next;
16813 }
16814 return ds;
16815}
16816
16817static struct tblentry *
16818tblentry_copy(struct tblentry *tep)
16819{
16820 struct tblentry *start;
16821 struct tblentry **newp;
16822 int size;
16823
16824 newp = &start;
16825 while (tep) {
16826 *newp = funcblock;
16827 size = sizeof(struct tblentry) + align_len(tep->cmdname);
16828
16829 funcblock = (char *) funcblock + size;
16830 memcpy(*newp, tep, sizeof(struct tblentry)+strlen(tep->cmdname));
16831 switch (tep->cmdtype) {
16832 case CMDBUILTIN:
16833 /* Save index of builtin, not pointer; fixed by forkshell_init() */
16834 (*newp)->param.index = tep->param.cmd - builtintab;
16835 break;
16836 case CMDFUNCTION:
16837 (*newp)->param.func = funcblock;
16838 funcblock = (char *) funcblock + offsetof(struct funcnode, n);
16839 copynode(&tep->param.func->n);
16840 SAVE_PTR((*newp)->param.func, "param.func", NO_FREE);
16841 break;
16842 default:
16843 break;
16844 }
16845 SAVE_PTR((*newp)->next, xasprintf("cmdname '%s'", tep->cmdname), FREE);
16846 tep = tep->next;
16847 newp = &(*newp)->next;
16848 }
16849 *newp = NULL;
16850 return start;
16851}
16852
16853static struct datasize
16854cmdtable_size(struct datasize ds)
16855{
16856 int i;
16857 ds.funcblocksize += sizeof(struct tblentry *)*CMDTABLESIZE;
16858 for (i = 0; i < CMDTABLESIZE; i++)
16859 ds = tblentry_size(ds, cmdtable[i]);
16860 return ds;
16861}
16862
16863static struct tblentry **
16864cmdtable_copy(void)
16865{
16866 struct tblentry **new = funcblock;
16867 int i;
16868
16869 funcblock = (char *) funcblock + sizeof(struct tblentry *)*CMDTABLESIZE;
16870 for (i = 0; i < CMDTABLESIZE; i++) {
16871 new[i] = tblentry_copy(cmdtable[i]);
16872 SAVE_PTR(new[i], xasprintf("cmdtable[%d]", i), FREE);
16873 }
16874 return new;
16875}
16876
16877#if ENABLE_ASH_ALIAS
16878/*
16879 * struct alias
16880 */
16881SLIST_SIZE_BEGIN(alias_size,struct alias)
16882ds.funcstringsize += align_len(p->name);
16883ds.funcstringsize += align_len(p->val);
16884SLIST_SIZE_END()
16885
16886SLIST_COPY_BEGIN(alias_copy,struct alias)
16887(*vpp)->name = nodeckstrdup(vp->name);
16888(*vpp)->val = nodeckstrdup(vp->val);
16889(*vpp)->flag = vp->flag;
16890SAVE_PTR((*vpp)->name, xasprintf("(*vpp)->name '%s'", vp->name ?: "NULL"), FREE);
16891SAVE_PTR((*vpp)->val, xasprintf("(*vpp)->val '%s'", vp->val ?: "NULL"), FREE);
16892SLIST_COPY_END()
16893
16894static struct datasize
16895atab_size(struct datasize ds)
16896{
16897 int i;
16898 ds.funcblocksize += sizeof(struct alias *)*ATABSIZE;
16899 for (i = 0; i < ATABSIZE; i++)
16900 ds = alias_size(ds, atab[i]);
16901 return ds;
16902}
16903
16904static struct alias **
16905atab_copy(void)
16906{
16907 struct alias **new = funcblock;
16908 int i;
16909
16910 funcblock = (char *) funcblock + sizeof(struct alias *)*ATABSIZE;
16911 for (i = 0; i < ATABSIZE; i++) {
16912 new[i] = alias_copy(atab[i]);
16913 SAVE_PTR(new[i], xasprintf("atab[%d]", i), FREE);
16914 }
16915 return new;
16916}
16917#endif
16918
16919/*
16920 * char **
16921 */
16922static struct datasize
16923argv_size(struct datasize ds, char **p)
16924{
16925 if (p) {
16926 while (*p) {
16927 ds.funcblocksize += sizeof(char *);
16928 ds.funcstringsize += align_len(*p);
16929 p++;
16930 }
16931 // Allow two extra elements for tryexec().
16932 ds.funcblocksize += 3 * sizeof(char *);
16933 }
16934 return ds;
16935}
16936
16937static char **
16938argv_copy(char **p)
16939{
16940 char **new, **start = funcblock;
16941#if FORKSHELL_DEBUG
16942 int i = 0;
16943#endif
16944
16945 if (p) {
16946 // Allow two extra elements for tryexec().
16947 funcblock = (char *) funcblock + 2 * sizeof(char *);
16948 while (*p) {
16949 new = funcblock;
16950 funcblock = (char *) funcblock + sizeof(char *);
16951 *new = nodeckstrdup(*p);
16952 SAVE_PTR(*new, xasprintf("argv[%d] '%s'", i++, *p), FREE);
16953 p++;
16954 }
16955 new = funcblock;
16956 funcblock = (char *) funcblock + sizeof(char *);
16957 *new = NULL;
16958 return start + 2;
16959 }
16960 return NULL;
16961}
16962
16963#if MAX_HISTORY
16964static struct datasize
16965history_size(struct datasize ds)
16966{
16967 int i;
16968 line_input_t *st = line_input_state;
16969
16970 ds.funcblocksize += sizeof(char *) * st->cnt_history;
16971 for (i = 0; i < st->cnt_history; i++) {
16972 ds.funcstringsize += align_len(st->history[i]);
16973 }
16974 return ds;
16975}
16976
16977static char **
16978history_copy(void)
16979{
16980 line_input_t *st = line_input_state;
16981 char **new = funcblock;
16982 int i;
16983
16984 funcblock = (char *)funcblock + sizeof(char *) * st->cnt_history;
16985 for (i = 0; i < st->cnt_history; i++) {
16986 new[i] = nodeckstrdup(st->history[i]);
16987 SAVE_PTR(new[i],
16988 xasprintf("history[%d] '%s'", i, st->history[i]), FREE);
16989 }
16990 return new;
16991}
16992#endif
16993
16994#if JOBS_WIN32
16995/*
16996 * struct procstat
16997 */
16998static struct datasize
16999procstat_size(struct datasize ds, int nj)
17000{
17001 struct job *jp = jobtab + nj;
17002
17003 if (jp->ps != &jp->ps0)
17004 ds.funcblocksize += sizeof(struct procstat) * jp->nprocs;
17005
17006 for (int i = 0; i < jp->nprocs; i++)
17007 ds.funcstringsize += align_len(jp->ps[i].ps_cmd);
17008
17009 return ds;
17010}
17011
17012static struct procstat *
17013procstat_copy(int nj)
17014{
17015 struct job *jp = jobtab + nj;
17016 struct procstat *new = funcblock;
17017
17018 funcblock = (char *)funcblock + sizeof(struct procstat) * jp->nprocs;
17019 memcpy(new, jp->ps, sizeof(struct procstat) * jp->nprocs);
17020
17021 for (int i = 0; i < jp->nprocs; i++) {
17022 new[i].ps_cmd = nodeckstrdup(jp->ps[i].ps_cmd);
17023 SAVE_PTR(new[i].ps_cmd,
17024 xasprintf("jobtab[%d].ps[%d].ps_cmd '%s'",
17025 nj, i, jp->ps[i].ps_cmd), FREE);
17026 }
17027 return new;
17028}
17029
17030/*
17031 * struct jobs
17032 */
17033static struct datasize
17034jobtab_size(struct datasize ds)
17035{
17036 ds.funcblocksize += sizeof(struct job) * njobs;
17037 for (int i = 0; i < njobs; i++) {
17038 if (jobtab[i].used)
17039 ds = procstat_size(ds, i);
17040 }
17041 return ds;
17042}
17043
17044static struct job *
17045jobtab_copy(void)
17046{
17047 struct job *new = funcblock;
17048 int i;
17049
17050 funcblock = (char *)funcblock + sizeof(struct job) * njobs;
17051 memcpy(new, jobtab, sizeof(struct job) * njobs);
17052
17053 for (i = 0; i < njobs; i++) {
17054 if (!jobtab[i].used)
17055 continue;
17056
17057 if (jobtab[i].ps == &jobtab[i].ps0) {
17058 new[i].ps0.ps_cmd = nodeckstrdup(jobtab[i].ps0.ps_cmd);
17059 SAVE_PTR(new[i].ps0.ps_cmd,
17060 xasprintf("jobtab[%d].ps0.ps_cmd '%s'",
17061 i, jobtab[i].ps0.ps_cmd), FREE);
17062 new[i].ps = &new[i].ps0;
17063 } else if (jobtab[i].nprocs) {
17064 new[i].ps = procstat_copy(i);
17065 } else {
17066 new[i].ps = NULL;
17067 }
17068 SAVE_PTR(new[i].ps, xasprintf("jobtab[%d].ps", i), FREE);
17069
17070 if (jobtab[i].prev_job) {
17071 new[i].prev_job = new + (jobtab[i].prev_job - jobtab);
17072 SAVE_PTR(new[i].prev_job,
17073 xasprintf("jobtab[%d].prev_job", i), FREE);
17074 }
17075 }
17076 return new;
17077}
17078#endif
17079
17080/*
17081 * struct redirtab
17082 */
17083static int
17084redirtab_size(int funcblocksize, struct redirtab *rdtp)
17085{
17086 while (rdtp) {
17087 funcblocksize += sizeof(*rdtp)+sizeof(rdtp->two_fd[0])*rdtp->pair_count;
17088 rdtp = rdtp->next;
17089 }
17090 return funcblocksize;
17091}
17092
17093static struct redirtab *
17094redirtab_copy(struct redirtab *rdtp)
17095{
17096 struct redirtab *start;
17097 struct redirtab **vpp;
17098
17099 vpp = &start;
17100 while (rdtp) {
17101 int size = sizeof(*rdtp)+sizeof(rdtp->two_fd[0])*rdtp->pair_count;
17102 *vpp = funcblock;
17103 funcblock = (char *) funcblock + size;
17104 memcpy(*vpp, rdtp, size);
17105 SAVE_PTR((*vpp)->next, "(*vpp)->next", NO_FREE);
17106 rdtp = rdtp->next;
17107 vpp = &(*vpp)->next;
17108 }
17109 *vpp = NULL;
17110 return start;
17111}
17112
17113static struct datasize
17114globals_var_size(struct datasize ds)
17115{
17116 int i;
17117
17118 ds.funcblocksize += sizeof(struct globals_var);
17119 ds.funcstringsize += align_len(funcname);
17120 ds = argv_size(ds, shellparam.p);
17121 ds.funcblocksize = redirtab_size(ds.funcblocksize, redirlist);
17122 for (i = 0; i < VTABSIZE; i++)
17123 ds = var_size(ds, vartab[i]);
17124 return ds;
17125}
17126
17127#undef funcname
17128#undef shellparam
17129#undef redirlist
17130#undef vartab
17131static struct globals_var *
17132globals_var_copy(void)
17133{
17134 int i;
17135 struct globals_var *gvp, *new;
17136
17137 gvp = ash_ptr_to_globals_var;
17138 new = funcblock;
17139 funcblock = (char *) funcblock + sizeof(struct globals_var);
17140 memcpy(new, gvp, sizeof(struct globals_var));
17141
17142 new->funcname = nodeckstrdup(gvp->funcname);
17143 SAVE_PTR(new->funcname, xasprintf("funcname '%s'", gvp->funcname ?: "NULL"), FREE);
17144
17145 /* shparam */
17146 new->shellparam.malloced = 0;
17147 new->shellparam.p = argv_copy(gvp->shellparam.p);
17148 SAVE_PTR(new->shellparam.p, "shellparam.p", NO_FREE);
17149
17150 new->redirlist = redirtab_copy(gvp->redirlist);
17151 SAVE_PTR(new->redirlist, "redirlist", NO_FREE);
17152
17153 for (i = 0; i < VTABSIZE; i++) {
17154 new->vartab[i] = var_copy(gvp->vartab[i]);
17155 SAVE_PTR(new->vartab[i], xasprintf("vartab[%d]", i), FREE);
17156 }
17157
17158 return new;
17159}
17160
17161static struct datasize
17162globals_misc_size(struct datasize ds)
17163{
17164 ds.funcblocksize += sizeof(struct globals_misc);
17165 ds.funcstringsize += align_len(minusc);
17166 if (curdir != nullstr)
17167 ds.funcstringsize += align_len(curdir);
17168 if (physdir != nullstr)
17169 ds.funcstringsize += align_len(physdir);
17170 ds.funcstringsize += align_len(arg0);
17171 ds.funcstringsize += align_len(commandname);
17172 for (int i = 0; i < ARRAY_SIZE(trap); i++)
17173 ds.funcstringsize += align_len(trap[i]);
17174 return ds;
17175}
17176
17177#undef minusc
17178#undef curdir
17179#undef physdir
17180#undef arg0
17181#undef commandname
17182#undef nullstr
17183#undef trap
17184static struct globals_misc *
17185globals_misc_copy(void)
17186{
17187 struct globals_misc *p = ash_ptr_to_globals_misc;
17188 struct globals_misc *new = funcblock;
17189
17190 funcblock = (char *) funcblock + sizeof(struct globals_misc);
17191 memcpy(new, p, sizeof(struct globals_misc));
17192
17193 new->minusc = nodeckstrdup(p->minusc);
17194 new->curdir = p->curdir != p->nullstr ? nodeckstrdup(p->curdir) : new->nullstr;
17195 new->physdir = p->physdir != p->nullstr ? nodeckstrdup(p->physdir) : new->nullstr;
17196 new->arg0 = nodeckstrdup(p->arg0);
17197 new->commandname = nodeckstrdup(p->commandname);
17198 SAVE_PTR(new->minusc, xasprintf("minusc '%s'", p->minusc ?: "NULL"), FREE);
17199 SAVE_PTR(new->curdir,
17200 xasprintf("curdir '%s'", new->curdir ?: "NULL"), FREE);
17201 SAVE_PTR(new->physdir,
17202 xasprintf("physdir '%s'", new->physdir ?: "NULL"), FREE);
17203 SAVE_PTR(new->arg0, xasprintf("arg0 '%s'", p->arg0 ?: "NULL"), FREE);
17204 SAVE_PTR(new->commandname,
17205 xasprintf("commandname '%s'", p->commandname ?: "NULL"), FREE);
17206 for (int i = 0; i < ARRAY_SIZE(p->trap); i++) {
17207 new->trap[i] = nodeckstrdup(p->trap[i]);
17208 SAVE_PTR(new->trap[i], xasprintf("trap[%d]", i), FREE);
17209 }
17210 return new;
17211}
17212
17213static struct datasize
17214forkshell_size(struct forkshell *fs)
17215{
17216 struct datasize ds = {0, 0};
17217
17218 ds.funcstringsize += align_len(fs->path);
17219 if (fs->fpid == FS_OPENHERE)
17220 return ds;
17221
17222 ds = globals_var_size(ds);
17223 ds = globals_misc_size(ds);
17224 ds = cmdtable_size(ds);
17225
17226 ds.funcblocksize = calcsize(ds.funcblocksize, fs->n);
17227 ds = argv_size(ds, fs->argv);
17228
17229 if ((ENABLE_ASH_ALIAS || MAX_HISTORY || JOBS_WIN32) &&
17230 fs->fpid != FS_SHELLEXEC) {
17231#if ENABLE_ASH_ALIAS
17232 ds = atab_size(ds);
17233#endif
17234#if MAX_HISTORY
17235 if (line_input_state)
17236 ds = history_size(ds);
17237#endif
17238#if JOBS_WIN32
17239 ds = jobtab_size(ds);
17240#endif
17241 }
17242 return ds;
17243}
17244
17245static void
17246forkshell_copy(struct forkshell *fs, struct forkshell *new)
17247{
17248 memcpy(new, fs, sizeof(struct forkshell)); /* non-pointer stuff */
17249
17250 new->path = nodeckstrdup(fs->path);
17251 SAVE_PTR(new->path, xasprintf("path '%s'", fs->path ?: "NULL"), FREE);
17252 if (fs->fpid == FS_OPENHERE)
17253 return;
17254
17255 new->gvp = globals_var_copy();
17256 new->gmp = globals_misc_copy();
17257 new->cmdtable = cmdtable_copy();
17258 SAVE_PTR(new->gvp, "gvp", NO_FREE);
17259 SAVE_PTR(new->gmp, "gmp", NO_FREE);
17260 SAVE_PTR(new->cmdtable, "cmdtable", NO_FREE);
17261
17262 new->n = copynode(fs->n);
17263 new->argv = argv_copy(fs->argv);
17264 SAVE_PTR(new->n, "n", NO_FREE);
17265 SAVE_PTR(new->argv, "argv", NO_FREE);
17266
17267 if ((ENABLE_ASH_ALIAS || MAX_HISTORY || JOBS_WIN32) &&
17268 fs->fpid != FS_SHELLEXEC) {
17269#if ENABLE_ASH_ALIAS
17270 new->atab = atab_copy();
17271 SAVE_PTR(new->atab, "atab", NO_FREE);
17272#endif
17273#if MAX_HISTORY
17274 if (line_input_state) {
17275 new->history = history_copy();
17276 SAVE_PTR(new->history, "history", NO_FREE);
17277 new->cnt_history = line_input_state->cnt_history;
17278 }
17279#endif
17280#if JOBS_WIN32
17281 if (njobs) {
17282 new->jobtab = jobtab_copy();
17283 SAVE_PTR(new->jobtab, "jobtab", NO_FREE);
17284 new->njobs = njobs;
17285 if (curjob) {
17286 new->curjob = new->jobtab + (curjob - jobtab);
17287 SAVE_PTR(new->curjob, "curjob", NO_FREE);
17288 }
17289 }
17290#endif
17291 }
17292}
17293
17294#if FORKSHELL_DEBUG
17295#define NUM_BLOCKS FUNCSTRING
17296enum {GVP, GMP, CMDTABLE, NODE, ARGV, ATAB, HISTORY, JOBTAB, FUNCSTRING};
17297
17298/* fp0 and notes can each be NULL */
17299static void
17300forkshell_print(FILE *fp0, struct forkshell *fs, const char **notes)
17301{
17302 FILE *fp;
17303 void *lfuncblock;
17304 char *lfuncstring;
17305 char *lrelocate;
17306 char *s;
17307 int count, i, total, bitmapsize;
17308 int size[NUM_BLOCKS];
17309 char *lptr[NUM_BLOCKS+1];
17310 const char *fsname[] = {
17311 "FS_OPENHERE",
17312 "FS_EVALBACKCMD",
17313 "FS_EVALSUBSHELL",
17314 "FS_EVALPIPE",
17315 "FS_SHELLEXEC"
17316 };
17317
17318 if (fp0 != NULL) {
17319 fp = fp0;
17320 }
17321 else {
17322 char name[64];
17323 static int num = 0;
17324
17325 sprintf(name, "fs_%d_%03d.out", getpid(), ++num % 100);
17326 if ((fp=fopen(name, "w")) == NULL)
17327 return;
17328 }
17329
17330 bitmapsize = (fs->relocatesize + 7)/8;
17331 total = sizeof(struct forkshell) + fs->funcblocksize +
17332 fs->funcstringsize + bitmapsize;
17333 fprintf(fp, "total size %6d = %d + %d + %d + %d = %d\n",
17334 fs->size + bitmapsize,
17335 (int)sizeof(struct forkshell), fs->funcblocksize,
17336 fs->funcstringsize, bitmapsize, total);
17337
17338 lfuncblock = (char *)(fs + 1);
17339 lfuncstring = (char *)lfuncblock + fs->funcblocksize;
17340 lrelocate = (char *)lfuncstring + fs->funcstringsize;
17341
17342 /* funcblocksize is zero for FS_OPENHERE */
17343 if (fs->funcblocksize != 0) {
17344 /* Depending on the configuration and the type of forkshell
17345 * some items may not be present. */
17346 lptr[FUNCSTRING] = lfuncstring;
17347#if JOBS_WIN32
17348 lptr[JOBTAB] = fs->jobtab ? (char *)fs->jobtab : lptr[FUNCSTRING];
17349#else
17350 lptr[JOBTAB] = lptr[FUNCSTRING];
17351#endif
17352#if MAX_HISTORY
17353 lptr[HISTORY] = fs->history ? (char *)fs->history : lptr[JOBTAB];
17354#else
17355 lptr[HISTORY] = lptr[JOBTAB];
17356#endif
17357 lptr[ATAB] = IF_ASH_ALIAS(fs->atab ? (char *)fs->atab :) lptr[HISTORY];
17358 lptr[ARGV] = fs->argv ? (char *)fs->argv : lptr[ATAB];
17359 lptr[NODE] = fs->n ? (char *)fs->n : lptr[ARGV];
17360 lptr[CMDTABLE] = (char *)fs->cmdtable;
17361 lptr[GMP] = (char *)fs->gmp;
17362 lptr[GVP] = (char *)fs->gvp;
17363
17364 fprintf(fp, "funcblocksize %6d = ", fs->funcblocksize);
17365 total = 0;
17366 for (i=0; i<NUM_BLOCKS; ++i) {
17367 size[i] = (int)(lptr[i+1] - lptr[i]);
17368 total += size[i];
17369 fprintf(fp, "%d %c ", size[i], i == NUM_BLOCKS - 1 ? '=' : '+');
17370 }
17371 fprintf(fp, "%d\n\n", total);
17372 }
17373 else {
17374 fprintf(fp, "\n");
17375 }
17376
17377 fprintf(fp, "%s\n\n", fsname[fs->fpid]);
17378 fprintf(fp, "--- relocate ---\n");
17379 count = 0;
17380 for (i = 0; i < fs->relocatesize; ++i) {
17381 if (lrelocate[i/8] & (1 << i % 8)) {
17382 char **ptr = (char **)((char *)fs + i * sizeof(char *));
17383 fprintf(fp, "%p %p %s\n", ptr, *ptr,
17384 notes && notes[i] ? notes[i] : "");
17385 ++count;
17386 }
17387 }
17388 fprintf(fp, "--- %d relocations ---\n\n", count);
17389
17390 fprintf(fp, "--- funcstring ---\n");
17391 count = 0;
17392 s = lfuncstring;
17393 while (s-lfuncstring < fs->funcstringsize) {
17394 if (!*s) {
17395 ++s;
17396 continue;
17397 }
17398 fprintf(fp, "%p '%s'\n", s, s);
17399 s += strlen(s)+1;
17400 ++count;
17401 }
17402 fprintf(fp, "--- %d strings ---\n", count);
17403
17404 if (fp0 == NULL)
17405 fclose(fp);
17406}
17407#endif
17408
17409static struct forkshell *
17410forkshell_prepare(struct forkshell *fs)
17411{
17412 struct forkshell *new;
17413 struct datasize ds;
17414 int size, relocatesize, bitmapsize;
17415 HANDLE h;
17416 SECURITY_ATTRIBUTES sa;
17417#if FORKSHELL_DEBUG
17418 char *relocate;
17419 char name[64];
17420 FILE *fp;
17421 static int num = 0;
17422#endif
17423
17424 /* calculate size of structure, funcblock and funcstring */
17425 ds = forkshell_size(fs);
17426 size = sizeof(struct forkshell) + ds.funcblocksize + ds.funcstringsize;
17427 relocatesize = (sizeof(struct forkshell) + ds.funcblocksize)/sizeof(char *);
17428 bitmapsize = (relocatesize + 7)/8;
17429
17430 /* Allocate shared memory region */
17431 memset(&sa, 0, sizeof(sa));
17432 sa.nLength = sizeof(sa);
17433 sa.lpSecurityDescriptor = NULL;
17434 sa.bInheritHandle = TRUE;
17435 h = CreateFileMapping(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE, 0,
17436 size+bitmapsize, NULL);
17437
17438 /* Initialise pointers */
17439 new = (struct forkshell *)MapViewOfFile(h, FILE_MAP_WRITE, 0,0, 0);
17440 if (new == NULL)
17441 return NULL;
17442 fs_size = size;
17443 fs_start = new;
17444 funcblock = (char *)(new + 1);
17445 funcstring_end = (char *)new + size;
17446#if FORKSHELL_DEBUG
17447 fs_funcstring = (char *)new + sizeof(struct forkshell) + ds.funcblocksize;
17448 relocate = (char *)new + size;
17449 annot = (const char **)xzalloc(sizeof(char *)*relocatesize);
17450 annot_free = xzalloc(relocatesize);
17451#endif
17452
17453 /* Now pack them all */
17454 forkshell_copy(fs, new);
17455
17456 /* Finish it up */
17457 new->size = size;
17458 new->relocatesize = relocatesize;
17459 new->old_base = (char *)new;
17460 new->hMapFile = h;
17461#if FORKSHELL_DEBUG
17462 sprintf(name, "fs_%d_%03d.out", getpid(), ++num % 100);
17463 if ((fp=fopen(name, "w")) != NULL) {
17464 int i;
17465
17466 new->funcblocksize = (char *)funcblock - (char *)(new + 1);
17467 new->funcstringsize = (char *)new + size - funcstring_end;
17468
17469 /* perform some sanity checks on pointers */
17470 fprintf(fp, "forkshell %p %6d\n", new, (int)sizeof(*new));
17471 fprintf(fp, "funcblock %p %6d\n", new+1, new->funcblocksize);
17472 fprintf(fp, "funcstring %p %6d\n", funcstring_end,
17473 new->funcstringsize);
17474 if ((char *)funcblock != funcstring_end)
17475 fprintf(fp, " funcstring != end funcblock + 1 %p\n", funcblock);
17476 fprintf(fp, "relocate %p %6d\n\n", relocate, bitmapsize);
17477
17478 forkshell_print(fp, new, annot);
17479
17480 for (i = 0; i < relocatesize; ++i) {
17481 if (annot_free[i]) {
17482 free((void *)annot[i]);
17483 }
17484 }
17485 free(annot);
17486 free(annot_free);
17487 annot = NULL;
17488 fclose(fp);
17489 }
17490#endif
17491 return new;
17492}
17493
17494#undef trap_ptr
17495static void
17496forkshell_init(const char *idstr)
17497{
17498 struct forkshell *fs;
17499 void *map_handle;
17500 HANDLE h;
17501 int i;
17502 char **ptr;
17503 char *lrelocate;
17504 struct jmploc jmploc;
17505
17506 if (sscanf(idstr, "%p", &map_handle) != 1)
17507 return;
17508
17509 h = (HANDLE)map_handle;
17510 fs = (struct forkshell *)MapViewOfFile(h, FILE_MAP_WRITE, 0,0, 0);
17511 if (!fs)
17512 return;
17513
17514 /* this memory can't be freed */
17515 sticky_mem_start = fs;
17516 sticky_mem_end = (char *) fs + fs->size;
17517
17518 /* pointer fixup */
17519 lrelocate = (char *)fs + fs->size;
17520 for (i = 0; i < fs->relocatesize; i++) {
17521 if (lrelocate[i/8] & (1 << i % 8)) {
17522 ptr = (char **)((char *)fs + i * sizeof(char *));
17523 if (*ptr)
17524 *ptr = (char *)fs + (*ptr - fs->old_base);
17525 }
17526 }
17527
17528 if (fs->fpid == FS_OPENHERE)
17529 goto end;
17530
17531 /* Now fix up stuff that can't be transferred */
17532 for (i = 0; i < CMDTABLESIZE; i++) {
17533 struct tblentry *e = fs->cmdtable[i];
17534 while (e) {
17535 if (e->cmdtype == CMDBUILTIN)
17536 e->param.cmd = builtintab + e->param.index;
17537 e = e->next;
17538 }
17539 }
17540 fs->gmp->trap_ptr = fs->gmp->trap;
17541
17542 /* Set global variables */
17543 ASSIGN_CONST_PTR(&ash_ptr_to_globals_var, fs->gvp);
17544 ASSIGN_CONST_PTR(&ash_ptr_to_globals_misc, fs->gmp);
17545 cmdtable = fs->cmdtable;
17546#if ENABLE_ASH_ALIAS
17547 atab = fs->atab; /* will be NULL for FS_SHELLEXEC */
17548#endif
17549#if MAX_HISTORY
17550 if (fs->cnt_history) {
17551 line_input_state = new_line_input_t(FOR_SHELL);
17552 line_input_state->cnt_history = fs->cnt_history;
17553 for (i = 0; i < line_input_state->cnt_history; i++)
17554 line_input_state->history[i] = fs->history[i];
17555 }
17556#endif
17557#if JOBS_WIN32
17558 jobtab = fs->jobtab;
17559 njobs = fs->njobs;
17560 curjob = fs->curjob;
17561#endif
17562
17563 CLEAR_RANDOM_T(&random_gen); /* or else $RANDOM repeats in child */
17564
17565 reinitvar();
17566
17567 if (setjmp(jmploc.loc)) {
17568 exitreset();
17569 exitshell();
17570 }
17571 exception_handler = &jmploc;
17572
17573 shlvl++;
17574 if (fs->mode == FORK_BG) {
17575 SetConsoleCtrlHandler(NULL, TRUE);
17576 if (fs->nprocs == 0) {
17577 close(0);
17578 if (open(bb_dev_null, O_RDONLY) != 0)
17579 ash_msg_and_raise_perror("can't open '%s'", bb_dev_null);
17580 }
17581 }
17582 else {
17583 SetConsoleCtrlHandler(ctrl_handler, TRUE);
17584 }
17585
17586 if (fs->n && fs->n->type == NCMD /* is it single cmd? */
17587 /* && n->ncmd.args->type == NARG - always true? */
17588 && fs->n->ncmd.args && strcmp(fs->n->ncmd.args->narg.text, "trap") == 0
17589 && fs->n->ncmd.args->narg.next == NULL /* "trap" with no arguments */
17590 /* && n->ncmd.args->narg.backquote == NULL - do we need to check this? */
17591 ) {
17592 TRACE(("Trap hack\n"));
17593 /* Save trap handler strings for trap builtin to print */
17594 fs->gmp->trap_ptr = xmemdup(fs->gmp->trap, sizeof(fs->gmp->trap));
17595 /* Fall through into clearing traps */
17596 }
17597 clear_traps();
17598#if JOBS_WIN32
17599 /* do job control only in root shell */
17600 doing_jobctl = 0;
17601
17602 if (fs->n && fs->n->type == NCMD && fs->n->ncmd.args &&
17603 strcmp(fs->n->ncmd.args->narg.text, "jobs") == 0) {
17604 TRACE(("Job hack\n"));
17605 if (!fs->jpnull)
17606 freejob(curjob);
17607 goto end;
17608 }
17609 for (struct job *jp = curjob; jp; jp = jp->prev_job)
17610 freejob(jp);
17611#endif
17612 end:
17613 forkshell_child(fs);
17614}
17615
17616#undef free
17617static void
17618sticky_free(void *base)
17619{
17620 if (base >= sticky_mem_start && base < sticky_mem_end)
17621 return;
17622 free(base);
17623}
17624#endif
14887 17625
14888/*- 17626/*-
14889 * Copyright (c) 1989, 1991, 1993, 1994 17627 * Copyright (c) 1989, 1991, 1993, 1994