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