-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathash.c
executable file
·13460 lines (12343 loc) · 298 KB
/
ash.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
/* vi: set sw=4 ts=4: */
/*
* twigsh shell port for nest.yt
*
* derived from ash shell port for busybox
*
* This code is derived from software contributed to Berkeley by
* Kenneth Almquist.
*
* Original BSD copyright notice is retained at the end of this file.
*
* Copyright (c) 1989, 1991, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Copyright (c) 1997-2005 Herbert Xu <[email protected]>
* was re-ported from NetBSD and debianized.
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
/*
* The following should be set to reflect the type of system you have:
* JOBS -> 1 if you have Berkeley job control, 0 otherwise.
* define SYSV if you are running under System V.
* define DEBUG=1 to compile in debugging ('set -o debug' to turn on)
* define DEBUG=2 to compile in and turn on debugging.
*
* When debugging is on (DEBUG is 1 and "set -o debug" was executed),
* debugging info will be written to ./trace and a quit signal
* will generate a core dump.
*/
#define DEBUG 2
/* Tweak debug output verbosity here */
#define DEBUG_TIME 0
#define DEBUG_PID 1
#define DEBUG_SIG 1
#define PROFILE 0
#define JOBS ENABLE_ASH_JOB_CONTROL
#include <paths.h>
#include <setjmp.h>
#include <fnmatch.h>
#include <sys/times.h>
#include <sys/utsname.h> /* for setting $HOSTNAME */
#include "busybox.h" /* for applet_names */
#include "unicode.h"
#include "applet_tables.h"
#include "shell_common.h"
#if ENABLE_SH_MATH_SUPPORT
# include "math.h"
#endif
#if ENABLE_ASH_RANDOM_SUPPORT
# include "random.h"
#else
# define CLEAR_RANDOM_T(rnd) ((void)0)
#endif
#include "NUM_APPLETS.h"
#if NUM_APPLETS == 1
/* STANDALONE does not make sense, and won't compile */
# undef CONFIG_FEATURE_SH_STANDALONE
# undef ENABLE_FEATURE_SH_STANDALONE
# undef IF_FEATURE_SH_STANDALONE
# undef IF_NOT_FEATURE_SH_STANDALONE
# define ENABLE_FEATURE_SH_STANDALONE 0
# define IF_FEATURE_SH_STANDALONE(...)
# define IF_NOT_FEATURE_SH_STANDALONE(...) __VA_ARGS__
#endif
#ifndef PIPE_BUF
# define PIPE_BUF 4096 /* amount of buffering in a pipe */
#endif
#if !BB_MMU
# error "Do not even bother, ash will not run on NOMMU machine"
#endif
const char *applet_name="twigsh";
//config:config ASH
//config: bool "ash"
//config: default y
//config: depends on !NOMMU
//config: help
//config: Tha 'ash' shell adds about 60k in the default configuration and is
//config: the most complete and most pedantically correct shell included with
//config: busybox. This shell is actually a derivative of the Debian 'dash'
//config: shell (by Herbert Xu), which was created by porting the 'ash' shell
//config: (written by Kenneth Almquist) from NetBSD.
//config:
//config:config ASH_BASH_COMPAT
//config: bool "bash-compatible extensions"
//config: default y
//config: depends on ASH
//config: help
//config: Enable bash-compatible extensions.
//config:
//config:config ASH_IDLE_TIMEOUT
//config: bool "Idle timeout variable"
//config: default n
//config: depends on ASH
//config: help
//config: Enables bash-like auto-logout after $TMOUT seconds of idle time.
//config:
//config:config ASH_JOB_CONTROL
//config: bool "Job control"
//config: default y
//config: depends on ASH
//config: help
//config: Enable job control in the ash shell.
//config:
//config:config ASH_ALIAS
//config: bool "Alias support"
//config: default y
//config: depends on ASH
//config: help
//config: Enable alias support in the ash shell.
//config:
//config:config ASH_GETOPTS
//config: bool "Builtin getopt to parse positional parameters"
//config: default y
//config: depends on ASH
//config: help
//config: Enable support for getopts builtin in ash.
//config:
//config:config ASH_BUILTIN_ECHO
//config: bool "Builtin version of 'echo'"
//config: default y
//config: depends on ASH
//config: help
//config: Enable support for echo builtin in ash.
//config:
//config:config ASH_BUILTIN_PRINTF
//config: bool "Builtin version of 'printf'"
//config: default y
//config: depends on ASH
//config: help
//config: Enable support for printf builtin in ash.
//config:
//config:config ASH_BUILTIN_TEST
//config: bool "Builtin version of 'test'"
//config: default y
//config: depends on ASH
//config: help
//config: Enable support for test builtin in ash.
//config:
//config:config ASH_HELP
//config: bool "help builtin"
//config: default y
//config: depends on ASH
//config: help
//config: Enable help builtin in ash.
//config:
//config:config ASH_CMDCMD
//config: bool "'command' command to override shell builtins"
//config: default y
//config: depends on ASH
//config: help
//config: Enable support for the ash 'command' builtin, which allows
//config: you to run the specified command with the specified arguments,
//config: even when there is an ash builtin command with the same name.
//config:
//config:config ASH_MAIL
//config: bool "Check for new mail on interactive shells"
//config: default n
//config: depends on ASH
//config: help
//config: Enable "check for new mail" function in the ash shell.
//config:
//config:config ASH_OPTIMIZE_FOR_SIZE
//config: bool "Optimize for size instead of speed"
//config: default y
//config: depends on ASH
//config: help
//config: Compile ash for reduced size at the price of speed.
//config:
//config:config ASH_RANDOM_SUPPORT
//config: bool "Pseudorandom generator and $RANDOM variable"
//config: default y
//config: depends on ASH
//config: help
//config: Enable pseudorandom generator and dynamic variable "$RANDOM".
//config: Each read of "$RANDOM" will generate a new pseudorandom value.
//config: You can reset the generator by using a specified start value.
//config: After "unset RANDOM" the generator will switch off and this
//config: variable will no longer have special treatment.
//config:
//config:config ASH_EXPAND_PRMT
//config: bool "Expand prompt string"
//config: default y
//config: depends on ASH
//config: help
//config: "PS#" may contain volatile content, such as backquote commands.
//config: This option recreates the prompt string from the environment
//config: variable each time it is displayed.
//config:
//applet:IF_ASH(APPLET(ash, BB_DIR_BIN, BB_SUID_DROP))
//applet:IF_FEATURE_SH_IS_ASH(APPLET_ODDNAME(sh, ash, BB_DIR_BIN, BB_SUID_DROP, sh))
//applet:IF_FEATURE_BASH_IS_ASH(APPLET_ODDNAME(bash, ash, BB_DIR_BIN, BB_SUID_DROP, bash))
//kbuild:lib-$(CONFIG_ASH) += ash.o ash_ptr_hack.o shell_common.o
//kbuild:lib-$(CONFIG_ASH_RANDOM_SUPPORT) += random.o
/* ============ Hash table sizes. Configurable. */
#define VTABSIZE 39
#define ATABSIZE 39
#define CMDTABLESIZE 31 /* should be prime */
/* ============ Shell options */
static const char *const optletters_optnames[] = {
"e" "errexit",
"f" "noglob",
"I" "ignoreeof",
"i" "interactive",
"m" "monitor",
"n" "noexec",
"s" "stdin",
"x" "xtrace",
"v" "verbose",
"C" "noclobber",
"a" "allexport",
"b" "notify",
"u" "nounset",
"\0" "vi"
#if ENABLE_ASH_BASH_COMPAT
,"\0" "pipefail"
#endif
#if DEBUG
,"\0" "nolog"
,"\0" "debug"
#endif
};
#define optletters(n) optletters_optnames[n][0]
#define optnames(n) (optletters_optnames[n] + 1)
enum { NOPTS = ARRAY_SIZE(optletters_optnames) };
/* ============ Misc data */
#define msg_illnum "Illegal number: %s"
/*
* We enclose jmp_buf in a structure so that we can declare pointers to
* jump locations. The global variable handler contains the location to
* jump to when an exception occurs, and the global variable exception_type
* contains a code identifying the exception. To implement nested
* exception handlers, the user should save the value of handler on entry
* to an inner scope, set handler to point to a jmploc structure for the
* inner scope, and restore handler on exit from the scope.
*/
struct jmploc {
jmp_buf loc;
};
struct globals_misc {
/* pid of main shell */
int rootpid;
/* shell level: 0 for the main shell, 1 for its children, and so on */
int shlvl;
#define rootshell (!shlvl)
char *minusc; /* argument to -c option */
char *minusg; /* argument to -d option */
char *curdir; // = nullstr; /* current working directory */
char *physdir; // = nullstr; /* physical working directory */
char *arg0; /* value of $0 */
struct jmploc *exception_handler;
volatile int suppress_int; /* counter */
volatile /*sig_atomic_t*/ smallint pending_int; /* 1 = got SIGINT */
/* last pending signal */
volatile /*sig_atomic_t*/ smallint pending_sig;
smallint exception_type; /* kind of exception (0..5) */
/* exceptions */
#define EXINT 0 /* SIGINT received */
#define EXERROR 1 /* a generic error */
#define EXSHELLPROC 2 /* execute a shell procedure */
#define EXEXEC 3 /* command execution failed */
#define EXEXIT 4 /* exit the shell */
#define EXSIG 5 /* trapped signal in wait(1) */
smallint isloginsh;
char nullstr[1]; /* zero length string */
char optlist[NOPTS];
#define eflag optlist[0]
#define fflag optlist[1]
#define Iflag optlist[2]
#define iflag optlist[3]
#define mflag optlist[4]
#define nflag optlist[5]
#define sflag optlist[6]
#define xflag optlist[7]
#define vflag optlist[8]
#define Cflag optlist[9]
#define aflag optlist[10]
#define bflag optlist[11]
#define uflag optlist[12]
#define viflag optlist[13]
#if ENABLE_ASH_BASH_COMPAT
# define pipefail optlist[14]
#else
# define pipefail 0
#endif
#if DEBUG
# define nolog optlist[14 + ENABLE_ASH_BASH_COMPAT]
# define debug optlist[15 + ENABLE_ASH_BASH_COMPAT]
#endif
/* trap handler commands */
/*
* Sigmode records the current value of the signal handlers for the various
* modes. A value of zero means that the current handler is not known.
* S_HARD_IGN indicates that the signal was ignored on entry to the shell.
*/
char sigmode[NSIG - 1];
#define S_DFL 1 /* default signal handling (SIG_DFL) */
#define S_CATCH 2 /* signal is caught */
#define S_IGN 3 /* signal is ignored (SIG_IGN) */
#define S_HARD_IGN 4 /* signal is ignored permenantly */
/* indicates specified signal received */
uint8_t gotsig[NSIG - 1]; /* offset by 1: "signal" 0 is meaningless */
uint8_t may_have_traps; /* 0: definitely no traps are set, 1: some traps may be set */
char *trap[NSIG];
char **trap_ptr; /* used only by "trap hack" */
/* Rarely referenced stuff */
#if ENABLE_ASH_RANDOM_SUPPORT
random_t random_gen;
#endif
pid_t backgndpid; /* pid of last background process */
smallint job_warning; /* user was warned about stopped jobs (can be 2, 1 or 0). */
};
extern struct globals_misc *const ash_ptr_to_globals_misc;
#define G_misc (*ash_ptr_to_globals_misc)
#define rootpid (G_misc.rootpid )
#define shlvl (G_misc.shlvl )
#define minusc (G_misc.minusc )
#define minusg (G_misc.minusg )
#define curdir (G_misc.curdir )
#define physdir (G_misc.physdir )
#define arg0 (G_misc.arg0 )
#define exception_handler (G_misc.exception_handler)
#define exception_type (G_misc.exception_type )
#define suppress_int (G_misc.suppress_int )
#define pending_int (G_misc.pending_int )
#define pending_sig (G_misc.pending_sig )
#define isloginsh (G_misc.isloginsh )
#define nullstr (G_misc.nullstr )
#define optlist (G_misc.optlist )
#define sigmode (G_misc.sigmode )
#define gotsig (G_misc.gotsig )
#define may_have_traps (G_misc.may_have_traps )
#define trap (G_misc.trap )
#define trap_ptr (G_misc.trap_ptr )
#define random_gen (G_misc.random_gen )
#define backgndpid (G_misc.backgndpid )
#define job_warning (G_misc.job_warning)
#define INIT_G_misc() do { \
(*(struct globals_misc**)&ash_ptr_to_globals_misc) = xzalloc(sizeof(G_misc)); \
barrier(); \
curdir = nullstr; \
physdir = nullstr; \
trap_ptr = trap; \
} while (0)
/* ============ DEBUG */
#if DEBUG
static void trace_printf(const char *fmt, ...);
static void trace_vprintf(const char *fmt, va_list va);
# define TRACE(param) trace_printf param
# define TRACEV(param) trace_vprintf param
# define close(fd) do { \
int dfd = (fd); \
if (close(dfd) < 0) \
bb_error_msg("bug on %d: closing %d(0x%x)", \
__LINE__, dfd, dfd); \
} while (0)
#else
# define TRACE(param)
# define TRACEV(param)
#endif
/* ============ Utility functions */
#define xbarrier() do { __asm__ __volatile__ ("": : :"memory"); } while (0)
#define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
#define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
static int isdigit_str9(const char *str)
{
int maxlen = 9 + 1; /* max 9 digits: 999999999 */
while (--maxlen && isdigit(*str))
str++;
return (*str == '\0');
}
static const char *var_end(const char *var)
{
while (*var)
if (*var++ == '=')
break;
return var;
}
/* ============ Interrupts / exceptions */
static void exitshell(void) NORETURN;
/*
* These macros allow the user to suspend the handling of interrupt signals
* over a period of time. This is similar to SIGHOLD or to sigblock, but
* much more efficient and portable. (But hacking the kernel is so much
* more fun than worrying about efficiency and portability. :-))
*/
#define INT_OFF do { \
suppress_int++; \
xbarrier(); \
} while (0)
/*
* Called to raise an exception. Since C doesn't include exceptions, we
* just do a longjmp to the exception handler. The type of exception is
* stored in the global variable "exception_type".
*/
static void raise_exception(int) NORETURN;
static void
raise_exception(int e)
{
#if DEBUG
if (exception_handler == NULL)
abort();
#endif
INT_OFF;
exception_type = e;
longjmp(exception_handler->loc, 1);
}
#if DEBUG
#define raise_exception(e) do { \
TRACE(("raising exception %d on line %d\n", (e), __LINE__)); \
raise_exception(e); \
} while (0)
#endif
/*
* Called from trap.c when a SIGINT is received. (If the user specifies
* that SIGINT is to be trapped or ignored using the trap builtin, then
* this routine is not called.) Suppressint is nonzero when interrupts
* are held using the INT_OFF macro. (The test for iflag is just
* defensive programming.)
*/
static void raise_interrupt(void) NORETURN;
static void
raise_interrupt(void)
{
int ex_type;
pending_int = 0;
/* Signal is not automatically unmasked after it is raised,
* do it ourself - unmask all signals */
sigprocmask_allsigs(SIG_UNBLOCK);
/* pending_sig = 0; - now done in signal_handler() */
ex_type = EXSIG;
if (gotsig[SIGINT - 1] && !trap[SIGINT]) {
if (!(rootshell && iflag)) {
/* Kill ourself with SIGINT */
signal(SIGINT, SIG_DFL);
raise(SIGINT);
}
ex_type = EXINT;
}
raise_exception(ex_type);
/* NOTREACHED */
}
#if DEBUG
#define raise_interrupt() do { \
TRACE(("raising interrupt on line %d\n", __LINE__)); \
raise_interrupt(); \
} while (0)
#endif
static inline void
int_on(void)
{
xbarrier();
if (--suppress_int == 0 && pending_int) {
raise_interrupt();
}
}
#define INT_ON int_on()
static inline void
force_int_on(void)
{
xbarrier();
suppress_int = 0;
if (pending_int)
raise_interrupt();
}
#define FORCE_INT_ON force_int_on()
#define SAVE_INT(v) ((v) = suppress_int)
#define RESTORE_INT(v) do { \
xbarrier(); \
suppress_int = (v); \
if (suppress_int == 0 && pending_int) \
raise_interrupt(); \
} while (0)
/* ============ Stdout/stderr output */
static void
outstr(const char *p, FILE *file)
{
INT_OFF;
fputs(p, file);
INT_ON;
}
static void
flush_stdout_stderr(void)
{
INT_OFF;
fflush_all();
INT_ON;
}
/* Was called outcslow(c,FILE*), but c was always '\n' */
static void
newline_and_flush(FILE *dest)
{
INT_OFF;
putc('\n', dest);
fflush(dest);
INT_ON;
}
static int out1fmt(const char *, ...) __attribute__((__format__(__printf__,1,2)));
static int
out1fmt(const char *fmt, ...)
{
va_list ap;
int r;
INT_OFF;
va_start(ap, fmt);
r = vprintf(fmt, ap);
va_end(ap);
INT_ON;
return r;
}
static int fmtstr(char *, size_t, const char *, ...) __attribute__((__format__(__printf__,3,4)));
static int
fmtstr(char *outbuf, size_t length, const char *fmt, ...)
{
va_list ap;
int ret;
va_start(ap, fmt);
INT_OFF;
ret = vsnprintf(outbuf, length, fmt, ap);
va_end(ap);
INT_ON;
return ret;
}
static void
out1str(const char *p)
{
outstr(p, stdout);
}
static void
out2str(const char *p)
{
outstr(p, stderr);
flush_stdout_stderr();
}
/* ============ Parser structures */
/* control characters in argument strings */
#define CTL_FIRST CTLESC
#define CTLESC ((unsigned char)'\201') /* escape next character */
#define CTLVAR ((unsigned char)'\202') /* variable defn */
#define CTLENDVAR ((unsigned char)'\203')
#define CTLBACKQ ((unsigned char)'\204')
#define CTLARI ((unsigned char)'\206') /* arithmetic expression */
#define CTLENDARI ((unsigned char)'\207')
#define CTLQUOTEMARK ((unsigned char)'\210')
#define CTL_LAST CTLQUOTEMARK
/* variable substitution byte (follows CTLVAR) */
#define VSTYPE 0x0f /* type of variable substitution */
#define VSNUL 0x10 /* colon--treat the empty string as unset */
/* values of VSTYPE field */
#define VSNORMAL 0x1 /* normal variable: $var or ${var} */
#define VSMINUS 0x2 /* ${var-text} */
#define VSPLUS 0x3 /* ${var+text} */
#define VSQUESTION 0x4 /* ${var?message} */
#define VSASSIGN 0x5 /* ${var=text} */
#define VSTRIMRIGHT 0x6 /* ${var%pattern} */
#define VSTRIMRIGHTMAX 0x7 /* ${var%%pattern} */
#define VSTRIMLEFT 0x8 /* ${var#pattern} */
#define VSTRIMLEFTMAX 0x9 /* ${var##pattern} */
#define VSLENGTH 0xa /* ${#var} */
#if ENABLE_ASH_BASH_COMPAT
#define VSSUBSTR 0xc /* ${var:position:length} */
#define VSREPLACE 0xd /* ${var/pattern/replacement} */
#define VSREPLACEALL 0xe /* ${var//pattern/replacement} */
#endif
static const char dolatstr[] ALIGN1 = {
CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', CTLQUOTEMARK, '\0'
};
#define DOLATSTRLEN 6
#define NCMD 0
#define NPIPE 1
#define NREDIR 2
#define NBACKGND 3
#define NSUBSHELL 4
#define NAND 5
#define NOR 6
#define NSEMI 7
#define NIF 8
#define NWHILE 9
#define NUNTIL 10
#define NFOR 11
#define NCASE 12
#define NCLIST 13
#define NDEFUN 14
#define NARG 15
#define NTO 16
#if ENABLE_ASH_BASH_COMPAT
#define NTO2 17
#endif
#define NCLOBBER 18
#define NFROM 19
#define NFROMTO 20
#define NAPPEND 21
#define NTOFD 22
#define NFROMFD 23
#define NHERE 24
#define NXHERE 25
#define NNOT 26
#define N_NUMBER 27
union node;
struct ncmd {
smallint type; /* Nxxxx */
union node *assign;
union node *args;
union node *redirect;
};
struct npipe {
smallint type;
smallint pipe_backgnd;
struct nodelist *cmdlist;
};
struct nredir {
smallint type;
union node *n;
union node *redirect;
};
struct nbinary {
smallint type;
union node *ch1;
union node *ch2;
};
struct nif {
smallint type;
union node *test;
union node *ifpart;
union node *elsepart;
};
struct nfor {
smallint type;
union node *args;
union node *body;
char *var;
};
struct ncase {
smallint type;
union node *expr;
union node *cases;
};
struct nclist {
smallint type;
union node *next;
union node *pattern;
union node *body;
};
struct narg {
smallint type;
union node *next;
char *text;
struct nodelist *backquote;
};
/* nfile and ndup layout must match!
* NTOFD (>&fdnum) uses ndup structure, but we may discover mid-flight
* that it is actually NTO2 (>&file), and change its type.
*/
struct nfile {
smallint type;
union node *next;
int fd;
int _unused_dupfd;
union node *fname;
char *expfname;
};
struct ndup {
smallint type;
union node *next;
int fd;
int dupfd;
union node *vname;
char *_unused_expfname;
};
struct nhere {
smallint type;
union node *next;
int fd;
union node *doc;
};
struct nnot {
smallint type;
union node *com;
};
union node {
smallint type;
struct ncmd ncmd;
struct npipe npipe;
struct nredir nredir;
struct nbinary nbinary;
struct nif nif;
struct nfor nfor;
struct ncase ncase;
struct nclist nclist;
struct narg narg;
struct nfile nfile;
struct ndup ndup;
struct nhere nhere;
struct nnot nnot;
};
/*
* NODE_EOF is returned by parsecmd when it encounters an end of file.
* It must be distinct from NULL.
*/
#define NODE_EOF ((union node *) -1L)
struct nodelist {
struct nodelist *next;
union node *n;
};
struct funcnode {
int count;
union node n;
};
/*
* Free a parse tree.
*/
static void
freefunc(struct funcnode *f)
{
if (f && --f->count < 0)
free(f);
}
/* ============ Debugging output */
#if DEBUG
static FILE *tracefile;
static void
trace_printf(const char *fmt, ...)
{
va_list va;
if (debug != 1)
return;
if (DEBUG_TIME)
fprintf(tracefile, "%u ", (int) time(NULL));
if (DEBUG_PID)
fprintf(tracefile, "[%u] ", (int) getpid());
if (DEBUG_SIG)
fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
va_start(va, fmt);
vfprintf(tracefile, fmt, va);
va_end(va);
}
static void
trace_vprintf(const char *fmt, va_list va)
{
if (debug != 1)
return;
if (DEBUG_TIME)
fprintf(tracefile, "%u ", (int) time(NULL));
if (DEBUG_PID)
fprintf(tracefile, "[%u] ", (int) getpid());
if (DEBUG_SIG)
fprintf(tracefile, "pending s:%d i:%d(supp:%d) ", pending_sig, pending_int, suppress_int);
vfprintf(tracefile, fmt, va);
}
static void
trace_puts(const char *s)
{
if (debug != 1)
return;
fputs(s, tracefile);
}
static void
trace_puts_quoted(char *s)
{
char *p;
char c;
if (debug != 1)
return;
putc('"', tracefile);
for (p = s; *p; p++) {
switch ((unsigned char)*p) {
case '\n': c = 'n'; goto backslash;
case '\t': c = 't'; goto backslash;
case '\r': c = 'r'; goto backslash;
case '\"': c = '\"'; goto backslash;
case '\\': c = '\\'; goto backslash;
case CTLESC: c = 'e'; goto backslash;
case CTLVAR: c = 'v'; goto backslash;
case CTLBACKQ: c = 'q'; goto backslash;
backslash:
putc('\\', tracefile);
putc(c, tracefile);
break;
default:
if (*p >= ' ' && *p <= '~')
putc(*p, tracefile);
else {
putc('\\', tracefile);
putc((*p >> 6) & 03, tracefile);
putc((*p >> 3) & 07, tracefile);
putc(*p & 07, tracefile);
}
break;
}
}
putc('"', tracefile);
}
static void
trace_puts_args(char **ap)
{
if (debug != 1)
return;
if (!*ap)
return;
while (1) {
trace_puts_quoted(*ap);
if (!*++ap) {
putc('\n', tracefile);
break;
}
putc(' ', tracefile);
}
}
static void
opentrace(void)
{
char s[100];
#ifdef O_APPEND
int flags;
#endif
if (debug != 1) {
if (tracefile)
fflush(tracefile);
/* leave open because libedit might be using it */
return;
}
strcpy(s, "./trace");
if (tracefile) {
if (!freopen(s, "a", tracefile)) {
fprintf(stderr, "Can't re-open %s\n", s);
debug = 0;
return;
}
} else {
tracefile = fopen(s, "a");
if (tracefile == NULL) {
fprintf(stderr, "Can't open %s\n", s);
debug = 0;
return;
}
}
#ifdef O_APPEND
flags = fcntl(fileno(tracefile), F_GETFL);
if (flags >= 0)
fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
#endif
setlinebuf(tracefile);
fputs("\nTracing started.\n", tracefile);
}
static void
indent(int amount, char *pfx, FILE *fp)
{
int i;
for (i = 0; i < amount; i++) {
if (pfx && i == amount - 1)
fputs(pfx, fp);
putc('\t', fp);
}
}
/* little circular references here... */
static void shtree(union node *n, int ind, char *pfx, FILE *fp);
static void
sharg(union node *arg, FILE *fp)
{
char *p;
struct nodelist *bqlist;
unsigned char subtype;
if (arg->type != NARG) {
out1fmt("<node type %d>\n", arg->type);
abort();
}
bqlist = arg->narg.backquote;
for (p = arg->narg.text; *p; p++) {
switch ((unsigned char)*p) {
case CTLESC:
p++;
putc(*p, fp);
break;
case CTLVAR:
putc('$', fp);
putc('{', fp);
subtype = *++p;
if (subtype == VSLENGTH)
putc('#', fp);
while (*p != '=') {
putc(*p, fp);
p++;
}
if (subtype & VSNUL)
putc(':', fp);
switch (subtype & VSTYPE) {
case VSNORMAL:
putc('}', fp);
break;