-
Notifications
You must be signed in to change notification settings - Fork 337
/
sh.c
2800 lines (2330 loc) · 77.8 KB
/
sh.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* sh.c - toybox shell
*
* Copyright 2006 Rob Landley <rob@landley.net>
*
* This shell aims for bash compatibility. The bash man page is at:
* http://man7.org/linux/man-pages/man1/bash.1.html
*
* The POSIX-2008/SUSv4 shell spec is at:
* http://opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
* and http://opengroup.org/onlinepubs/9699919799/utilities/sh.html
*
* The chap02 link describes the following shell builtins:
*
* break : continue exit
* . eval exec export readonly return set shift times trap unset
*
* The second link (the utilities directory) also contains specs for the
* following shell builtins:
*
* cd ulimit umask
* alias bg command fc fg getopts hash jobs kill read type unalias wait
*
* deviations from posix: don't care about $LANG or $LC_ALL
* TODO: test that $PS1 color changes work without stupid \[ \] hack
* TODO: Handle embedded NUL bytes in the command line? (When/how?)
* builtins: alias bg command fc fg getopts jobs newgrp read umask unalias wait
* disown umask suspend source pushd popd dirs logout times trap
* unset local export readonly set : . let history declare
* "special" builtins: break continue eval exec return shift
* builtins with extra shell behavior: kill pwd time test
* | & ; < > ( ) $ ` \ " ' <space> <tab> <newline>
* * ? [ # ~ = %
* ! { } case do done elif else esac fi for if in then until while
* [[ ]] function select
* label:
* TODO: test exit from "trap EXIT" doesn't recurse
* TODO: ! history expansion
* TODO: getuid() vs geteuid()
*
* bash man page:
* control operators || & && ; ;; ;& ;;& ( ) | |& <newline>
* reserved words
* ! case coproc do done elif else esac fi for function if in select
* then until while { } time [[ ]]
USE_SH(NEWTOY(cd, ">1LP[-LP]", TOYFLAG_NOFORK))
USE_SH(NEWTOY(eval, 0, TOYFLAG_NOFORK))
USE_SH(NEWTOY(exec, "^cla:", TOYFLAG_NOFORK))
USE_SH(NEWTOY(exit, 0, TOYFLAG_NOFORK))
USE_SH(NEWTOY(export, "np", TOYFLAG_NOFORK))
USE_SH(NEWTOY(shift, ">1", TOYFLAG_NOFORK))
USE_SH(NEWTOY(unset, "fvn", TOYFLAG_NOFORK))
USE_SH(NEWTOY(sh, "(noediting)(noprofile)(norc)sc:i", TOYFLAG_BIN))
USE_SH(OLDTOY(toysh, sh, TOYFLAG_BIN))
USE_SH(OLDTOY(bash, sh, TOYFLAG_BIN))
// Login lies in argv[0], so add some aliases to catch that
USE_SH(OLDTOY(-sh, sh, 0))
USE_SH(OLDTOY(-toysh, sh, 0))
USE_SH(OLDTOY(-bash, sh, 0))
config SH
bool "sh (toysh)"
default n
help
usage: sh [-c command] [script]
Command shell. Runs a shell script, or reads input interactively
and responds to it.
-c command line to execute
-i interactive mode (default when STDIN is a tty)
# These are here for the help text, they're not selectable and control nothing
config CD
bool
default n
depends on SH
help
usage: cd [-PL] [path]
Change current directory. With no arguments, go $HOME.
-P Physical path: resolve symlinks in path
-L Local path: .. trims directories off $PWD (default)
config EXIT
bool
default n
depends on SH
help
usage: exit [status]
Exit shell. If no return value supplied on command line, use value
of most recent command, or 0 if none.
config UNSET
bool
default n
depends on SH
help
usage: unset [-fvn] NAME...
-f NAME is a function
-v NAME is a variable
-n dereference NAME and unset that
config EVAL
bool
default n
depends on SH
help
usage: eval COMMAND...
Execute (combined) arguments as a shell command.
config EXEC
bool
default n
depends on SH
help
usage: exec [-cl] [-a NAME] COMMAND...
-a set argv[0] to NAME
-c clear environment
-l prepend - to argv[0]
config EXPORT
bool
default n
depends on SH
help
usage: export [-n] [NAME[=VALUE]...]
Make variables available to child processes. NAME exports existing local
variable(s), NAME=VALUE sets and exports.
-n Unexport. Turn listed variable(s) into local variables.
With no arguments list exported variables/attributes as "declare" statements.
config SHIFT
bool
default n
depends on SH
help
usage: shift [N]
Skip N (default 1) positional parameters, moving $1 and friends along the list.
Does not affect $0.
*/
#define FOR_sh
#include "toys.h"
GLOBALS(
union {
struct {
char *c;
} sh;
struct {
char *a;
} exec;
};
// keep lineno here, we use it to work around a compiler bug
long lineno;
char *ifs, *isexec;
struct double_list functions;
unsigned options, jobcnt;
int hfd, pid, varslen, shift, cdcount;
unsigned long long SECONDS;
struct sh_vars {
long flags;
char *str;
} *vars;
// Running jobs for job control.
struct sh_job {
struct sh_job *next, *prev;
unsigned jobno;
// Every pipeline has at least one set of arguments or it's Not A Thing
struct sh_arg {
char **v;
int c;
} pipeline;
// null terminated array of running processes in pipeline
struct sh_process {
struct sh_process *next, *prev;
struct arg_list *delete; // expanded strings
// undo redirects, a=b at start, child PID, exit status, has !
int *urd, envlen, pid, exit, not;
struct sh_arg arg;
} *procs, *proc;
} *jobs, *job;
struct sh_process *pp;
struct sh_arg *arg;
)
// Can't yet avoid this prototype. Fundamental problem is $($($(blah))) nests,
// leading to function loop with run->parse->run
static int sh_run(char *new);
// Pipeline segments
struct sh_pipeline {
struct sh_pipeline *next, *prev;
int count, here, type;
struct sh_arg arg[1];
};
// scratch space (state held between calls). Don't want to make it global yet
// because this could be reentrant.
struct sh_function {
char *name;
struct sh_pipeline *pipeline;
struct double_list *expect;
// TODO: lifetime rules for arg? remember "shift" command.
struct sh_arg *arg; // arguments to function call
char *end;
};
#define BUGBUG 0
// call with NULL to just dump FDs
static void dump_state(struct sh_function *sp)
{
struct sh_pipeline *pl;
long i;
int q = 0, fd = open("/proc/self/fd", O_RDONLY);
DIR *dir = fdopendir(fd);
char buf[256];
if (sp && sp->expect) {
struct double_list *dl;
for (dl = sp->expect; dl; dl = (dl->next == sp->expect) ? 0 : dl->next)
dprintf(255, "expecting %s\n", dl->data);
if (sp->pipeline)
dprintf(255, "pipeline count=%d here=%d\n", sp->pipeline->prev->count,
sp->pipeline->prev->here);
}
if (sp) for (pl = sp->pipeline; pl ; pl = (pl->next == sp->pipeline) ? 0 : pl->next) {
for (i = 0; i<pl->arg->c; i++)
dprintf(255, "arg[%d][%ld]=%s\n", q, i, pl->arg->v[i]);
if (pl->arg->c<0) dprintf(255, "argc=%d\n", pl->arg->c);
else dprintf(255, "type=%d term[%d]=%s\n", pl->type, q++, pl->arg->v[pl->arg->c]);
}
if (dir) {
struct dirent *dd;
while ((dd = readdir(dir))) {
if (atoi(dd->d_name)!=fd && 0<readlinkat(fd, dd->d_name, buf,sizeof(buf)))
dprintf(255, "OPEN %d: %s = %s\n", getpid(), dd->d_name, buf);
}
closedir(dir);
}
close(fd);
}
// ordered for greedy matching, so >&; becomes >& ; not > &;
// making these const means I need to typecast the const away later to
// avoid endless warnings.
static const char *redirectors[] = {"<<<", "<<-", "<<", "<&", "<>", "<", ">>",
">&", ">|", ">", "&>>", "&>", 0};
#define OPT_I 1
#define OPT_BRACE 2 // set -B
#define OPT_NOCLOBBER 4 // set -C
#define OPT_S 8
#define OPT_C 16
static void syntax_err(char *s)
{
error_msg("syntax error: %s", s);
toys.exitval = 2;
}
// append to array with null terminator and realloc as necessary
static void array_add(char ***list, unsigned count, char *data)
{
if (!(count&31)) *list = xrealloc(*list, sizeof(char *)*(count+33));
(*list)[count] = data;
(*list)[count+1] = 0;
}
// add argument to an arg_list
static void add_arg(struct arg_list **list, char *arg)
{
struct arg_list *al;
if (!list) return;
al = xmalloc(sizeof(struct arg_list));
al->next = *list;
al->arg = arg;
*list = al;
}
static void array_add_del(char ***list, unsigned count, char *data,
struct arg_list **delete)
{
add_arg(delete, data);
array_add(list, count, data);
}
// return length of valid variable name
static char *varend(char *s)
{
if (isdigit(*s)) return s;
while (*s>' ' && (*s=='_' || !ispunct(*s))) s++;
return s;
}
// Return index of variable within this list
static struct sh_vars *findvar(char *name)
{
int len = varend(name)-name;
struct sh_vars *var = TT.vars+TT.varslen;
if (len) while (var-- != TT.vars)
if (!strncmp(var->str, name, len) && var->str[len] == '=') return var;
return 0;
}
// Append variable to TT.vars, returning *struct. Does not check duplicates.
static struct sh_vars *addvar(char *s)
{
if (!(TT.varslen&31))
TT.vars = xrealloc(TT.vars, (TT.varslen+32)*sizeof(*TT.vars));
TT.vars[TT.varslen].flags = 0;
TT.vars[TT.varslen].str = s;
return TT.vars+TT.varslen++;
}
// TODO function to resolve a string into a number for $((1+2)) etc
long long do_math(char *s)
{
return atoll(s);
}
// Assign one variable from malloced key=val string, returns var struct
// TODO implement remaining types
#define VAR_DICT 256
#define VAR_ARRAY 128
#define VAR_INT 64
#define VAR_TOLOWER 32
#define VAR_TOUPPER 16
#define VAR_NAMEREF 8
#define VAR_GLOBAL 4
#define VAR_READONLY 2
#define VAR_MAGIC 1
// declare -aAilnrux
// ft
static struct sh_vars *setvar(char *s)
{
int len = varend(s)-s;
long flags;
struct sh_vars *var;
if (s[len] != '=') {
error_msg("bad setvar %s\n", s);
free(s);
return 0;
}
if (len == 3 && !memcmp(s, "IFS", 3)) TT.ifs = s+4;
if (!(var = findvar(s))) return addvar(s);
flags = var->flags;
if (flags&VAR_READONLY) {
error_msg("%.*s: read only", len, s);
free(s);
return var;
} else if (flags&VAR_MAGIC) {
if (*s == 'S') TT.SECONDS = millitime() - 1000*do_math(s+len-1);
else if (*s == 'R') srandom(do_math(s+len-1));
} else if (flags&VAR_GLOBAL) xsetenv(var->str = s, 0);
else {
free(var->str);
var->str = s;
}
// TODO if (flags&(VAR_TOUPPER|VAR_TOLOWER))
// unicode _is stupid enough for upper/lower case to be different utf8 byte
// lengths. example: lowercase of U+0130 (C4 B0) is U+0069 (69)
// TODO VAR_INT
// TODO VAR_ARRAY VAR_DICT
return var;
}
static void unsetvar(char *name)
{
struct sh_vars *var = findvar(name);
int ii = var-TT.vars;
if (!var) return;
if (var->flags&VAR_GLOBAL) xunsetenv(name);
else free(var->str);
memmove(TT.vars+ii, TT.vars+ii+1, TT.varslen-ii);
TT.varslen--;
}
static struct sh_vars *setvarval(char *name, char *val)
{
return setvar(xmprintf("%s=%s", name, val));
}
// get value of variable starting at s.
static char *getvar(char *s)
{
struct sh_vars *var = findvar(s);
if (!var) return 0;
if (var->flags & VAR_MAGIC) {
char c = *var->str;
if (c == 'S') sprintf(toybuf, "%lld", (millitime()-TT.SECONDS)/1000);
else if (c == 'R') sprintf(toybuf, "%ld", random()&((1<<16)-1));
else if (c == 'L') sprintf(toybuf, "%ld", TT.lineno);
else if (c == 'G') sprintf(toybuf, "TODO: GROUPS");
return toybuf;
}
return varend(var->str)+1;
}
// malloc declare -x "escaped string"
static char *declarep(struct sh_vars *var)
{
char *types = "-rgnuliaA", *in = types, flags[16], *out = flags, *ss;
int len;
while (*++in) if (var->flags&(1<<(in-types))) *out++ = *in;
if (in == types) *out++ = *types;
*out = 0;
len = out-flags;
for (in = types = varend(var->str); *in; in++) len += !!strchr("$\"\\`", *in);
len += in-types;
ss = xmalloc(len+13);
out = ss + sprintf(ss, "declare -%s \"", out);
while (types) {
if (strchr("$\"\\`", *in)) *out++ = '\\';
*out++ = *types++;
}
*out++ = '"';
*out = 0;
return ss;
}
// return length of match found at this point (try is null terminated array)
static int anystart(char *s, char **try)
{
char *ss = s;
while (*try) if (strstart(&s, *try++)) return s-ss;
return 0;
}
// does this entire string match one of the strings in try[]
static int anystr(char *s, char **try)
{
while (*try) if (!strcmp(s, *try++)) return 1;
return 0;
}
// return length of valid prefix that could go before redirect
static int redir_prefix(char *word)
{
char *s = word;
if (*s == '{') {
if (*(s = varend(s+1)) == '}' && s != word+1) s++;
else s = word;
} else while (isdigit(*s)) s++;
return s-word;
}
// parse next word from command line. Returns end, or 0 if need continuation
// caller eats leading spaces. early = skip one quote block (or return start)
static char *parse_word(char *start, int early)
{
int i, quote = 0, q, qc = 0;
char *end = start, *s;
// Things we should only return at the _start_ of a word
if (strstart(&end, "<(") || strstart(&end, ">(")) toybuf[quote++]=')';
// Redirections. 123<<file- parses as 2 args: "123<<" "file-".
s = end + redir_prefix(end);
if ((i = anystart(s, (void *)redirectors))) return s+i;
// (( is a special quote at the start of a word
if (strstart(&end, "((")) toybuf[quote++] = 254;
// find end of this word
while (*end) {
i = 0;
// barf if we're near overloading quote stack (nesting ridiculously deep)
if (quote>4000) {
syntax_err("tilt");
return (void *)1;
}
// Handle quote contexts
if ((q = quote ? toybuf[quote-1] : 0)) {
// when waiting for parentheses, they nest
if ((q == ')' || q >= 254) && (*end == '(' || *end == ')')) {
if (*end == '(') qc++;
else if (qc) qc--;
else if (q >= 254) {
// (( can end with )) or retroactively become two (( if we hit one )
if (strstart(&end, "))")) quote--;
else if (q == 254) return start+1;
else if (q == 255) toybuf[quote-1] = ')';
} else if (*end == ')') quote--;
end++;
// end quote?
} else if (*end == q) quote--, end++;
// single quote claims everything
else if (q == '\'') end++;
else i++;
// loop if we already handled a symbol and aren't stopping early
if (early && !quote) return end;
if (!i) continue;
} else {
// Things that only matter when unquoted
if (isspace(*end)) break;
if (*end == ')') return end+(start==end);
// Flow control characters that end pipeline segments
s = end + anystart(end, (char *[]){";;&", ";;", ";&", ";", "||",
"|&", "|", "&&", "&", "(", ")", 0});
if (s != end) return (end == start) ? s : end;
}
// Things the same unquoted or in most non-single-quote contexts
// start new quote context?
if (strchr("\"'`", *end)) toybuf[quote++] = *end;
// backslash escapes
else if (*end == '\\') {
if (!end[1] || (end[1]=='\n' && !end[2])) return 0;
end += 2;
} else if (*end == '$' && -1 != (i = stridx("({[", end[1]))) {
end++;
if (strstart(&end, "((")) toybuf[quote++] = 255;
else {
toybuf[quote++] = ")}]"[i];
end++;
}
}
if (early && !quote) return end;
end++;
}
return quote ? 0 : end;
}
// Return next available high (>=10) file descriptor
static int next_hfd()
{
int hfd;
for (; TT.hfd<=99999; TT.hfd++) if (-1 == fcntl(TT.hfd, F_GETFL)) break;
hfd = TT.hfd;
if (TT.hfd > 99999) {
hfd = -1;
if (!errno) errno = EMFILE;
}
return hfd;
}
// Perform a redirect, saving displaced filehandle to a high (>10) fd
// rd is an int array: [0] = count, followed by from/to pairs to restore later.
// If from >= 0 dup from->to after saving to. If from == -1 just save to.
// if from == -2 schedule "to" to be closed by unredirect.
static int save_redirect(int **rd, int from, int to)
{
int cnt, hfd, *rr;
if (from == to) return 0;
// save displaced to, copying to high (>=10) file descriptor to undo later
// except if we're saving to environment variable instead (don't undo that)
if (from>-2) {
if ((hfd = next_hfd())==-1) return 1;
if (hfd != dup2(to, hfd)) hfd = -1;
else fcntl(hfd, F_SETFD, FD_CLOEXEC);
if (BUGBUG) dprintf(255, "%d redir from=%d to=%d hfd=%d\n", getpid(), from, to, hfd);
// dup "to"
if (from >= 0 && to != dup2(from, to)) {
if (hfd >= 0) close(hfd);
return 1;
}
} else {
if (BUGBUG) dprintf(255, "%d schedule close %d\n", getpid(), to);
hfd = to;
to = -1;
}
// Append undo information to redirect list so we can restore saved hfd later.
if (!((cnt = *rd ? **rd : 0)&31)) *rd = xrealloc(*rd, (cnt+33)*2*sizeof(int));
*(rr = *rd) = ++cnt;
rr[2*cnt-1] = hfd;
rr[2*cnt] = to;
return 0;
}
// TODO: waitpid(WNOHANG) to clean up zombies and catch background& ending
static void subshell_callback(char **argv)
{
char *s;
xsetenv(s = xmprintf("@%d,%d=", getpid(), getppid()), 0);
s[strlen(s)-1] = 0;
xsetenv(xmprintf("$=%d", TT.pid), 0);
// TODO: test $$ in (nommu)
}
// TODO check every caller of run_subshell for error, or syntax_error() here
// from pipe() failure
// Pass environment and command string to child shell, return PID of child
static int run_subshell(char *str, int len)
{
pid_t pid;
if (BUGBUG) dprintf(255, "run_subshell %.*s\n", len, str);
// The with-mmu path is significantly faster.
if (CFG_TOYBOX_FORK) {
char *s;
if ((pid = fork())<0) perror_msg("fork");
else if (!pid) {
s = xstrndup(str, len);
sh_run(s);
free(s);
_exit(toys.exitval);
}
// On nommu vfork, exec /proc/self/exe, and pipe state data to ourselves.
} else {
int pipes[2], i, c;
// open pipe to child
if (pipe(pipes) || 254 != dup2(pipes[0], 254)) return 1;
close(pipes[0]);
fcntl(pipes[1], F_SETFD, FD_CLOEXEC);
// vfork child
pid = xpopen_setup(0, 0, subshell_callback);
// free entries added to end of environment by callback (shared heap)
for (i = 0; environ[i]; i++) {
c = environ[i][0];
if (c == '_' || !ispunct(c)) continue;
free(environ[i]);
environ[i] = 0;
}
// marshall data to child
close(254);
for (i = 0; i<TT.varslen; i++) {
char *s;
if (TT.vars[i].flags&VAR_GLOBAL) continue;
dprintf(pipes[1], "%s\n", s = declarep(TT.vars+i));
free(s);
}
dprintf(pipes[1], "%.*s\n", len, str);
close(pipes[1]);
}
return pid;
}
// restore displaced filehandles, closing high filehandles they were copied to
static void unredirect(int *urd)
{
int *rr = urd+1, i;
if (!urd) return;
for (i = 0; i<*urd; i++, rr += 2) {
if (BUGBUG) dprintf(255, "%d urd %d %d\n", getpid(), rr[0], rr[1]);
if (rr[0] != -1) {
// No idea what to do about fd exhaustion here, so Steinbach's Guideline.
dup2(rr[0], rr[1]);
close(rr[0]);
}
}
free(urd);
}
// Call subshell with either stdin/stdout redirected, return other end of pipe
static int pipe_subshell(char *s, int len, int out)
{
int pipes[2], *uu = 0, in = !out;
// Grab subshell data
if (pipe(pipes)) {
perror_msg("%.*s", len, s);
return -1;
}
// Perform input or output redirect and launch process (ignoring errors)
save_redirect(&uu, pipes[in], in);
close(pipes[in]);
run_subshell(s, len);
unredirect(uu);
return pipes[out];
}
// utf8 strchr: return wide char matched at wc from chrs, or 0 if not matched
// if len, save length of wc
static int utf8chr(char *wc, char *chrs, int *len)
{
wchar_t wc1, wc2;
int ll;
if (len) *len = 1;
if (!*wc) return 0;
if (0<(ll = utf8towc(&wc1, wc, 99))) {
if (len) *len = ll;
while (*chrs) {
if(1>(ll = utf8towc(&wc2, chrs, 99))) chrs++;
else {
if (wc1 == wc2) return wc1;
chrs += ll;
}
}
}
return 0;
}
#define NO_PATH (1<<0) // path expansion (wildcards)
#define NO_SPLIT (1<<1) // word splitting
#define NO_BRACE (1<<2) // {brace,expansion}
#define NO_TILDE (1<<3) // ~username/path
#define NO_QUOTE (1<<4) // quote removal
#define SEMI_IFS (1<<5) // Use ' ' instead of IFS to combine $*
// TODO: parameter/variable $(command) $((math)) split pathglob
// TODO: ${name:?error} causes an error/abort here (syntax_err longjmp?)
// TODO: $1 $@ $* need args marshalled down here: function+structure?
// arg = append to this
// str = string to expand
// flags = type of expansions (not) to do
// delete = append new allocations to this so they can be freed later
// TODO: at_args: $1 $2 $3 $* $@
static int expand_arg_nobrace(struct sh_arg *arg, char *str, unsigned flags,
struct arg_list **delete)
{
char cc, qq = 0, *old = str, *new = str, *s, *ss, *ifs, **aa;
int ii = 0, dd, jj, kk, ll, oo = 0, nodel;
if (BUGBUG) dprintf(255, "expand %s\n", str);
// Tilde expansion
if (!(flags&NO_TILDE) && *str == '~') {
struct passwd *pw = 0;
ss = 0;
while (str[ii] && str[ii]!=':' && str[ii]!='/') ii++;
if (ii==1) {
if (!(ss = getvar("HOME")) || !*ss) pw = bufgetpwuid(getuid());
} else {
// TODO bufgetpwnam
pw = getpwnam(s = xstrndup(str+1, ii-1));
free(s);
}
if (pw) {
ss = pw->pw_dir;
if (!ss || !*ss) ss = "/";
}
if (ss) {
oo = strlen(ss);
s = xmprintf("%s%s", ss, str+ii);
if (old != new) free(new);
new = s;
}
}
// parameter/variable expansion, and dequoting
for (; (cc = str[ii++]); old!=new && (new[oo] = 0)) {
// skip literal chars
if (!strchr("$'`\\\"", cc)) {
if (old != new) new[oo++] = cc;
continue;
}
// allocate snapshot if we just started modifying
if (old == new) {
new = xstrdup(new);
new[oo = ii-1] = 0;
}
ifs = 0;
aa = 0;
nodel = 0;
// handle different types of escapes
if (cc == '\\') new[oo++] = str[ii] ? str[ii++] : cc;
else if (cc == '"') qq++;
else if (cc == '\'') {
if (qq&1) new[oo++] = cc;
else {
qq += 2;
while ((cc = str[ii++]) != '\'') new[oo++] = cc;
}
// both types of subshell work the same, so do $( here not in '$' below
// TODO $((echo hello) | cat) ala $(( becomes $( ( retroactively
} else if (cc == '`' || (cc == '$' && strchr("([", str[ii]))) {
off_t pp = 0;
s = str+ii-1;
kk = parse_word(s, 1)-s;
if (str[ii] == '[' || *toybuf == 255) {
s += 2+(str[ii]!='[');
kk -= 3+2*(str[ii]!='[');
dprintf(2, "TODO: do math for %.*s\n", kk, s);
} else {
// Run subshell and trim trailing newlines
s += (jj = 1+(cc == '$'));
ii += --kk;
kk -= jj;
// Special case echo $(<input)
for (ss = s; isspace(*ss); ss++);
if (*ss != '<') ss = 0;
else {
while (isspace(*++ss));
if (!(ll = parse_word(ss, 0)-ss)) ss = 0;
else {
jj = ll+(ss-s);
while (isspace(s[jj])) jj++;
if (jj != kk) ss = 0;
else {
jj = xcreate_stdio(ss = xstrndup(ss, ll), O_RDONLY|WARN_ONLY, 0);
free(ss);
}
}
}
// TODO what does \ in `` mean? What is echo `printf %s \$x` supposed to do?
if (!ss) jj = pipe_subshell(s, kk, 0);
if ((ifs = readfd(jj, 0, &pp)))
for (kk = strlen(ifs); kk && ifs[kk-1]=='\n'; ifs[--kk] = 0);
close(jj);
}
} else if (cc == '$') {
// parse $ $'' ${} or $VAR
cc = str[ii++];
if (cc=='\'') {
for (s = str+ii; *s != '\''; oo += wcrtomb(new+oo, unescape2(&s, 0),0));
ii = s-str+1;
continue;
} else if (cc == '{') {
cc = *(ss = str+ii);
if (!(jj = strchr(ss, '}')-ss)) ifs = (void *)1;
ii += jj+1;
if (jj>1) {
// handle ${!x} and ${#x}
if (*ss == '!') {
if (!(ss = getvar(ss+1)) || !*ss) continue;
jj = varend(ss)-ss;
if (ss[jj]) ifs = (void *)1;
} else if (*ss == '#') {
if (jj == 2 && (*ss == '@' || *ss == '*')) jj--;
else ifs = xmprintf("%ld", (long)strlen(getvar(ss) ? : ""));
}
}
} else {
ss = str+--ii;
if (!(jj = varend(ss)-ss)) jj++;
ii += jj;
}
// ${#nom} ${} ${x}
// ${x:-y} use default
// ${x:=y} assign default (error if positional)
// ${x:?y} err if null
// ${x:+y} alt value
// ${x:off} ${x:off:len} off<0 from end (must ": -"), len<0 also from end must
// 0-based indexing
// ${@:off:len} positional parameters, off -1 = len, -len is error
// 1-based indexing
// ${!x} deref (does bad substitution if name has : in it)
// ${!x*} ${!x@} names matching prefix
// note: expands something other than arg->c
// ${x#y} remove shortest prefix ${x##y} remove longest prefix
// x can be @ or *
// ${x%y} ${x%%y} suffix
// ${x/pat/sub} substitute ${x//pat/sub} global ${x/#pat/sub} begin
// ${x/%pat/sub} end ${x/pat} delete pat
// x can be @ or *
// ${x^pat} ${x^^pat} uppercase/g ${x,} ${x,,} lowercase/g (no pat = ?)
// ${x@QEPAa} Q=$'blah' E=blah without the $'' wrap, P=expand as $PS1
// A=declare that recreates var a=attribute flags
// x can be @*
// TODO: $_ is last arg of last command, and exported as path to exe run
// TODO: $! is PID of most recent background job
if (ifs);
else if (cc == '-') {
s = ifs = xmalloc(8);
if (TT.options&OPT_I) *s++ = 'i';
if (TT.options&OPT_BRACE) *s++ = 'B';
if (TT.options&OPT_S) *s++ = 's';
if (TT.options&OPT_C) *s++ = 'c';
*s = 0;
} else if (cc == '?') ifs = xmprintf("%d", toys.exitval);
else if (cc == '$') ifs = xmprintf("%d", TT.pid);
else if (cc == '#') ifs = xmprintf("%d", TT.arg->c?TT.arg->c-1:0);
else if (cc == '*' || cc == '@') aa = TT.arg->v+1;
else if (isdigit(cc)) {
for (kk = ll = 0; kk<jj && isdigit(ss[kk]); kk++)
ll = (10*ll)+ss[kk]-'0';
if (ll) ll += TT.shift;
if (ll<TT.arg->c) ifs = TT.arg->v[ll];
nodel = 1;
// $VARIABLE
} else {
if (ss == varend(ss)) {
ii--;
if (ss[-1] == '$') new[oo++] = '$';
else ifs = (void *)1;
} else ifs = getvar(ss);
nodel = 1;
}
}
// TODO: $((a=42)) can change var, affect lifetime
// must replace ifs AND any previous output arg[] within pointer strlen()
// TODO ${blah} here
if (ifs == (void *)1) {
error_msg("%.*s: bad substitution", (int)(s-(str+ii)+3), str+ii-2);
free(new);
return 1;
}
// combine before/ifs/after sections, splitting words on $IFS in ifs
if (ifs || aa) {
char sep[8];
// If not gluing together, nothing to substitute, not quoted: do nothing
if (!aa && !*ifs && !qq) continue;
// Fetch separator
*sep = 0;
if ((qq&1) && cc=='*') {
wchar_t wc;
if (flags&SEMI_IFS) strcpy(sep, " ");
else if (0<(dd = utf8towc(&wc, TT.ifs, 4)))
sprintf(sep, "%.*s", dd, TT.ifs);
}