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