TOUR revision 1.4
11.4Sjtc# @(#)TOUR 8.1 (Berkeley) 5/31/93 21.4Sjtc 31.4SjtcNOTE -- This is the original TOUR paper distributed with ash and 41.4Sjtcdoes not represent the current state of the shell. It is provided anyway 51.4Sjtcsince it provides helpful information for how the shell is structured, 61.4Sjtcbut be warned that things have changed -- the current shell is 71.4Sjtcstill under development. 81.4Sjtc 91.4Sjtc================================================================ 101.1Scgd 111.1Scgd A Tour through Ash 121.1Scgd 131.1Scgd Copyright 1989 by Kenneth Almquist. 141.1Scgd 151.1Scgd 161.1ScgdDIRECTORIES: The subdirectory bltin contains commands which can 171.1Scgdbe compiled stand-alone. The rest of the source is in the main 181.1Scgdash directory. 191.1Scgd 201.1ScgdSOURCE CODE GENERATORS: Files whose names begin with "mk" are 211.1Scgdprograms that generate source code. A complete list of these 221.1Scgdprograms is: 231.1Scgd 241.1Scgd program intput files generates 251.1Scgd ------- ------------ --------- 261.1Scgd mkbuiltins builtins builtins.h builtins.c 271.1Scgd mkinit *.c init.c 281.1Scgd mknodes nodetypes nodes.h nodes.c 291.1Scgd mksignames - signames.h signames.c 301.1Scgd mksyntax - syntax.h syntax.c 311.1Scgd mktokens - token.def 321.1Scgd bltin/mkexpr unary_op binary_op operators.h operators.c 331.1Scgd 341.1ScgdThere are undoubtedly too many of these. Mkinit searches all the 351.1ScgdC source files for entries looking like: 361.1Scgd 371.1Scgd INIT { 381.1Scgd x = 1; /* executed during initialization */ 391.1Scgd } 401.1Scgd 411.1Scgd RESET { 421.1Scgd x = 2; /* executed when the shell does a longjmp 431.1Scgd back to the main command loop */ 441.1Scgd } 451.1Scgd 461.1Scgd SHELLPROC { 471.1Scgd x = 3; /* executed when the shell runs a shell procedure */ 481.1Scgd } 491.1Scgd 501.1ScgdIt pulls this code out into routines which are when particular 511.1Scgdevents occur. The intent is to improve modularity by isolating 521.1Scgdthe information about which modules need to be explicitly 531.1Scgdinitialized/reset within the modules themselves. 541.1Scgd 551.1ScgdMkinit recognizes several constructs for placing declarations in 561.1Scgdthe init.c file. 571.1Scgd INCLUDE "file.h" 581.1Scgdincludes a file. The storage class MKINIT makes a declaration 591.1Scgdavailable in the init.c file, for example: 601.1Scgd MKINIT int funcnest; /* depth of function calls */ 611.1ScgdMKINIT alone on a line introduces a structure or union declara- 621.1Scgdtion: 631.1Scgd MKINIT 641.1Scgd struct redirtab { 651.1Scgd short renamed[10]; 661.1Scgd }; 671.1ScgdPreprocessor #define statements are copied to init.c without any 681.1Scgdspecial action to request this. 691.1Scgd 701.1ScgdINDENTATION: The ash source is indented in multiples of six 711.1Scgdspaces. The only study that I have heard of on the subject con- 721.1Scgdcluded that the optimal amount to indent is in the range of four 731.1Scgdto six spaces. I use six spaces since it is not too big a jump 741.1Scgdfrom the widely used eight spaces. If you really hate six space 751.1Scgdindentation, use the adjind (source included) program to change 761.1Scgdit to something else. 771.1Scgd 781.1ScgdEXCEPTIONS: Code for dealing with exceptions appears in 791.1Scgdexceptions.c. The C language doesn't include exception handling, 801.1Scgdso I implement it using setjmp and longjmp. The global variable 811.1Scgdexception contains the type of exception. EXERROR is raised by 821.1Scgdcalling error. EXINT is an interrupt. EXSHELLPROC is an excep- 831.1Scgdtion which is raised when a shell procedure is invoked. The pur- 841.1Scgdpose of EXSHELLPROC is to perform the cleanup actions associated 851.1Scgdwith other exceptions. After these cleanup actions, the shell 861.1Scgdcan interpret a shell procedure itself without exec'ing a new 871.1Scgdcopy of the shell. 881.1Scgd 891.1ScgdINTERRUPTS: In an interactive shell, an interrupt will cause an 901.1ScgdEXINT exception to return to the main command loop. (Exception: 911.1ScgdEXINT is not raised if the user traps interrupts using the trap 921.1Scgdcommand.) The INTOFF and INTON macros (defined in exception.h) 931.1Scgdprovide uninterruptable critical sections. Between the execution 941.1Scgdof INTOFF and the execution of INTON, interrupt signals will be 951.1Scgdheld for later delivery. INTOFF and INTON can be nested. 961.1Scgd 971.1ScgdMEMALLOC.C: Memalloc.c defines versions of malloc and realloc 981.1Scgdwhich call error when there is no memory left. It also defines a 991.1Scgdstack oriented memory allocation scheme. Allocating off a stack 1001.1Scgdis probably more efficient than allocation using malloc, but the 1011.1Scgdbig advantage is that when an exception occurs all we have to do 1021.1Scgdto free up the memory in use at the time of the exception is to 1031.1Scgdrestore the stack pointer. The stack is implemented using a 1041.1Scgdlinked list of blocks. 1051.1Scgd 1061.1ScgdSTPUTC: If the stack were contiguous, it would be easy to store 1071.1Scgdstrings on the stack without knowing in advance how long the 1081.1Scgdstring was going to be: 1091.1Scgd p = stackptr; 1101.1Scgd *p++ = c; /* repeated as many times as needed */ 1111.1Scgd stackptr = p; 1121.1ScgdThe folloing three macros (defined in memalloc.h) perform these 1131.1Scgdoperations, but grow the stack if you run off the end: 1141.1Scgd STARTSTACKSTR(p); 1151.1Scgd STPUTC(c, p); /* repeated as many times as needed */ 1161.1Scgd grabstackstr(p); 1171.1Scgd 1181.1ScgdWe now start a top-down look at the code: 1191.1Scgd 1201.1ScgdMAIN.C: The main routine performs some initialization, executes 1211.1Scgdthe user's profile if necessary, and calls cmdloop. Cmdloop is 1221.1Scgdrepeatedly parses and executes commands. 1231.1Scgd 1241.1ScgdOPTIONS.C: This file contains the option processing code. It is 1251.1Scgdcalled from main to parse the shell arguments when the shell is 1261.1Scgdinvoked, and it also contains the set builtin. The -i and -j op- 1271.1Scgdtions (the latter turns on job control) require changes in signal 1281.1Scgdhandling. The routines setjobctl (in jobs.c) and setinteractive 1291.1Scgd(in trap.c) are called to handle changes to these options. 1301.1Scgd 1311.1ScgdPARSING: The parser code is all in parser.c. A recursive des- 1321.1Scgdcent parser is used. Syntax tables (generated by mksyntax) are 1331.1Scgdused to classify characters during lexical analysis. There are 1341.1Scgdthree tables: one for normal use, one for use when inside single 1351.1Scgdquotes, and one for use when inside double quotes. The tables 1361.1Scgdare machine dependent because they are indexed by character vari- 1371.1Scgdables and the range of a char varies from machine to machine. 1381.1Scgd 1391.1ScgdPARSE OUTPUT: The output of the parser consists of a tree of 1401.1Scgdnodes. The various types of nodes are defined in the file node- 1411.1Scgdtypes. 1421.1Scgd 1431.1ScgdNodes of type NARG are used to represent both words and the con- 1441.1Scgdtents of here documents. An early version of ash kept the con- 1451.1Scgdtents of here documents in temporary files, but keeping here do- 1461.1Scgdcuments in memory typically results in significantly better per- 1471.1Scgdformance. It would have been nice to make it an option to use 1481.1Scgdtemporary files for here documents, for the benefit of small 1491.1Scgdmachines, but the code to keep track of when to delete the tem- 1501.1Scgdporary files was complex and I never fixed all the bugs in it. 1511.1Scgd(AT&T has been maintaining the Bourne shell for more than ten 1521.1Scgdyears, and to the best of my knowledge they still haven't gotten 1531.1Scgdit to handle temporary files correctly in obscure cases.) 1541.1Scgd 1551.1ScgdThe text field of a NARG structure points to the text of the 1561.1Scgdword. The text consists of ordinary characters and a number of 1571.1Scgdspecial codes defined in parser.h. The special codes are: 1581.1Scgd 1591.1Scgd CTLVAR Variable substitution 1601.1Scgd CTLENDVAR End of variable substitution 1611.1Scgd CTLBACKQ Command substitution 1621.1Scgd CTLBACKQ|CTLQUOTE Command substitution inside double quotes 1631.1Scgd CTLESC Escape next character 1641.1Scgd 1651.1ScgdA variable substitution contains the following elements: 1661.1Scgd 1671.1Scgd CTLVAR type name '=' [ alternative-text CTLENDVAR ] 1681.1Scgd 1691.1ScgdThe type field is a single character specifying the type of sub- 1701.1Scgdstitution. The possible types are: 1711.1Scgd 1721.1Scgd VSNORMAL $var 1731.1Scgd VSMINUS ${var-text} 1741.1Scgd VSMINUS|VSNUL ${var:-text} 1751.1Scgd VSPLUS ${var+text} 1761.1Scgd VSPLUS|VSNUL ${var:+text} 1771.1Scgd VSQUESTION ${var?text} 1781.1Scgd VSQUESTION|VSNUL ${var:?text} 1791.1Scgd VSASSIGN ${var=text} 1801.1Scgd VSASSIGN|VSNUL ${var=text} 1811.1Scgd 1821.1ScgdIn addition, the type field will have the VSQUOTE flag set if the 1831.1Scgdvariable is enclosed in double quotes. The name of the variable 1841.1Scgdcomes next, terminated by an equals sign. If the type is not 1851.1ScgdVSNORMAL, then the text field in the substitution follows, ter- 1861.1Scgdminated by a CTLENDVAR byte. 1871.1Scgd 1881.1ScgdCommands in back quotes are parsed and stored in a linked list. 1891.1ScgdThe locations of these commands in the string are indicated by 1901.1ScgdCTLBACKQ and CTLBACKQ+CTLQUOTE characters, depending upon whether 1911.1Scgdthe back quotes were enclosed in double quotes. 1921.1Scgd 1931.1ScgdThe character CTLESC escapes the next character, so that in case 1941.1Scgdany of the CTL characters mentioned above appear in the input, 1951.1Scgdthey can be passed through transparently. CTLESC is also used to 1961.1Scgdescape '*', '?', '[', and '!' characters which were quoted by the 1971.1Scgduser and thus should not be used for file name generation. 1981.1Scgd 1991.1ScgdCTLESC characters have proved to be particularly tricky to get 2001.1Scgdright. In the case of here documents which are not subject to 2011.1Scgdvariable and command substitution, the parser doesn't insert any 2021.1ScgdCTLESC characters to begin with (so the contents of the text 2031.1Scgdfield can be written without any processing). Other here docu- 2041.1Scgdments, and words which are not subject to splitting and file name 2051.1Scgdgeneration, have the CTLESC characters removed during the vari- 2061.1Scgdable and command substitution phase. Words which are subject 2071.1Scgdsplitting and file name generation have the CTLESC characters re- 2081.1Scgdmoved as part of the file name phase. 2091.1Scgd 2101.1ScgdEXECUTION: Command execution is handled by the following files: 2111.1Scgd eval.c The top level routines. 2121.1Scgd redir.c Code to handle redirection of input and output. 2131.1Scgd jobs.c Code to handle forking, waiting, and job control. 2141.1Scgd exec.c Code to to path searches and the actual exec sys call. 2151.1Scgd expand.c Code to evaluate arguments. 2161.1Scgd var.c Maintains the variable symbol table. Called from expand.c. 2171.1Scgd 2181.1ScgdEVAL.C: Evaltree recursively executes a parse tree. The exit 2191.1Scgdstatus is returned in the global variable exitstatus. The alter- 2201.1Scgdnative entry evalbackcmd is called to evaluate commands in back 2211.1Scgdquotes. It saves the result in memory if the command is a buil- 2221.1Scgdtin; otherwise it forks off a child to execute the command and 2231.1Scgdconnects the standard output of the child to a pipe. 2241.1Scgd 2251.1ScgdJOBS.C: To create a process, you call makejob to return a job 2261.1Scgdstructure, and then call forkshell (passing the job structure as 2271.1Scgdan argument) to create the process. Waitforjob waits for a job 2281.1Scgdto complete. These routines take care of process groups if job 2291.1Scgdcontrol is defined. 2301.1Scgd 2311.1ScgdREDIR.C: Ash allows file descriptors to be redirected and then 2321.1Scgdrestored without forking off a child process. This is accom- 2331.1Scgdplished by duplicating the original file descriptors. The redir- 2341.1Scgdtab structure records where the file descriptors have be dupli- 2351.1Scgdcated to. 2361.1Scgd 2371.1ScgdEXEC.C: The routine find_command locates a command, and enters 2381.1Scgdthe command in the hash table if it is not already there. The 2391.1Scgdthird argument specifies whether it is to print an error message 2401.1Scgdif the command is not found. (When a pipeline is set up, 2411.1Scgdfind_command is called for all the commands in the pipeline be- 2421.1Scgdfore any forking is done, so to get the commands into the hash 2431.1Scgdtable of the parent process. But to make command hashing as 2441.1Scgdtransparent as possible, we silently ignore errors at that point 2451.1Scgdand only print error messages if the command cannot be found 2461.1Scgdlater.) 2471.1Scgd 2481.1ScgdThe routine shellexec is the interface to the exec system call. 2491.1Scgd 2501.1ScgdEXPAND.C: Arguments are processed in three passes. The first 2511.1Scgd(performed by the routine argstr) performs variable and command 2521.1Scgdsubstitution. The second (ifsbreakup) performs word splitting 2531.1Scgdand the third (expandmeta) performs file name generation. If the 2541.1Scgd"/u" directory is simulated, then when "/u/username" is replaced 2551.1Scgdby the user's home directory, the flag "didudir" is set. This 2561.1Scgdtells the cd command that it should print out the directory name, 2571.1Scgdjust as it would if the "/u" directory were implemented using 2581.1Scgdsymbolic links. 2591.1Scgd 2601.1ScgdVAR.C: Variables are stored in a hash table. Probably we should 2611.1Scgdswitch to extensible hashing. The variable name is stored in the 2621.1Scgdsame string as the value (using the format "name=value") so that 2631.1Scgdno string copying is needed to create the environment of a com- 2641.1Scgdmand. Variables which the shell references internally are preal- 2651.1Scgdlocated so that the shell can reference the values of these vari- 2661.1Scgdables without doing a lookup. 2671.1Scgd 2681.1ScgdWhen a program is run, the code in eval.c sticks any environment 2691.1Scgdvariables which precede the command (as in "PATH=xxx command") in 2701.1Scgdthe variable table as the simplest way to strip duplicates, and 2711.1Scgdthen calls "environment" to get the value of the environment. 2721.1ScgdThere are two consequences of this. First, if an assignment to 2731.1ScgdPATH precedes the command, the value of PATH before the assign- 2741.1Scgdment must be remembered and passed to shellexec. Second, if the 2751.1Scgdprogram turns out to be a shell procedure, the strings from the 2761.1Scgdenvironment variables which preceded the command must be pulled 2771.1Scgdout of the table and replaced with strings obtained from malloc, 2781.1Scgdsince the former will automatically be freed when the stack (see 2791.1Scgdthe entry on memalloc.c) is emptied. 2801.1Scgd 2811.1ScgdBUILTIN COMMANDS: The procedures for handling these are scat- 2821.1Scgdtered throughout the code, depending on which location appears 2831.1Scgdmost appropriate. They can be recognized because their names al- 2841.1Scgdways end in "cmd". The mapping from names to procedures is 2851.1Scgdspecified in the file builtins, which is processed by the mkbuil- 2861.1Scgdtins command. 2871.1Scgd 2881.1ScgdA builtin command is invoked with argc and argv set up like a 2891.1Scgdnormal program. A builtin command is allowed to overwrite its 2901.1Scgdarguments. Builtin routines can call nextopt to do option pars- 2911.1Scgding. This is kind of like getopt, but you don't pass argc and 2921.1Scgdargv to it. Builtin routines can also call error. This routine 2931.1Scgdnormally terminates the shell (or returns to the main command 2941.1Scgdloop if the shell is interactive), but when called from a builtin 2951.1Scgdcommand it causes the builtin command to terminate with an exit 2961.1Scgdstatus of 2. 2971.1Scgd 2981.1ScgdThe directory bltins contains commands which can be compiled in- 2991.1Scgddependently but can also be built into the shell for efficiency 3001.1Scgdreasons. The makefile in this directory compiles these programs 3011.1Scgdin the normal fashion (so that they can be run regardless of 3021.1Scgdwhether the invoker is ash), but also creates a library named 3031.1Scgdbltinlib.a which can be linked with ash. The header file bltin.h 3041.1Scgdtakes care of most of the differences between the ash and the 3051.1Scgdstand-alone environment. The user should call the main routine 3061.1Scgd"main", and #define main to be the name of the routine to use 3071.1Scgdwhen the program is linked into ash. This #define should appear 3081.1Scgdbefore bltin.h is included; bltin.h will #undef main if the pro- 3091.1Scgdgram is to be compiled stand-alone. 3101.1Scgd 3111.1ScgdCD.C: This file defines the cd and pwd builtins. The pwd com- 3121.1Scgdmand runs /bin/pwd the first time it is invoked (unless the user 3131.1Scgdhas already done a cd to an absolute pathname), but then 3141.1Scgdremembers the current directory and updates it when the cd com- 3151.1Scgdmand is run, so subsequent pwd commands run very fast. The main 3161.1Scgdcomplication in the cd command is in the docd command, which 3171.1Scgdresolves symbolic links into actual names and informs the user 3181.1Scgdwhere the user ended up if he crossed a symbolic link. 3191.1Scgd 3201.1ScgdSIGNALS: Trap.c implements the trap command. The routine set- 3211.1Scgdsignal figures out what action should be taken when a signal is 3221.1Scgdreceived and invokes the signal system call to set the signal ac- 3231.1Scgdtion appropriately. When a signal that a user has set a trap for 3241.1Scgdis caught, the routine "onsig" sets a flag. The routine dotrap 3251.1Scgdis called at appropriate points to actually handle the signal. 3261.1ScgdWhen an interrupt is caught and no trap has been set for that 3271.1Scgdsignal, the routine "onint" in error.c is called. 3281.1Scgd 3291.1ScgdOUTPUT: Ash uses it's own output routines. There are three out- 3301.1Scgdput structures allocated. "Output" represents the standard out- 3311.1Scgdput, "errout" the standard error, and "memout" contains output 3321.1Scgdwhich is to be stored in memory. This last is used when a buil- 3331.1Scgdtin command appears in backquotes, to allow its output to be col- 3341.1Scgdlected without doing any I/O through the UNIX operating system. 3351.1ScgdThe variables out1 and out2 normally point to output and errout, 3361.1Scgdrespectively, but they are set to point to memout when appropri- 3371.1Scgdate inside backquotes. 3381.1Scgd 3391.1ScgdINPUT: The basic input routine is pgetc, which reads from the 3401.1Scgdcurrent input file. There is a stack of input files; the current 3411.1Scgdinput file is the top file on this stack. The code allows the 3421.1Scgdinput to come from a string rather than a file. (This is for the 3431.1Scgd-c option and the "." and eval builtin commands.) The global 3441.1Scgdvariable plinno is saved and restored when files are pushed and 3451.1Scgdpopped from the stack. The parser routines store the number of 3461.1Scgdthe current line in this variable. 3471.1Scgd 3481.1ScgdDEBUGGING: If DEBUG is defined in shell.h, then the shell will 3491.1Scgdwrite debugging information to the file $HOME/trace. Most of 3501.1Scgdthis is done using the TRACE macro, which takes a set of printf 3511.1Scgdarguments inside two sets of parenthesis. Example: 3521.1Scgd"TRACE(("n=%d0, n))". The double parenthesis are necessary be- 3531.1Scgdcause the preprocessor can't handle functions with a variable 3541.1Scgdnumber of arguments. Defining DEBUG also causes the shell to 3551.1Scgdgenerate a core dump if it is sent a quit signal. The tracing 3561.1Scgdcode is in show.c. 357