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