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