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