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