xref: /dragonfly/bin/sh/TOUR (revision cecb9aae)
1#	@(#)TOUR	8.1 (Berkeley) 5/31/93
2# $FreeBSD: head/bin/sh/TOUR 245689 2013-01-20 12:44:50Z jilles $
3
4NOTE -- This is the original TOUR paper distributed with ash and
5does not represent the current state of the shell.  It is provided anyway
6since it provides helpful information for how the shell is structured,
7but be warned that things have changed -- the current shell is
8still under development.
9
10================================================================
11
12                       A Tour through Ash
13
14               Copyright 1989 by Kenneth Almquist.
15
16
17DIRECTORIES:  The subdirectory bltin contains commands which can
18be compiled stand-alone.  The rest of the source is in the main
19ash directory.
20
21SOURCE CODE GENERATORS:  Files whose names begin with "mk" are
22programs that generate source code.  A complete list of these
23programs is:
24
25        program         input files         generates
26        -------         -----------         ---------
27        mkbuiltins      builtins            builtins.h builtins.c
28        mkinit          *.c                 init.c
29        mknodes         nodetypes           nodes.h nodes.c
30        mksyntax            -               syntax.h syntax.c
31        mktokens            -               token.h
32
33There are undoubtedly too many of these.  Mkinit searches all the
34C source files for entries looking like:
35
36        RESET {
37              x = 2;    /* executed when the shell does a longjmp
38                           back to the main command loop */
39        }
40
41It pulls this code out into routines which are when particular
42events occur.  The intent is to improve modularity by isolating
43the information about which modules need to be explicitly
44initialized/reset within the modules themselves.
45
46Mkinit recognizes several constructs for placing declarations in
47the init.c file.
48        INCLUDE "file.h"
49includes a file.  The storage class MKINIT makes a declaration
50available in the init.c file, for example:
51        MKINIT int funcnest;    /* depth of function calls */
52MKINIT alone on a line introduces a structure or union declara-
53tion:
54        MKINIT
55        struct redirtab {
56              short renamed[10];
57        };
58Preprocessor #define statements are copied to init.c without any
59special action to request this.
60
61EXCEPTIONS:  Code for dealing with exceptions appears in
62exceptions.c.  The C language doesn't include exception handling,
63so I implement it using setjmp and longjmp.  The global variable
64exception contains the type of exception.  EXERROR is raised by
65calling error.  EXINT is an interrupt.
66
67INTERRUPTS:  In an interactive shell, an interrupt will cause an
68EXINT exception to return to the main command loop.  (Exception:
69EXINT is not raised if the user traps interrupts using the trap
70command.)  The INTOFF and INTON macros (defined in exception.h)
71provide uninterruptible critical sections.  Between the execution
72of INTOFF and the execution of INTON, interrupt signals will be
73held for later delivery.  INTOFF and INTON can be nested.
74
75MEMALLOC.C:  Memalloc.c defines versions of malloc and realloc
76which call error when there is no memory left.  It also defines a
77stack oriented memory allocation scheme.  Allocating off a stack
78is probably more efficient than allocation using malloc, but the
79big advantage is that when an exception occurs all we have to do
80to free up the memory in use at the time of the exception is to
81restore the stack pointer.  The stack is implemented using a
82linked list of blocks.
83
84STPUTC:  If the stack were contiguous, it would be easy to store
85strings on the stack without knowing in advance how long the
86string was going to be:
87        p = stackptr;
88        *p++ = c;       /* repeated as many times as needed */
89        stackptr = p;
90The following three macros (defined in memalloc.h) perform these
91operations, but grow the stack if you run off the end:
92        STARTSTACKSTR(p);
93        STPUTC(c, p);   /* repeated as many times as needed */
94        grabstackstr(p);
95
96We now start a top-down look at the code:
97
98MAIN.C:  The main routine performs some initialization, executes
99the user's profile if necessary, and calls cmdloop.  Cmdloop
100repeatedly parses and executes commands.
101
102OPTIONS.C:  This file contains the option processing code.  It is
103called from main to parse the shell arguments when the shell is
104invoked, and it also contains the set builtin.  The -i and -m op-
105tions (the latter turns on job control) require changes in signal
106handling.  The routines setjobctl (in jobs.c) and setinteractive
107(in trap.c) are called to handle changes to these options.
108
109PARSING:  The parser code is all in parser.c.  A recursive des-
110cent parser is used.  Syntax tables (generated by mksyntax) are
111used to classify characters during lexical analysis.  There are
112four tables:  one for normal use, one for use when inside single
113quotes and dollar single quotes, one for use when inside double
114quotes and one for use in arithmetic.  The tables are machine
115dependent because they are indexed by character variables and
116the range of a char varies from machine to machine.
117
118PARSE OUTPUT:  The output of the parser consists of a tree of
119nodes.  The various types of nodes are defined in the file node-
120types.
121
122Nodes of type NARG are used to represent both words and the con-
123tents of here documents.  An early version of ash kept the con-
124tents of here documents in temporary files, but keeping here do-
125cuments in memory typically results in significantly better per-
126formance.  It would have been nice to make it an option to use
127temporary files for here documents, for the benefit of small
128machines, but the code to keep track of when to delete the tem-
129porary files was complex and I never fixed all the bugs in it.
130(AT&T has been maintaining the Bourne shell for more than ten
131years, and to the best of my knowledge they still haven't gotten
132it to handle temporary files correctly in obscure cases.)
133
134The text field of a NARG structure points to the text of the
135word.  The text consists of ordinary characters and a number of
136special codes defined in parser.h.  The special codes are:
137
138        CTLVAR              Variable substitution
139        CTLENDVAR           End of variable substitution
140        CTLBACKQ            Command substitution
141        CTLBACKQ|CTLQUOTE   Command substitution inside double quotes
142        CTLESC              Escape next character
143
144A variable substitution contains the following elements:
145
146        CTLVAR type name '=' [ alternative-text CTLENDVAR ]
147
148The type field is a single character specifying the type of sub-
149stitution.  The possible types are:
150
151        VSNORMAL            $var
152        VSMINUS             ${var-text}
153        VSMINUS|VSNUL       ${var:-text}
154        VSPLUS              ${var+text}
155        VSPLUS|VSNUL        ${var:+text}
156        VSQUESTION          ${var?text}
157        VSQUESTION|VSNUL    ${var:?text}
158        VSASSIGN            ${var=text}
159        VSASSIGN|VSNUL      ${var:=text}
160
161In addition, the type field will have the VSQUOTE flag set if the
162variable is enclosed in double quotes.  The name of the variable
163comes next, terminated by an equals sign.  If the type is not
164VSNORMAL, then the text field in the substitution follows, ter-
165minated by a CTLENDVAR byte.
166
167Commands in back quotes are parsed and stored in a linked list.
168The locations of these commands in the string are indicated by
169CTLBACKQ and CTLBACKQ+CTLQUOTE characters, depending upon whether
170the back quotes were enclosed in double quotes.
171
172The character CTLESC escapes the next character, so that in case
173any of the CTL characters mentioned above appear in the input,
174they can be passed through transparently.  CTLESC is also used to
175escape '*', '?', '[', and '!' characters which were quoted by the
176user and thus should not be used for file name generation.
177
178CTLESC characters have proved to be particularly tricky to get
179right.  In the case of here documents which are not subject to
180variable and command substitution, the parser doesn't insert any
181CTLESC characters to begin with (so the contents of the text
182field can be written without any processing).  Other here docu-
183ments, and words which are not subject to splitting and file name
184generation, have the CTLESC characters removed during the vari-
185able and command substitution phase.  Words which are subject to
186splitting and file name generation have the CTLESC characters re-
187moved as part of the file name phase.
188
189EXECUTION:  Command execution is handled by the following files:
190        eval.c     The top level routines.
191        redir.c    Code to handle redirection of input and output.
192        jobs.c     Code to handle forking, waiting, and job control.
193        exec.c     Code to do path searches and the actual exec sys call.
194        expand.c   Code to evaluate arguments.
195        var.c      Maintains the variable symbol table.  Called from expand.c.
196
197EVAL.C:  Evaltree recursively executes a parse tree.  The exit
198status is returned in the global variable exitstatus.  The alter-
199native entry evalbackcmd is called to evaluate commands in back
200quotes.  It saves the result in memory if the command is a buil-
201tin; otherwise it forks off a child to execute the command and
202connects the standard output of the child to a pipe.
203
204JOBS.C:  To create a process, you call makejob to return a job
205structure, and then call forkshell (passing the job structure as
206an argument) to create the process.  Waitforjob waits for a job
207to complete.  These routines take care of process groups if job
208control is defined.
209
210REDIR.C:  Ash allows file descriptors to be redirected and then
211restored without forking off a child process.  This is accom-
212plished by duplicating the original file descriptors.  The redir-
213tab structure records where the file descriptors have been dupli-
214cated to.
215
216EXEC.C:  The routine find_command locates a command, and enters
217the command in the hash table if it is not already there.  The
218third argument specifies whether it is to print an error message
219if the command is not found.  (When a pipeline is set up,
220find_command is called for all the commands in the pipeline be-
221fore any forking is done, so to get the commands into the hash
222table of the parent process.  But to make command hashing as
223transparent as possible, we silently ignore errors at that point
224and only print error messages if the command cannot be found
225later.)
226
227The routine shellexec is the interface to the exec system call.
228
229EXPAND.C:  Arguments are processed in three passes.  The first
230(performed by the routine argstr) performs variable and command
231substitution.  The second (ifsbreakup) performs word splitting
232and the third (expandmeta) performs file name generation.
233
234VAR.C:  Variables are stored in a hash table.  Probably we should
235switch to extensible hashing.  The variable name is stored in the
236same string as the value (using the format "name=value") so that
237no string copying is needed to create the environment of a com-
238mand.  Variables which the shell references internally are preal-
239located so that the shell can reference the values of these vari-
240ables without doing a lookup.
241
242When a program is run, the code in eval.c sticks any environment
243variables which precede the command (as in "PATH=xxx command") in
244the variable table as the simplest way to strip duplicates, and
245then calls "environment" to get the value of the environment.
246
247BUILTIN COMMANDS:  The procedures for handling these are scat-
248tered throughout the code, depending on which location appears
249most appropriate.  They can be recognized because their names al-
250ways end in "cmd".  The mapping from names to procedures is
251specified in the file builtins, which is processed by the mkbuilt-
252ins command.
253
254A builtin command is invoked with argc and argv set up like a
255normal program.  A builtin command is allowed to overwrite its
256arguments.  Builtin routines can call nextopt to do option pars-
257ing.  This is kind of like getopt, but you don't pass argc and
258argv to it.  Builtin routines can also call error.  This routine
259normally terminates the shell (or returns to the main command
260loop if the shell is interactive), but when called from a builtin
261command it causes the builtin command to terminate with an exit
262status of 2.
263
264The directory bltins contains commands which can be compiled in-
265dependently but can also be built into the shell for efficiency
266reasons.  The makefile in this directory compiles these programs
267in the normal fashion (so that they can be run regardless of
268whether the invoker is ash), but also creates a library named
269bltinlib.a which can be linked with ash.  The header file bltin.h
270takes care of most of the differences between the ash and the
271stand-alone environment.  The user should call the main routine
272"main", and #define main to be the name of the routine to use
273when the program is linked into ash.  This #define should appear
274before bltin.h is included; bltin.h will #undef main if the pro-
275gram is to be compiled stand-alone.
276
277CD.C:  This file defines the cd and pwd builtins.
278
279SIGNALS:  Trap.c implements the trap command.  The routine set-
280signal figures out what action should be taken when a signal is
281received and invokes the signal system call to set the signal ac-
282tion appropriately.  When a signal that a user has set a trap for
283is caught, the routine "onsig" sets a flag.  The routine dotrap
284is called at appropriate points to actually handle the signal.
285When an interrupt is caught and no trap has been set for that
286signal, the routine "onint" in error.c is called.
287
288OUTPUT:  Ash uses it's own output routines.  There are three out-
289put structures allocated.  "Output" represents the standard out-
290put, "errout" the standard error, and "memout" contains output
291which is to be stored in memory.  This last is used when a buil-
292tin command appears in backquotes, to allow its output to be col-
293lected without doing any I/O through the UNIX operating system.
294The variables out1 and out2 normally point to output and errout,
295respectively, but they are set to point to memout when appropri-
296ate inside backquotes.
297
298INPUT:  The basic input routine is pgetc, which reads from the
299current input file.  There is a stack of input files; the current
300input file is the top file on this stack.  The code allows the
301input to come from a string rather than a file.  (This is for the
302-c option and the "." and eval builtin commands.)  The global
303variable plinno is saved and restored when files are pushed and
304popped from the stack.  The parser routines store the number of
305the current line in this variable.
306
307DEBUGGING:  If DEBUG is defined in shell.h, then the shell will
308write debugging information to the file $HOME/trace.  Most of
309this is done using the TRACE macro, which takes a set of printf
310arguments inside two sets of parenthesis.  Example:
311"TRACE(("n=%d0, n))".  The double parenthesis are necessary be-
312cause the preprocessor can't handle functions with a variable
313number of arguments.  Defining DEBUG also causes the shell to
314generate a core dump if it is sent a quit signal.  The tracing
315code is in show.c.
316