home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume19 / ash / part07 < prev    next >
Encoding:
Internet Message Format  |  1989-05-29  |  57.1 KB

  1. Subject:  v19i007:  A reimplementation of the System V shell, Part07/08
  2. Newsgroups: comp.sources.unix
  3. Sender: sources
  4. Approved: rsalz@uunet.UU.NET
  5.  
  6. Submitted-by: ka@june.cs.washington.edu (Kenneth Almquist)
  7. Posting-number: Volume 19, Issue 7
  8. Archive-name: ash/part07
  9.  
  10. # This is part 7 of ash.  To unpack, feed it into the shell (not csh).
  11. # The ash distribution consists of eight pieces.  Be sure you get them all.
  12. # After you unpack everything, read the file README.
  13.  
  14. echo extracting redir.h
  15. cat > redir.h <<\EOF
  16. /*
  17.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  18.  * This file is part of ash, which is distributed under the terms specified
  19.  * by the Ash General Public License.  See the file named LICENSE.
  20.  */
  21.  
  22. /* flags passed to redirect */
  23. #define REDIR_PUSH 01        /* save previous values of file descriptors */
  24. #define REDIR_BACKQ 02        /* save the command output in memory */
  25.  
  26. #ifdef __STDC__
  27. void redirect(union node *, int);
  28. void popredir(void);
  29. void clearredir(void);
  30. int copyfd(int, int);
  31. #else
  32. void redirect();
  33. void popredir();
  34. void clearredir();
  35. int copyfd();
  36. #endif
  37. EOF
  38. if test `wc -c < redir.h` -ne 578
  39. then    echo 'redir.h is the wrong size'
  40. fi
  41. echo extracting redir.c
  42. cat > redir.c <<\EOF
  43. /*
  44.  * Code for dealing with input/output redirection.
  45.  *
  46.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  47.  * This file is part of ash, which is distributed under the terms specified
  48.  * by the Ash General Public License.  See the file named LICENSE.
  49.  */
  50.  
  51. #include "shell.h"
  52. #include "nodes.h"
  53. #include "jobs.h"
  54. #include "expand.h"
  55. #include "redir.h"
  56. #include "output.h"
  57. #include "memalloc.h"
  58. #include "error.h"
  59. #include <signal.h>
  60. #include <fcntl.h>
  61. #include "myerrno.h"
  62.  
  63.  
  64. #define EMPTY -2        /* marks an unused slot in redirtab */
  65. #define PIPESIZE 4096        /* amount of buffering in a pipe */
  66.  
  67.  
  68. MKINIT
  69. struct redirtab {
  70.       struct redirtab *next;
  71.       short renamed[10];
  72. };
  73.  
  74.  
  75. MKINIT struct redirtab *redirlist;
  76.  
  77.  
  78. #ifdef __STDC__
  79. STATIC void openredirect(union node *, char *);
  80. STATIC int openhere(union node *);
  81. #else
  82. STATIC void openredirect();
  83. STATIC int openhere();
  84. #endif
  85.  
  86.  
  87.  
  88. /*
  89.  * Process a list of redirection commands.  If the REDIR_PUSH flag is set,
  90.  * old file descriptors are stashed away so that the redirection can be
  91.  * undone by calling popredir.  If the REDIR_BACKQ flag is set, then the
  92.  * standard output, and the standard error if it becomes a duplicate of
  93.  * stdout, is saved in memory.
  94.  */
  95.  
  96. void
  97. redirect(redir, flags)
  98.       union node *redir;
  99.       int flags;
  100.       {
  101.       union node *n;
  102.       struct redirtab *sv;
  103.       int i;
  104.       int fd;
  105.       char memory[10];        /* file descriptors to write to memory */
  106.  
  107.       for (i = 10 ; --i >= 0 ; )
  108.         memory[i] = 0;
  109.       memory[1] = flags & REDIR_BACKQ;
  110.       if (flags & REDIR_PUSH) {
  111.         sv = ckmalloc(sizeof (struct redirtab));
  112.         for (i = 0 ; i < 10 ; i++)
  113.           sv->renamed[i] = EMPTY;
  114.         sv->next = redirlist;
  115.         redirlist = sv;
  116.       }
  117.       for (n = redir ; n ; n = n->nfile.next) {
  118.         fd = n->nfile.fd;
  119.         if ((flags & REDIR_PUSH) && sv->renamed[fd] == EMPTY) {
  120.           INTOFF;
  121.           if ((i = copyfd(fd, 10)) != EMPTY) {
  122.             sv->renamed[fd] = i;
  123.             close(fd);
  124.           }
  125.           INTON;
  126.           if (i == EMPTY)
  127.             error("Out of file descriptors");
  128.         } else {
  129.           close(fd);
  130.         }
  131.         openredirect(n, memory);
  132.       }
  133.       if (memory[1])
  134.         out1 = &memout;
  135.       if (memory[2])
  136.         out2 = &memout;
  137. }
  138.  
  139.  
  140. STATIC void
  141. openredirect(redir, memory)
  142.       union node *redir;
  143.       char memory[10];
  144.       {
  145.       int fd = redir->nfile.fd;
  146.       char *fname;
  147.       int f;
  148.  
  149.       /*
  150.        * We suppress interrupts so that we won't leave open file
  151.        * descriptors around.  This may not be such a good idea because
  152.        * an open of a device or a fifo can block indefinitely.
  153.        */
  154.       INTOFF;
  155.       memory[fd] = 0;
  156.       switch (redir->nfile.type) {
  157.       case NFROM:
  158.         fname = redir->nfile.expfname;
  159.         if ((f = open(fname, O_RDONLY)) < 0)
  160.           error("cannot open %s: %s", fname, errmsg(errno, E_OPEN));
  161. movefd:
  162.         if (f != fd) {
  163.           copyfd(f, fd);
  164.           close(f);
  165.         }
  166.         break;
  167.       case NTO:
  168.         fname = redir->nfile.expfname;
  169. #ifdef O_CREAT
  170.         if ((f = open(fname, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)
  171.           error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
  172. #else
  173.         if ((f = creat(fname, 0666)) < 0)
  174.           error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
  175. #endif
  176.         goto movefd;
  177.       case NAPPEND:
  178.         fname = redir->nfile.expfname;
  179. #ifdef O_APPEND
  180.         if ((f = open(fname, O_WRONLY|O_CREAT|O_APPEND, 0666)) < 0)
  181.           error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
  182. #else
  183.         if ((f = open(fname, O_WRONLY)) < 0
  184.          && (f = creat(fname, 0666)) < 0)
  185.           error("cannot create %s: %s", fname, errmsg(errno, E_CREAT));
  186.         lseek(f, 0L, 2);
  187. #endif
  188.         goto movefd;
  189.       case NTOFD:
  190.       case NFROMFD:
  191.         if (redir->ndup.dupfd >= 0) {    /* if not ">&-" */
  192.           if (memory[redir->ndup.dupfd])
  193.             memory[fd] = 1;
  194.           else
  195.             copyfd(redir->ndup.dupfd, fd);
  196.         }
  197.         break;
  198.       case NHERE:
  199.       case NXHERE:
  200.         f = openhere(redir);
  201.         goto movefd;
  202.       default:
  203.         abort();
  204.       }
  205.       INTON;
  206. }
  207.  
  208.  
  209. /*
  210.  * Handle here documents.  Normally we fork off a process to write the
  211.  * data to a pipe.  If the document is short, we can stuff the data in
  212.  * the pipe without forking.
  213.  */
  214.  
  215. STATIC int
  216. openhere(redir)
  217.       union node *redir;
  218.       {
  219.       int pip[2];
  220.       int len;
  221.  
  222.       if (pipe(pip) < 0)
  223.         error("Pipe call failed");
  224.       if (redir->type == NHERE) {
  225.         len = strlen(redir->nhere.doc->narg.text);
  226.         if (len <= PIPESIZE) {
  227.           xwrite(pip[1], redir->nhere.doc->narg.text, len);
  228.           goto out;
  229.         }
  230.       }
  231.       if (forkshell((struct job *)NULL, (union node *)NULL, FORK_NOJOB) == 0) {
  232.         close(pip[0]);
  233.         signal(SIGINT, SIG_IGN);
  234.         signal(SIGQUIT, SIG_IGN);
  235.         signal(SIGHUP, SIG_IGN);
  236. #ifdef SIGTSTP
  237.         signal(SIGTSTP, SIG_IGN);
  238. #endif
  239.         signal(SIGPIPE, SIG_DFL);
  240.         if (redir->type == NHERE)
  241.           xwrite(pip[1], redir->nhere.doc->narg.text, len);
  242.         else
  243.           expandhere(redir->nhere.doc, pip[1]);
  244.         _exit(0);
  245.       }
  246. out:
  247.       close(pip[1]);
  248.       return pip[0];
  249. }
  250.  
  251.  
  252.  
  253. /*
  254.  * Undo the effects of the last redirection.
  255.  */
  256.  
  257. void
  258. popredir() {
  259.       register struct redirtab *rp = redirlist;
  260.       int i;
  261.  
  262.       for (i = 0 ; i < 10 ; i++) {
  263.         if (rp->renamed[i] != EMPTY) {
  264.           close(i);
  265.           if (rp->renamed[i] >= 0) {
  266.             copyfd(rp->renamed[i], i);
  267.             close(rp->renamed[i]);
  268.           }
  269.         }
  270.       }
  271.       INTOFF;
  272.       redirlist = rp->next;
  273.       ckfree(rp);
  274.       INTON;
  275. }
  276.  
  277.  
  278.  
  279. /*
  280.  * Undo all redirections.  Called on error or interrupt.
  281.  */
  282.  
  283. #ifdef mkinit
  284.  
  285. INCLUDE "redir.h"
  286.  
  287. RESET {
  288.       while (redirlist)
  289.         popredir();
  290. }
  291.  
  292. SHELLPROC {
  293.       clearredir();
  294. }
  295.  
  296. #endif
  297.  
  298.  
  299. /*
  300.  * Discard all saved file descriptors.
  301.  */
  302.  
  303. void
  304. clearredir() {
  305.       register struct redirtab *rp;
  306.       int i;
  307.  
  308.       for (rp = redirlist ; rp ; rp = rp->next) {
  309.         for (i = 0 ; i < 10 ; i++) {
  310.           if (rp->renamed[i] >= 0) {
  311.             close(rp->renamed[i]);
  312.           }
  313.           rp->renamed[i] = EMPTY;
  314.         }
  315.       }
  316. }
  317.  
  318.  
  319.  
  320. /*
  321.  * Copy a file descriptor, like the F_DUPFD option of fcntl.  Returns -1
  322.  * if the source file descriptor is closed, EMPTY if there are no unused
  323.  * file descriptors left.
  324.  */
  325.  
  326. int
  327. copyfd(from, to) {
  328. #ifdef F_DUPFD
  329.       int newfd;
  330.  
  331.       newfd = fcntl(from, F_DUPFD, to);
  332.       if (newfd < 0 && errno == EMFILE)
  333.         return EMPTY;
  334.       return newfd;
  335. #else
  336.       char toclose[32];
  337.       int i;
  338.       int newfd;
  339.       int e;
  340.  
  341.       for (i = 0 ; i < to ; i++)
  342.         toclose[i] = 0;
  343.       INTOFF;
  344.       while ((newfd = dup(from)) >= 0 && newfd < to)
  345.         toclose[newfd] = 1;
  346.       e = errno;
  347.       for (i = 0 ; i < to ; i++) {
  348.         if (toclose[i])
  349.           close(i);
  350.       }
  351.       INTON;
  352.       if (newfd < 0 && e == EMFILE)
  353.         return EMPTY;
  354.       return newfd;
  355. #endif
  356. }
  357. EOF
  358. if test `wc -c < redir.c` -ne 6644
  359. then    echo 'redir.c is the wrong size'
  360. fi
  361. echo extracting shell.h.bsd
  362. cat > shell.h.bsd <<\EOF
  363. /*
  364.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  365.  * This file is part of ash, which is distributed under the terms specified
  366.  * by the Ash General Public License.  See the file named LICENSE.
  367.  */
  368.  
  369. /*
  370.  * The follow should be set to reflect the type of system you have:
  371.  *    JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  372.  *    SYMLINKS -> 1 if your system includes symbolic links, 0 otherwise.
  373.  *    DIRENT -> 1 if your system has the SVR3 directory(3X) routines.
  374.  *    UDIR -> 1 if you want the shell to simulate the /u directory.
  375.  *    ATTY -> 1 to include code for atty(1).
  376.  *    SHORTNAMES -> 1 if your linker cannot handle long names.
  377.  *    define BSD if you are running 4.2 BSD or later.
  378.  *    define SYSV if you are running under System V.
  379.  *    define DEBUG to turn on debugging.
  380.  *
  381.  * When debugging is on, debugging info will be written to $HOME/trace and
  382.  * a quit signal will generate a core dump.
  383.  */
  384.  
  385.  
  386. #define JOBS 1
  387. #define SYMLINKS 1
  388. #define DIRENT 0
  389. #define UDIR 1
  390. #define ATTY 1
  391. #define SHORTNAMES 0
  392. #define BSD
  393. /* #define SYSV */
  394. /* #define DEBUG */
  395.  
  396.  
  397.  
  398. #if SHORTNAMES
  399. #include "shortnames.h"
  400. #endif
  401.  
  402.  
  403. #ifdef __STDC__
  404. typedef void *pointer;
  405. #ifndef NULL
  406. #define NULL (void *)0
  407. #endif
  408. #else /* not __STDC__ */
  409. #define const
  410. #define volatile
  411. typedef char *pointer;
  412. #ifndef NULL
  413. #define NULL 0
  414. #endif
  415. #endif /* __STDC__ */
  416. #define STATIC    /* empty */
  417. #define MKINIT    /* empty */
  418.  
  419. extern char nullstr[1];        /* null string */
  420.  
  421.  
  422. #ifdef DEBUG
  423. #define TRACE(param)    trace param
  424. #else
  425. #define TRACE(param)
  426. #endif
  427. EOF
  428. if test `wc -c < shell.h.bsd` -ne 1520
  429. then    echo 'shell.h.bsd is the wrong size'
  430. fi
  431. echo extracting shell.h.s5r2
  432. cat > shell.h.s5r2 <<\EOF
  433. /*
  434.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  435.  * This file is part of ash, which is distributed under the terms specified
  436.  * by the Ash General Public License.  See the file named LICENSE.
  437.  */
  438.  
  439. /*
  440.  * The follow should be set to reflect the type of system you have:
  441.  *    JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  442.  *    SYMLINKS -> 1 if your system includes symbolic links, 0 otherwise.
  443.  *    DIRENT -> 1 if your system has the SVR3 directory(3X) routines.
  444.  *    UDIR -> 1 if you want the shell to simulate the /u directory.
  445.  *    ATTY -> 1 to include code for atty(1).
  446.  *    SHORTNAMES -> 1 if your linker cannot handle long names.
  447.  *    define BSD if you are running 4.2 BSD or later.
  448.  *    define SYSV if you are running under System V.
  449.  *    define DEBUG to turn on debugging.
  450.  *
  451.  * When debugging is on, debugging info will be written to $HOME/trace and
  452.  * a quit signal will generate a core dump.
  453.  */
  454.  
  455.  
  456. #define JOBS 0
  457. #define SYMLINKS 0
  458. #define DIRENT 0
  459. #define UDIR 1
  460. #define ATTY 0
  461. #define SHORTNAMES 0
  462. /* #define BSD */
  463. #define SYSV
  464. /* #define DEBUG */
  465.  
  466.  
  467.  
  468. #if SHORTNAMES
  469. #include "shortnames.h"
  470. #endif
  471.  
  472.  
  473. #ifdef __STDC__
  474. typedef void *pointer;
  475. #ifndef NULL
  476. #define NULL (void *)0
  477. #endif
  478. #else /* not __STDC__ */
  479. #define const
  480. #define volatile
  481. typedef char *pointer;
  482. #ifndef NULL
  483. #define NULL 0
  484. #endif
  485. #endif /* __STDC__ */
  486. #define STATIC    /* empty */
  487. #define MKINIT    /* empty */
  488.  
  489. extern char nullstr[1];        /* null string */
  490.  
  491.  
  492. #ifdef DEBUG
  493. #define TRACE(param)    trace param
  494. #else
  495. #define TRACE(param)
  496. #endif
  497. EOF
  498. if test `wc -c < shell.h.s5r2` -ne 1520
  499. then    echo 'shell.h.s5r2 is the wrong size'
  500. fi
  501. echo extracting shell.h.s5r3
  502. cat > shell.h.s5r3 <<\EOF
  503. /*
  504.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  505.  * This file is part of ash, which is distributed under the terms specified
  506.  * by the Ash General Public License.  See the file named LICENSE.
  507.  */
  508.  
  509. /*
  510.  * The follow should be set to reflect the type of system you have:
  511.  *    JOBS -> 1 if you have Berkeley job control, 0 otherwise.
  512.  *    SYMLINKS -> 1 if your system includes symbolic links, 0 otherwise.
  513.  *    DIRENT -> 1 if your system has the SVR3 directory(3X) routines.
  514.  *    UDIR -> 1 if you want the shell to simulate the /u directory.
  515.  *    ATTY -> 1 to include code for atty(1).
  516.  *    SHORTNAMES -> 1 if your linker cannot handle long names.
  517.  *    define BSD if you are running 4.2 BSD or later.
  518.  *    define SYSV if you are running under System V.
  519.  *    define DEBUG to turn on debugging.
  520.  *
  521.  * When debugging is on, debugging info will be written to $HOME/trace and
  522.  * a quit signal will generate a core dump.
  523.  */
  524.  
  525.  
  526. #define JOBS 0
  527. #define SYMLINKS 0
  528. #define DIRENT 1
  529. #define UDIR 1
  530. #define ATTY 0
  531. #define SHORTNAMES 0
  532. /* #define BSD */
  533. #define SYSV
  534. /* #define DEBUG */
  535.  
  536.  
  537.  
  538. #if SHORTNAMES
  539. #include "shortnames.h"
  540. #endif
  541.  
  542.  
  543. #ifdef __STDC__
  544. typedef void *pointer;
  545. #ifndef NULL
  546. #define NULL (void *)0
  547. #endif
  548. #else /* not __STDC__ */
  549. #define const
  550. #define volatile
  551. typedef char *pointer;
  552. #ifndef NULL
  553. #define NULL 0
  554. #endif
  555. #endif /* __STDC__ */
  556. #define STATIC    /* empty */
  557. #define MKINIT    /* empty */
  558.  
  559. extern char nullstr[1];        /* null string */
  560.  
  561.  
  562. #ifdef DEBUG
  563. #define TRACE(param)    trace param
  564. #else
  565. #define TRACE(param)
  566. #endif
  567. EOF
  568. if test `wc -c < shell.h.s5r3` -ne 1520
  569. then    echo 'shell.h.s5r3 is the wrong size'
  570. fi
  571. echo extracting shortnames.h
  572. cat > shortnames.h <<\EOF
  573. /*
  574.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  575.  * This file is part of ash, which is distributed under the terms specified
  576.  * by the Ash General Public License.  See the file named LICENSE.
  577.  *
  578.  * The following defines avoid global name conflicts for linkers that
  579.  * only look at the first six characters.
  580.  */
  581.  
  582. #define builtinfunc bltfu
  583. #define builtinloc bltlo
  584. #define cmdlookup cmdlk
  585. #define command cmd_
  586. #define commandtext cmdtx
  587. #define delete_cmd_entry delce
  588. #define environment envmt
  589. #define expandarg exarg
  590. #define expandhere exher
  591. #define expandmeta exmet
  592. #define growstackblock grosb
  593. #define heredoclist herdl
  594. #define lookupvar lookv
  595. #define match_begin matcb
  596. #define number_parens numpa
  597. #define parsebackquote parbq
  598. #define parsefile parfi
  599. #define parsenextc parnx
  600. #define parsenleft parnl
  601. #define pushednleft pusnl
  602. #define pushedstring pusst
  603. #define readtoken1 rtok1
  604. #define setinputfd stifd
  605. #define setinputfile stifi
  606. #define setinteractive stint
  607. #define setvareq stveq
  608. #define stacknleft stknl
  609. EOF
  610. if test `wc -c < shortnames.h` -ne 1027
  611. then    echo 'shortnames.h is the wrong size'
  612. fi
  613. echo extracting show.c
  614. cat > show.c <<\EOF
  615. /*
  616.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  617.  * This file is part of ash, which is distributed under the terms specified
  618.  * by the Ash General Public License.  See the file named LICENSE.
  619.  */
  620.  
  621. #include <stdio.h>
  622. #include "shell.h"
  623. #include "parser.h"
  624. #include "nodes.h"
  625. #include "mystring.h"
  626.  
  627.  
  628. #ifdef notdef
  629. static shtree(), shcmd(), sharg(), indent();
  630.  
  631.  
  632. showtree(n)
  633.       union node *n;
  634.       {
  635.       trputs("showtree called\n");
  636.       shtree(n, 1, NULL, stdout);
  637. }
  638.  
  639.  
  640. static
  641. shtree(n, ind, pfx, fp)
  642.       union node *n;
  643.       char *pfx;
  644.       FILE *fp;
  645.       {
  646.       struct nodelist *lp;
  647.       char *s;
  648.  
  649.       indent(ind, pfx, fp);
  650.       switch(n->type) {
  651.       case NSEMI:
  652.         s = "; ";
  653.         goto binop;
  654.       case NAND:
  655.         s = " && ";
  656.         goto binop;
  657.       case NOR:
  658.         s = " || ";
  659. binop:
  660.         shtree(n->nbinary.ch1, ind, NULL, fp);
  661.         if (ind < 0)
  662.           fputs(s, fp);
  663.         shtree(n->nbinary.ch2, ind, NULL, fp);
  664.         break;
  665.       case NCMD:
  666.         shcmd(n, fp);
  667.         if (ind >= 0)
  668.           putc('\n', fp);
  669.         break;
  670.       case NPIPE:
  671.         for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
  672.           shcmd(lp->n, fp);
  673.           if (lp->next)
  674.             fputs(" | ", fp);
  675.         }
  676.         if (n->npipe.backgnd)
  677.           fputs(" &", fp);
  678.         if (ind >= 0)
  679.           putc('\n', fp);
  680.         break;
  681.       default:
  682.         fprintf(fp, "<node type %d>", n->type);
  683.         if (ind >= 0)
  684.           putc('\n', fp);
  685.         break;
  686.       }
  687. }
  688.  
  689.  
  690.  
  691. static
  692. shcmd(cmd, fp)
  693.       union node *cmd;
  694.       FILE *fp;
  695.       {
  696.       union node *np;
  697.       int first;
  698.       char *s;
  699.       int dftfd;
  700.  
  701.       first = 1;
  702.       for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
  703.         if (! first)
  704.           putchar(' ');
  705.         sharg(np, fp);
  706.         first = 0;
  707.       }
  708.       for (np = cmd->ncmd.redirect ; np ; np = np->nfile.next) {
  709.         if (! first)
  710.           putchar(' ');
  711.         switch (np->nfile.type) {
  712.           case NTO:    s = ">";  dftfd = 1; break;
  713.           case NAPPEND:    s = ">>"; dftfd = 1; break;
  714.           case NTOFD:    s = ">&"; dftfd = 1; break;
  715.           case NFROM:    s = "<";  dftfd = 0; break;
  716.           case NFROMFD:    s = "<&"; dftfd = 0; break;
  717.         }
  718.         if (np->nfile.fd != dftfd)
  719.           fprintf(fp, "%d", np->nfile.fd);
  720.         fputs(s, fp);
  721.         if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
  722.           fprintf(fp, "%d", np->nfile.dupfd);
  723.         } else {
  724.           sharg(np->nfile.fname, fp);
  725.         }
  726.         first = 0;
  727.       }
  728. }
  729.  
  730.  
  731.  
  732. static
  733. sharg(arg, fp)
  734.       union node *arg;
  735.       FILE *fp;
  736.       {
  737.       char *p;
  738.       struct nodelist *bqlist;
  739.  
  740.       if (arg->type != NARG) {
  741.         printf("<node type %d>\n", arg->type);
  742.         fflush(stdout);
  743.         abort();
  744.       }
  745.       bqlist = arg->narg.backquote;
  746.       for (p = arg->narg.text ; *p ; p++) {
  747.         switch (*p) {
  748.         case CTLESC:
  749.           putc(*++p, fp);
  750.           break;
  751.         case CTLVAR:
  752.         case CTLVAR|CTLQUOTE:
  753.           putc('$', fp);
  754.           break;
  755.         case CTLBACKQ:
  756.         case CTLBACKQ|CTLQUOTE:
  757.           putc('`', fp);
  758.           shtree(bqlist->n, -1, NULL, fp);
  759.           putc('`', fp);
  760.           break;
  761.         default:
  762.           putc(*p, fp);
  763.           break;
  764.         }
  765.       }
  766. }
  767.  
  768.  
  769. static
  770. indent(amount, pfx, fp)
  771.       char *pfx;
  772.       FILE *fp;
  773.       {
  774.       int i;
  775.  
  776.       for (i = 0 ; i < amount ; i++) {
  777.         if (pfx && i == amount - 1)
  778.           fputs(pfx, fp);
  779.         putc('\t', fp);
  780.       }
  781. }
  782. #endif
  783.  
  784.  
  785.  
  786. /*
  787.  * Debugging stuff.
  788.  */
  789.  
  790.  
  791. FILE *tracefile;
  792.  
  793.  
  794.  
  795. trputc(c) {
  796. #ifdef DEBUG
  797.       if (tracefile == NULL)
  798.         return;
  799.       putc(c, tracefile);
  800.       if (c == '\n')
  801.         fflush(tracefile);
  802. #endif
  803. }
  804.  
  805.  
  806. trace(fmt, a1, a2, a3, a4, a5, a6, a7, a8)
  807.       char *fmt;
  808.       {
  809. #ifdef DEBUG
  810.       if (tracefile == NULL)
  811.         return;
  812.       fprintf(tracefile, fmt, a1, a2, a3, a4, a5, a6, a7, a8);
  813.       if (strchr(fmt, '\n'))
  814.         fflush(tracefile);
  815. #endif
  816. }
  817.  
  818.  
  819. trputs(s)
  820.       char *s;
  821.       {
  822. #ifdef DEBUG
  823.       if (tracefile == NULL)
  824.         return;
  825.       fputs(s, tracefile);
  826.       if (strchr(s, '\n'))
  827.         fflush(tracefile);
  828. #endif
  829. }
  830.  
  831.  
  832. trstring(s)
  833.       char *s;
  834.       {
  835.       register char *p;
  836.       char c;
  837.  
  838. #ifdef DEBUG
  839.       if (tracefile == NULL)
  840.         return;
  841.       putc('"', tracefile);
  842.       for (p = s ; *p ; p++) {
  843.         switch (*p) {
  844.         case '\n':  c = 'n';  goto backslash;
  845.         case '\t':  c = 't';  goto backslash;
  846.         case '\r':  c = 'r';  goto backslash;
  847.         case '"':  c = '"';  goto backslash;
  848.         case '\\':  c = '\\';  goto backslash;
  849.         case CTLESC:  c = 'e';  goto backslash;
  850.         case CTLVAR:  c = 'v';  goto backslash;
  851.         case CTLVAR+CTLQUOTE:  c = 'V';  goto backslash;
  852.         case CTLBACKQ:  c = 'q';  goto backslash;
  853.         case CTLBACKQ+CTLQUOTE:  c = 'Q';  goto backslash;
  854. backslash:      putc('\\', tracefile);
  855.           putc(c, tracefile);
  856.           break;
  857.         default:
  858.           if (*p >= ' ' && *p <= '~')
  859.             putc(*p, tracefile);
  860.           else {
  861.             putc('\\', tracefile);
  862.             putc(*p >> 6 & 03, tracefile);
  863.             putc(*p >> 3 & 07, tracefile);
  864.             putc(*p & 07, tracefile);
  865.           }
  866.           break;
  867.         }
  868.       }
  869.       putc('"', tracefile);
  870. #endif
  871. }
  872.  
  873.  
  874. trargs(ap)
  875.       char **ap;
  876.       {
  877. #ifdef DEBUG
  878.       if (tracefile == NULL)
  879.         return;
  880.       while (*ap) {
  881.         trstring(*ap++);
  882.         if (*ap)
  883.           putc(' ', tracefile);
  884.         else
  885.           putc('\n', tracefile);
  886.       }
  887.       fflush(tracefile);
  888. #endif
  889. }
  890.  
  891.  
  892. opentrace() {
  893.       char s[100];
  894.       char *p;
  895.       char *getenv();
  896.       int flags;
  897.  
  898. #ifdef DEBUG
  899.       if ((p = getenv("HOME")) == NULL)
  900.         p = "/tmp";
  901.       scopy(p, s);
  902.       strcat(s, "/trace");
  903.       if ((tracefile = fopen(s, "a")) == NULL) {
  904.         fprintf(stderr, "Can't open %s\n", s);
  905.         exit(2);
  906.       }
  907. #ifdef O_APPEND
  908.       if ((flags = fcntl(fileno(tracefile), F_GETFL, 0)) >= 0)
  909.         fcntl(fileno(tracefile), F_SETFL, flags | O_APPEND);
  910. #endif
  911.       fputs("\nTracing started.\n", tracefile);
  912.       fflush(tracefile);
  913. #endif
  914. }
  915. EOF
  916. if test `wc -c < show.c` -ne 5655
  917. then    echo 'show.c is the wrong size'
  918. fi
  919. echo extracting trap.h
  920. cat > trap.h <<\EOF
  921. /*
  922.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  923.  * This file is part of ash, which is distributed under the terms specified
  924.  * by the Ash General Public License.  See the file named LICENSE.
  925.  */
  926.  
  927. extern int sigpending;
  928.  
  929. #ifdef __STDC__
  930. void clear_traps(void);
  931. int setsignal(int);
  932. void ignoresig(int);
  933. void dotrap(void);
  934. void setinteractive(int);
  935. void exitshell(int);
  936. #else
  937. void clear_traps();
  938. int setsignal();
  939. void ignoresig();
  940. void dotrap();
  941. void setinteractive();
  942. void exitshell();
  943. #endif
  944. EOF
  945. if test `wc -c < trap.h` -ne 511
  946. then    echo 'trap.h is the wrong size'
  947. fi
  948. echo extracting trap.c
  949. cat > trap.c <<\EOF
  950. /*
  951.  * Routines for dealing with signals.
  952.  *
  953.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  954.  * This file is part of ash, which is distributed under the terms specified
  955.  * by the Ash General Public License.  See the file named LICENSE.
  956.  */
  957.  
  958. #include "shell.h"
  959. #include "main.h"
  960. #include "nodes.h"    /* for other headers */
  961. #include "eval.h"
  962. #include "jobs.h"
  963. #include "options.h"
  964. #include "syntax.h"
  965. #include "signames.h"
  966. #include "output.h"
  967. #include "memalloc.h"
  968. #include "error.h"
  969. #include "trap.h"
  970. #include "mystring.h"
  971. #include <signal.h>
  972.  
  973.  
  974. /*
  975.  * Sigmode records the current value of the signal handlers for the various
  976.  * modes.  A value of zero means that the current handler is not known.
  977.  * S_HARD_IGN indicates that the signal was ignored on entry to the shell,
  978.  */
  979.  
  980. #define S_DFL 1            /* default signal handling (SIG_DFL) */
  981. #define S_CATCH 2        /* signal is caught */
  982. #define S_IGN 3            /* signal is ignored (SIG_IGN) */
  983. #define S_HARD_IGN 4        /* signal is ignored permenantly */
  984.  
  985.  
  986. extern char nullstr[1];        /* null string */
  987.  
  988. char *trap[MAXSIG+1];        /* trap handler commands */
  989. MKINIT char sigmode[MAXSIG];    /* current value of signal */
  990. char gotsig[MAXSIG];        /* indicates specified signal received */
  991. int sigpending;            /* indicates some signal received */
  992.  
  993.  
  994. #ifdef SYSV
  995. typedef void (*sigaction)();    /* type returned by signal(2) */
  996. #else
  997. typedef int (*sigaction)();    /* type returned by signal(2) */
  998. #endif
  999.  
  1000.  
  1001.  
  1002. /*
  1003.  * The trap builtin.
  1004.  */
  1005.  
  1006. trapcmd(argc, argv)  char **argv; {
  1007.       char *action;
  1008.       char **ap;
  1009.       int signo;
  1010.  
  1011.       if (argc <= 1) {
  1012.         for (signo = 0 ; signo <= MAXSIG ; signo++) {
  1013.           if (trap[signo] != NULL)
  1014.             out1fmt("%d: %s\n", signo, trap[signo]);
  1015.         }
  1016.         return 0;
  1017.       }
  1018.       ap = argv + 1;
  1019.       if (is_number(*ap))
  1020.         action = NULL;
  1021.       else
  1022.         action = *ap++;
  1023.       while (*ap) {
  1024.         if ((signo = number(*ap)) < 0 || signo > MAXSIG)
  1025.           error("%s: bad trap", *ap);
  1026.         INTOFF;
  1027.         if (action)
  1028.           action = savestr(action);
  1029.         if (trap[signo])
  1030.           ckfree(trap[signo]);
  1031.         trap[signo] = action;
  1032.         if (signo != 0)
  1033.           setsignal(signo);
  1034.         INTON;
  1035.         ap++;
  1036.       }
  1037.       return 0;
  1038. }
  1039.  
  1040.  
  1041.  
  1042. /*
  1043.  * Clear traps on a fork.
  1044.  */
  1045.  
  1046. void
  1047. clear_traps() {
  1048.       char **tp;
  1049.  
  1050.       for (tp = trap ; tp <= &trap[MAXSIG] ; tp++) {
  1051.         if (*tp && **tp) {    /* trap not NULL or SIG_IGN */
  1052.           INTOFF;
  1053.           ckfree(*tp);
  1054.           *tp = NULL;
  1055.           if (tp != &trap[0])
  1056.             setsignal(tp - trap);
  1057.           INTON;
  1058.         }
  1059.       }
  1060. }
  1061.  
  1062.  
  1063.  
  1064. /*
  1065.  * Set the signal handler for the specified signal.  The routine figures
  1066.  * out what it should be set to.
  1067.  */
  1068.  
  1069. int
  1070. setsignal(signo) {
  1071.       int action;
  1072.       sigaction sigact;
  1073.       char *t;
  1074.       extern void onsig();
  1075.  
  1076.       if ((t = trap[signo]) == NULL)
  1077.             action = S_DFL;
  1078.       else if (*t != '\0')
  1079.             action = S_CATCH;
  1080.       else
  1081.             action = S_IGN;
  1082.       if (rootshell && action == S_DFL) {
  1083.             switch (signo) {
  1084.             case SIGINT:
  1085.                   if (iflag)
  1086.                         action = S_CATCH;
  1087.                   break;
  1088. #ifndef DEBUG
  1089.             case SIGQUIT:
  1090. #endif
  1091.             case SIGTERM:
  1092.                   if (iflag)
  1093.                         action = S_IGN;
  1094.                   break;
  1095. #if JOBS
  1096.             case SIGTSTP:
  1097.             case SIGTTOU:
  1098.                   if (jflag)
  1099.                         action = S_IGN;
  1100.                   break;
  1101. #endif
  1102.             }
  1103.       }
  1104.       t = &sigmode[signo - 1];
  1105.       if (*t == 0) {    /* current setting unknown */
  1106.             /*
  1107.              * There is a race condition here if action is not S_IGN.
  1108.              * A signal can be ignored that shouldn't be.
  1109.              */
  1110.             if ((int)(sigact = signal(signo, SIG_IGN)) == -1)
  1111.                   error("Signal system call failed");
  1112.             if (sigact == SIG_IGN) {
  1113.                   *t = S_HARD_IGN;
  1114.             } else {
  1115.                   *t = S_IGN;
  1116.             }
  1117.       }
  1118.       if (*t == S_HARD_IGN || *t == action)
  1119.             return 0;
  1120.       switch (action) {
  1121.         case S_DFL:       sigact = SIG_DFL;        break;
  1122.         case S_CATCH:  sigact = (sigaction)onsig;    break;
  1123.         case S_IGN:       sigact = SIG_IGN;        break;
  1124.       }
  1125.       *t = action;
  1126.       return (int)signal(signo, sigact);
  1127. }
  1128.  
  1129.  
  1130.  
  1131. /*
  1132.  * Ignore a signal.
  1133.  */
  1134.  
  1135. void
  1136. ignoresig(signo) {
  1137.       if (sigmode[signo - 1] != S_IGN && sigmode[signo - 1] != S_HARD_IGN) {
  1138.         signal(signo, SIG_IGN);
  1139.       }
  1140.       sigmode[signo - 1] = S_HARD_IGN;
  1141. }
  1142.  
  1143.  
  1144. #ifdef mkinit
  1145. INCLUDE "signames.h"
  1146. INCLUDE "trap.h"
  1147.  
  1148. SHELLPROC {
  1149.       char *sm;
  1150.  
  1151.       clear_traps();
  1152.       for (sm = sigmode ; sm < sigmode + MAXSIG ; sm++) {
  1153.         if (*sm == S_IGN)
  1154.           *sm = S_HARD_IGN;
  1155.       }
  1156. }
  1157. #endif
  1158.  
  1159.  
  1160.  
  1161. /*
  1162.  * Signal handler.
  1163.  */
  1164.  
  1165. void
  1166. onsig(signo) {
  1167.       signal(signo, (sigaction)onsig);
  1168.       if (signo == SIGINT && trap[SIGINT] == NULL) {
  1169.             onint();
  1170.             return;
  1171.       }
  1172.       gotsig[signo - 1] = 1;
  1173.       sigpending++;
  1174. }
  1175.  
  1176.  
  1177.  
  1178. /*
  1179.  * Called to execute a trap.  Perhaps we should avoid entering new trap
  1180.  * handlers while we are executing a trap handler.
  1181.  */
  1182.  
  1183. void
  1184. dotrap() {
  1185.       int i;
  1186.  
  1187.       for (;;) {
  1188.         for (i = 1 ; ; i++) {
  1189.           if (gotsig[i - 1])
  1190.             break;
  1191.           if (i >= MAXSIG)
  1192.             goto done;
  1193.         }
  1194.         gotsig[i - 1] = 0;
  1195.         evalstring(trap[i]);
  1196.       }
  1197. done:
  1198.       sigpending = 0;
  1199. }
  1200.  
  1201.  
  1202.  
  1203. /*
  1204.  * Controls whether the shell is interactive or not.
  1205.  */
  1206.  
  1207. int is_interactive;
  1208.  
  1209. void
  1210. setinteractive(on) {
  1211.       if (on == is_interactive)
  1212.             return;
  1213.       setsignal(SIGINT);
  1214.       setsignal(SIGQUIT);
  1215.       setsignal(SIGTERM);
  1216.       is_interactive = on;
  1217. }
  1218.  
  1219.  
  1220.  
  1221. /*
  1222.  * Called to exit the shell.
  1223.  */
  1224.  
  1225. void
  1226. exitshell(status) {
  1227.       struct jmploc loc1, loc2;
  1228.       char *p;
  1229.  
  1230.       TRACE(("exitshell(%d) pid=%d\n", status, getpid()));
  1231.       if (setjmp(loc1.loc))  goto l1;
  1232.       if (setjmp(loc2.loc))  goto l2;
  1233.       handler = &loc1;
  1234.       if ((p = trap[0]) != NULL && *p != '\0') {
  1235.         trap[0] = NULL;
  1236.         evalstring(p);
  1237.       }
  1238. l1:   handler = &loc2;            /* probably unnecessary */
  1239.       flushall();
  1240. #if JOBS
  1241.       setjobctl(0);
  1242. #endif
  1243. l2:   _exit(status);
  1244. }
  1245. EOF
  1246. if test `wc -c < trap.c` -ne 6014
  1247. then    echo 'trap.c is the wrong size'
  1248. fi
  1249. echo extracting var.h
  1250. cat > var.h <<\EOF
  1251. /*
  1252.  * Shell variables.
  1253.  *
  1254.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  1255.  * This file is part of ash, which is distributed under the terms specified
  1256.  * by the Ash General Public License.  See the file named LICENSE.
  1257.  */
  1258.  
  1259. /* flags */
  1260. #define VEXPORT        01    /* variable is exported */
  1261. #define VREADONLY    02    /* variable cannot be modified */
  1262. #define VSTRFIXED    04    /* variable struct is staticly allocated */
  1263. #define VTEXTFIXED    010    /* text is staticly allocated */
  1264. #define VSTACK        020    /* text is allocated on the stack */
  1265. #define VUNSET        040    /* the variable is not set */
  1266.  
  1267.  
  1268. struct var {
  1269.       struct var *next;        /* next entry in hash list */
  1270.       int flags;        /* flags are defined above */
  1271.       char *text;        /* name=value */
  1272. };
  1273.  
  1274.  
  1275. struct localvar {
  1276.       struct localvar *next;    /* next local variable in list */
  1277.       struct var *vp;        /* the variable that was made local */
  1278.       int flags;        /* saved flags */
  1279.       char *text;        /* saved text */
  1280. };
  1281.  
  1282.  
  1283. struct localvar *localvars;
  1284.  
  1285. #if ATTY
  1286. extern struct var vatty;
  1287. #endif
  1288. extern struct var vifs;
  1289. extern struct var vmail;
  1290. extern struct var vmpath;
  1291. extern struct var vpath;
  1292. extern struct var vps1;
  1293. extern struct var vps2;
  1294. #if ATTY
  1295. extern struct var vterm;
  1296. #endif
  1297.  
  1298. /*
  1299.  * The following macros access the values of the above variables.
  1300.  * They have to skip over the name.  They return the null string
  1301.  * for unset variables.
  1302.  */
  1303.  
  1304. #define ifsval()    (vifs.text + 4)
  1305. #define mailval()    (vmail.text + 5)
  1306. #define mpathval()    (vmpath.text + 9)
  1307. #define pathval()    (vpath.text + 5)
  1308. #define ps1val()    (vps1.text + 4)
  1309. #define ps2val()    (vps2.text + 4)
  1310. #if ATTY
  1311. #define termval()    (vterm.text + 5)
  1312. #endif
  1313.  
  1314. #if ATTY
  1315. #define attyset()    ((vatty.flags & VUNSET) == 0)
  1316. #endif
  1317. #define mpathset()    ((vmpath.flags & VUNSET) == 0)
  1318.  
  1319.  
  1320. #ifdef __STDC__
  1321. void initvar();
  1322. void setvar(char *, char *, int);
  1323. void setvareq(char *, int);
  1324. void listsetvar(struct strlist *);
  1325. char *lookupvar(char *);
  1326. char *bltinlookup(char *, int);
  1327. char **environment();
  1328. int showvarscmd(int, char **);
  1329. void mklocal(char *);
  1330. void poplocalvars(void);
  1331. #else
  1332. void initvar();
  1333. void setvar();
  1334. void setvareq();
  1335. void listsetvar();
  1336. char *lookupvar();
  1337. char *bltinlookup();
  1338. char **environment();
  1339. int showvarscmd();
  1340. void mklocal();
  1341. void poplocalvars();
  1342. #endif
  1343. EOF
  1344. if test `wc -c < var.h` -ne 2241
  1345. then    echo 'var.h is the wrong size'
  1346. fi
  1347. echo extracting var.c
  1348. cat > var.c <<\EOF
  1349. /*
  1350.  * Shell variables.
  1351.  *
  1352.  * Copyright (C) 1989 by Kenneth Almquist.  All rights reserved.
  1353.  * This file is part of ash, which is distributed under the terms specified
  1354.  * by the Ash General Public License.  See the file named LICENSE.
  1355.  */
  1356.  
  1357.  
  1358. #include "shell.h"
  1359. #include "output.h"
  1360. #include "expand.h"
  1361. #include "nodes.h"    /* for other headers */
  1362. #include "eval.h"    /* defines cmdenviron */
  1363. #include "exec.h"
  1364. #include "syntax.h"
  1365. #include "options.h"
  1366. #include "mail.h"
  1367. #include "var.h"
  1368. #include "memalloc.h"
  1369. #include "error.h"
  1370. #include "mystring.h"
  1371.  
  1372.  
  1373. #define VTABSIZE 39
  1374.  
  1375.  
  1376. struct varinit {
  1377.       struct var *var;
  1378.       int flags;
  1379.       char *text;
  1380. };
  1381.  
  1382.  
  1383. #if ATTY
  1384. struct var vatty;
  1385. #endif
  1386. struct var vifs;
  1387. struct var vmail;
  1388. struct var vmpath;
  1389. struct var vpath;
  1390. struct var vps1;
  1391. struct var vps2;
  1392. struct var vvers;
  1393. #if ATTY
  1394. struct var vterm;
  1395. #endif
  1396.  
  1397. const struct varinit varinit[] = {
  1398. #if ATTY
  1399.       {&vatty,    VSTRFIXED|VTEXTFIXED|VUNSET,    "ATTY="},
  1400. #endif
  1401.       {&vifs,    VSTRFIXED|VTEXTFIXED,        "IFS= \t\n"},
  1402.       {&vmail,    VSTRFIXED|VTEXTFIXED|VUNSET,    "MAIL="},
  1403.       {&vmpath,    VSTRFIXED|VTEXTFIXED|VUNSET,    "MAILPATH="},
  1404.       {&vpath,    VSTRFIXED|VTEXTFIXED,        "PATH=:/bin:/usr/bin"},
  1405.       {&vps1,    VSTRFIXED|VTEXTFIXED,        "PS1=@ "},
  1406.       {&vps2,    VSTRFIXED|VTEXTFIXED,        "PS2=> "},
  1407.       {&vvers,    VSTRFIXED|VTEXTFIXED,        "SHELLVERS=ash 0.2"},
  1408. #if ATTY
  1409.       {&vterm,    VSTRFIXED|VTEXTFIXED|VUNSET,    "TERM="},
  1410. #endif
  1411.       {NULL,    0,                NULL}
  1412. };
  1413.  
  1414. struct var *vartab[VTABSIZE];
  1415.  
  1416. #ifdef __STDC__
  1417. STATIC void unsetvar(char *);
  1418. STATIC struct var **hashvar(char *);
  1419. STATIC int varequal(char *, char *);
  1420. #else
  1421. STATIC void unsetvar();
  1422. STATIC struct var **hashvar();
  1423. STATIC int varequal();
  1424. #endif
  1425.  
  1426.  
  1427.  
  1428. /*
  1429.  * Initialize the varable symbol tables and import the environment
  1430.  */
  1431.  
  1432. #ifdef mkinit
  1433. INCLUDE "var.h"
  1434. INIT {
  1435.       char **envp;
  1436.       extern char **environ;
  1437.  
  1438.       initvar();
  1439.       for (envp = environ ; *envp ; envp++) {
  1440.         if (strchr(*envp, '=')) {
  1441.           setvareq(*envp, VEXPORT|VTEXTFIXED);
  1442.         }
  1443.       }
  1444. }
  1445. #endif
  1446.  
  1447.  
  1448. /*
  1449.  * This routine initializes the builtin variables.  It is called when the
  1450.  * shell is initialized and again when a shell procedure is spawned.
  1451.  */
  1452.  
  1453. void
  1454. initvar() {
  1455.       const struct varinit *ip;
  1456.       struct var *vp;
  1457.       struct var **vpp;
  1458.  
  1459.       for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
  1460.         if ((vp->flags & VEXPORT) == 0) {
  1461.           vpp = hashvar(ip->text);
  1462.           vp->next = *vpp;
  1463.           *vpp = vp;
  1464.           vp->text = ip->text;
  1465.           vp->flags = ip->flags;
  1466.         }
  1467.       }
  1468. }
  1469.  
  1470.  
  1471.  
  1472. /*
  1473.  * Set the value of a variable.  The flags argument is ored with the
  1474.  * flags of the variable.  If val is NULL, the variable is unset.
  1475.  */
  1476.  
  1477. void
  1478. setvar(name, val, flags)
  1479.       char *name, *val;
  1480.       {
  1481.       char *p, *q;
  1482.       int len;
  1483.       int namelen;
  1484.       char *nameeq;
  1485.       int isbad;
  1486.  
  1487.       isbad = 0;
  1488.       p = name;
  1489.       if (! is_name(*p++))
  1490.         isbad = 1;
  1491.       for (;;) {
  1492.         if (! is_in_name(*p)) {
  1493.           if (*p == '\0' || *p == '=')
  1494.             break;
  1495.           isbad = 1;
  1496.         }
  1497.         p++;
  1498.       }
  1499.       namelen = p - name;
  1500.       if (isbad)
  1501.         error("%.*s: is read only", namelen, name);
  1502.       len = namelen + 2;        /* 2 is space for '=' and '\0' */
  1503.       if (val == NULL) {
  1504.         flags |= VUNSET;
  1505.       } else {
  1506.         len += strlen(val);
  1507.       }
  1508.       p = nameeq = ckmalloc(len);
  1509.       q = name;
  1510.       while (--namelen >= 0)
  1511.         *p++ = *q++;
  1512.       *p++ = '=';
  1513.       *p = '\0';
  1514.       if (val)
  1515.         scopy(val, p);
  1516.       setvareq(nameeq, flags);
  1517. }
  1518.  
  1519.  
  1520.  
  1521. /*
  1522.  * Same as setvar except that the variable and value are passed in
  1523.  * the first argument as name=value.  Since the first argument will
  1524.  * be actually stored in the table, it should not be a string that
  1525.  * will go away.
  1526.  */
  1527.  
  1528. void
  1529. setvareq(s, flags)
  1530.       char *s;
  1531.       {
  1532.       struct var *vp, **vpp;
  1533.  
  1534.       vpp = hashvar(s);
  1535.       for (vp = *vpp ; vp ; vp = vp->next) {
  1536.         if (varequal(s, vp->text)) {
  1537.           if (vp->flags & VREADONLY) {
  1538.             int len = strchr(s, '=') - s;
  1539.             error("%.*s: is read only", len, s);
  1540.           }
  1541.           INTOFF;
  1542.           if (vp == &vpath)
  1543.             changepath(s + 5);    /* 5 = strlen("PATH=") */
  1544.           if ((vp->flags & (VTEXTFIXED|VSTACK)) == 0)
  1545.             ckfree(vp->text);
  1546.           vp->flags &=~ (VTEXTFIXED|VSTACK|VUNSET);
  1547.           vp->flags |= flags;
  1548.           vp->text = s;
  1549.           if (vp == &vmpath || (vp == &vmail && ! mpathset()))
  1550.             chkmail(1);
  1551.           INTON;
  1552.           return;
  1553.         }
  1554.       }
  1555.       /* not found */
  1556.       vp = ckmalloc(sizeof (*vp));
  1557.       vp->flags = flags;
  1558.       vp->text = s;
  1559.       vp->next = *vpp;
  1560.       *vpp = vp;
  1561. }
  1562.  
  1563.  
  1564.  
  1565. /*
  1566.  * Process a linked list of variable assignments.
  1567.  */
  1568.  
  1569. void
  1570. listsetvar(list)
  1571.       struct strlist *list;
  1572.       {
  1573.       struct strlist *lp;
  1574.  
  1575.       INTOFF;
  1576.       for (lp = list ; lp ; lp = lp->next) {
  1577.         setvareq(savestr(lp->text), 0);
  1578.       }
  1579.       INTON;
  1580. }
  1581.  
  1582.  
  1583.  
  1584. /*
  1585.  * Find the value of a variable.  Returns NULL if not set.
  1586.  */
  1587.  
  1588. char *
  1589. lookupvar(name)
  1590.       char *name;
  1591.       {
  1592.       struct var *v;
  1593.  
  1594.       for (v = *hashvar(name) ; v ; v = v->next) {
  1595.         if (varequal(v->text, name)) {
  1596.           if (v->flags & VUNSET)
  1597.             return NULL;
  1598.           return strchr(v->text, '=') + 1;
  1599.         }
  1600.       }
  1601.       return NULL;
  1602. }
  1603.  
  1604.  
  1605.  
  1606. /*
  1607.  * Search the environment of a builtin command.  If the second argument
  1608.  * is nonzero, return the value of a variable even if it hasn't been
  1609.  * exported.
  1610.  */
  1611.  
  1612. char *
  1613. bltinlookup(name, doall)
  1614.       char *name;
  1615.       {
  1616.       struct strlist *sp;
  1617.       struct var *v;
  1618.  
  1619.       for (sp = cmdenviron ; sp ; sp = sp->next) {
  1620.         if (varequal(sp->text, name))
  1621.           return strchr(sp->text, '=') + 1;
  1622.       }
  1623.       for (v = *hashvar(name) ; v ; v = v->next) {
  1624.         if (varequal(v->text, name)) {
  1625.           if (v->flags & VUNSET
  1626.            || ! doall && (v->flags & VEXPORT) == 0)
  1627.             return NULL;
  1628.           return strchr(v->text, '=') + 1;
  1629.         }
  1630.       }
  1631.       return NULL;
  1632. }
  1633.  
  1634.  
  1635.  
  1636. /*
  1637.  * Generate a list of exported variables.  This routine is used to construct
  1638.  * the third argument to execve when executing a program.
  1639.  */
  1640.  
  1641. char **
  1642. environment() {
  1643.       int nenv;
  1644.       struct var **vpp;
  1645.       struct var *vp;
  1646.       char **env, **ep;
  1647.  
  1648.       nenv = 0;
  1649.       for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
  1650.         for (vp = *vpp ; vp ; vp = vp->next)
  1651.           if (vp->flags & VEXPORT)
  1652.             nenv++;
  1653.       }
  1654.       ep = env = stalloc((nenv + 1) * sizeof *env);
  1655.       for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
  1656.         for (vp = *vpp ; vp ; vp = vp->next)
  1657.           if (vp->flags & VEXPORT)
  1658.             *ep++ = vp->text;
  1659.       }
  1660.       *ep = NULL;
  1661.       return env;
  1662. }
  1663.  
  1664.  
  1665. /*
  1666.  * Called when a shell procedure is invoked to clear out nonexported
  1667.  * variables.  It is also necessary to reallocate variables of with
  1668.  * VSTACK set since these are currently allocated on the stack.
  1669.  */
  1670.  
  1671. #ifdef mkinit
  1672. MKINIT void shprocvar();
  1673.  
  1674. SHELLPROC {
  1675.       shprocvar();
  1676. }
  1677. #endif
  1678.  
  1679. void
  1680. shprocvar() {
  1681.       struct var **vpp;
  1682.       struct var *vp, **prev;
  1683.  
  1684.       for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
  1685.         for (prev = vpp ; (vp = *prev) != NULL ; ) {
  1686.           if ((vp->flags & VEXPORT) == 0) {
  1687.             *prev = vp->next;
  1688.             if ((vp->flags & VTEXTFIXED) == 0)
  1689.                   ckfree(vp->text);
  1690.             if ((vp->flags & VSTRFIXED) == 0)
  1691.                   ckfree(vp);
  1692.           } else {
  1693.             if (vp->flags & VSTACK) {
  1694.                   vp->text = savestr(vp->text);
  1695.                   vp->flags &=~ VSTACK;
  1696.             }
  1697.             prev = &vp->next;
  1698.           }
  1699.         }
  1700.       }
  1701.       initvar();
  1702. }
  1703.  
  1704.  
  1705.  
  1706. /*
  1707.  * Command to list all variables which are set.  Currently this command
  1708.  * is invoked from the set command when the set command is called without
  1709.  * any variables.
  1710.  */
  1711.  
  1712. int
  1713. showvarscmd(argc, argv)  char **argv; {
  1714.       struct var **vpp;
  1715.       struct var *vp;
  1716.  
  1717.       for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
  1718.         for (vp = *vpp ; vp ; vp = vp->next) {
  1719.           if ((vp->flags & VUNSET) == 0)
  1720.             out1fmt("%s\n", vp->text);
  1721.         }
  1722.       }
  1723.       return 0;
  1724. }
  1725.  
  1726.  
  1727.  
  1728. /*
  1729.  * The export and readonly commands.
  1730.  */
  1731.  
  1732. int
  1733. exportcmd(argc, argv)  char **argv; {
  1734.       struct var **vpp;
  1735.       struct var *vp;
  1736.       char *name;
  1737.       char *p;
  1738.       int flag = argv[0][0] == 'r'? VREADONLY : VEXPORT;
  1739.  
  1740.       listsetvar(cmdenviron);
  1741.       if (argc > 1) {
  1742.         while ((name = *argptr++) != NULL) {
  1743.           if ((p = strchr(name, '=')) != NULL) {
  1744.             p++;
  1745.           } else {
  1746.             vpp = hashvar(name);
  1747.             for (vp = *vpp ; vp ; vp = vp->next) {
  1748.                   if (varequal(vp->text, name)) {
  1749.                     vp->flags |= flag;
  1750.                     goto found;
  1751.                   }
  1752.             }
  1753.           }
  1754.           setvar(name, p, flag);
  1755. found:;
  1756.         }
  1757.       } else {
  1758.         for (vpp = vartab ; vpp < vartab + VTABSIZE ; vpp++) {
  1759.           for (vp = *vpp ; vp ; vp = vp->next) {
  1760.             if (vp->flags & flag) {
  1761.                   for (p = vp->text ; *p != '=' ; p++)
  1762.                     out1c(*p);
  1763.                   out1c('\n');
  1764.             }
  1765.           }
  1766.         }
  1767.       }
  1768.       return 0;
  1769. }
  1770.  
  1771.  
  1772. /*
  1773.  * The "local" command.
  1774.  */
  1775.  
  1776. localcmd(argc, argv)  char **argv; {
  1777.       char *name;
  1778.  
  1779.       if (! in_function())
  1780.         error("Not in a function");
  1781.       while ((name = *argptr++) != NULL) {
  1782.         mklocal(name);
  1783.       }
  1784.       return 0;
  1785. }
  1786.  
  1787.  
  1788. /*
  1789.  * Make a variable a local variable.  When a variable is made local, it's
  1790.  * value and flags are saved in a localvar structure.  The saved values
  1791.  * will be restored when the shell function returns.  We handle the name
  1792.  * "-" as a special case.
  1793.  */
  1794.  
  1795. void
  1796. mklocal(name)
  1797.       char *name;
  1798.       {
  1799.       struct localvar *lvp;
  1800.       struct var **vpp;
  1801.       struct var *vp;
  1802.  
  1803.       INTOFF;
  1804.       lvp = ckmalloc(sizeof (struct localvar));
  1805.       if (name[0] == '-' && name[1] == '\0') {
  1806.         lvp->text = ckmalloc(sizeof optval);
  1807.         bcopy(optval, lvp->text, sizeof optval);
  1808.         vp = NULL;
  1809.       } else {
  1810.         vpp = hashvar(name);
  1811.         for (vp = *vpp ; vp && ! varequal(vp->text, name) ; vp = vp->next);
  1812.         if (vp == NULL) {
  1813.           if (strchr(name, '='))
  1814.             setvareq(savestr(name), VSTRFIXED);
  1815.           else
  1816.             setvar(name, NULL, VSTRFIXED);
  1817.           vp = *vpp;    /* the new variable */
  1818.           lvp->text = NULL;
  1819.           lvp->flags = VUNSET;
  1820.         } else {
  1821.           lvp->text = vp->text;
  1822.           lvp->flags = vp->flags;
  1823.           vp->flags |= VSTRFIXED|VTEXTFIXED;
  1824.           if (strchr(name, '='))
  1825.             setvareq(savestr(name), 0);
  1826.         }
  1827.       }
  1828.       lvp->vp = vp;
  1829.       lvp->next = localvars;
  1830.       localvars = lvp;
  1831.       INTON;
  1832. }
  1833.  
  1834.  
  1835. /*
  1836.  * Called after a function returns.
  1837.  */
  1838.  
  1839. void
  1840. poplocalvars() {
  1841.       struct localvar *lvp;
  1842.       struct var *vp;
  1843.  
  1844.       while ((lvp = localvars) != NULL) {
  1845.         localvars = lvp->next;
  1846.         vp = lvp->vp;
  1847.         if (vp == NULL) {    /* $- saved */
  1848.           bcopy(lvp->text, optval, sizeof optval);
  1849.           ckfree(lvp->text);
  1850.         } else if ((lvp->flags & (VUNSET|VSTRFIXED)) == VUNSET) {
  1851.           unsetvar(vp->text);
  1852.         } else {
  1853.           if ((vp->flags & VTEXTFIXED) == 0)
  1854.             ckfree(vp->text);
  1855.           vp->flags = lvp->flags;
  1856.           vp->text = lvp->text;
  1857.         }
  1858.         ckfree(lvp);
  1859.       }
  1860. }
  1861.  
  1862.  
  1863. setvarcmd(argc, argv)  char **argv; {
  1864.       if (argc <= 2)
  1865.         return unsetcmd(argc, argv);
  1866.       else if (argc == 3)
  1867.         setvar(argv[1], argv[2], 0);
  1868.       else
  1869.         error("List assignment not implemented");
  1870.       return 0;
  1871. }
  1872.  
  1873.  
  1874. /*
  1875.  * The unset builtin command.  We unset the function before we unset the
  1876.  * variable to allow a function to be unset when there is a readonly variable
  1877.  * with the same name.
  1878.  */
  1879.  
  1880. unsetcmd(argc, argv)  char **argv; {
  1881.       char **ap;
  1882.  
  1883.       for (ap = argv + 1 ; *ap ; ap++) {
  1884.         unsetfunc(*ap);
  1885.         unsetvar(*ap);
  1886.       }
  1887.       return 0;
  1888. }
  1889.  
  1890.  
  1891. /*
  1892.  * Unset the specified variable.
  1893.  */
  1894.  
  1895. STATIC void
  1896. unsetvar(s)
  1897.       char *s;
  1898.       {
  1899.       struct var **vpp;
  1900.       struct var *vp;
  1901.  
  1902.       vpp = hashvar(s);
  1903.       for (vp = *vpp ; vp ; vpp = &vp->next, vp = *vpp) {
  1904.         if (varequal(vp->text, s)) {
  1905.           INTOFF;
  1906.           if (*(strchr(vp->text, '=') + 1) != '\0'
  1907.            || vp->flags & VREADONLY) {
  1908.             setvar(s, nullstr, 0);
  1909.           }
  1910.           vp->flags &=~ VEXPORT;
  1911.           vp->flags |= VUNSET;
  1912.           if ((vp->flags & VSTRFIXED) == 0) {
  1913.             if ((vp->flags & VTEXTFIXED) == 0)
  1914.                   ckfree(vp->text);
  1915.             *vpp = vp->next;
  1916.             ckfree(vp);
  1917.           }
  1918.           INTON;
  1919.           return;
  1920.         }
  1921.       }
  1922. }
  1923.  
  1924.  
  1925.  
  1926. /*
  1927.  * Find the appropriate entry in the hash table from the name.
  1928.  */
  1929.  
  1930. STATIC struct var **
  1931. hashvar(p)
  1932.       register char *p;
  1933.       {
  1934.       unsigned int hashval;
  1935.  
  1936.       hashval = *p << 4;
  1937.       while (*p && *p != '=')
  1938.         hashval += *p++;
  1939.       return &vartab[hashval % VTABSIZE];
  1940. }
  1941.  
  1942.  
  1943.  
  1944. /*
  1945.  * Returns true if the two strings specify the same varable.  The first
  1946.  * variable name is terminated by '='; the second may be terminated by
  1947.  * either '=' or '\0'.
  1948.  */
  1949.  
  1950. STATIC int
  1951. varequal(p, q)
  1952.       register char *p, *q;
  1953.       {
  1954.       while (*p == *q++) {
  1955.         if (*p++ == '=')
  1956.           return 1;
  1957.       }
  1958.       if (*p == '=' && *(q - 1) == '\0')
  1959.         return 1;
  1960.       return 0;
  1961. }
  1962. EOF
  1963. if test `wc -c < var.c` -ne 12409
  1964. then    echo 'var.c is the wrong size'
  1965. fi
  1966. echo extracting TOUR
  1967. cat > TOUR <<\EOF
  1968.                        A Tour through Ash
  1969.  
  1970.                Copyright 1989 by Kenneth Almquist.
  1971.  
  1972.  
  1973. DIRECTORIES:  The subdirectory bltin contains commands which can
  1974. be compiled stand-alone.  The rest of the source is in the main
  1975. ash directory.
  1976.  
  1977. SOURCE CODE GENERATORS:  Files whose names begin with "mk" are
  1978. programs that generate source code.  A complete list of these
  1979. programs is:
  1980.  
  1981.         program         intput files        generates
  1982.         -------         ------------        ---------
  1983.         mkbuiltins      builtins            builtins.h builtins.c
  1984.         mkinit          *.c                 init.c
  1985.         mknodes         nodetypes           nodes.h nodes.c
  1986.         mksignames          -               signames.h signames.c
  1987.         mksyntax            -               syntax.h syntax.c
  1988.         mktokens            -               token.def
  1989.         bltin/mkexpr    unary_op binary_op  operators.h operators.c
  1990.  
  1991. There are undoubtedly too many of these.  Mkinit searches all the
  1992. C source files for entries looking like:
  1993.  
  1994.         INIT {
  1995.               x = 1;    /* executed during initialization */
  1996.         }
  1997.  
  1998.         RESET {
  1999.               x = 2;    /* executed when the shell does a longjmp
  2000.                            back to the main command loop */
  2001.         }
  2002.  
  2003.         SHELLPROC {
  2004.               x = 3;    /* executed when the shell runs a shell procedure */
  2005.         }
  2006.  
  2007. It pulls this code out into routines which are when particular
  2008. events occur.  The intent is to improve modularity by isolating
  2009. the information about which modules need to be explicitly
  2010. initialized/reset within the modules themselves.
  2011.  
  2012. Mkinit recognizes several constructs for placing declarations in
  2013. the init.c file.
  2014.         INCLUDE "file.h"
  2015. includes a file.  The storage class MKINIT makes a declaration
  2016. available in the init.c file, for example:
  2017.         MKINIT int funcnest;    /* depth of function calls */
  2018. MKINIT alone on a line introduces a structure or union declara-
  2019. tion:
  2020.         MKINIT
  2021.         struct redirtab {
  2022.               short renamed[10];
  2023.         };
  2024. Preprocessor #define statements are copied to init.c without any
  2025. special action to request this.
  2026.  
  2027. INDENTATION:  The ash source is indented in multiples of six
  2028. spaces.  The only study that I have heard of on the subject con-
  2029. cluded that the optimal amount to indent is in the range of four
  2030. to six spaces.  I use six spaces since it is not too big a jump
  2031. from the widely used eight spaces.  If you really hate six space
  2032. indentation, use the adjind (source included) program to change
  2033. it to something else.
  2034.  
  2035. EXCEPTIONS:  Code for dealing with exceptions appears in
  2036. exceptions.c.  The C language doesn't include exception handling,
  2037. so I implement it using setjmp and longjmp.  The global variable
  2038. exception contains the type of exception.  EXERROR is raised by
  2039. calling error.  EXINT is an interrupt.  EXSHELLPROC is an excep-
  2040. tion which is raised when a shell procedure is invoked.  The pur-
  2041. pose of EXSHELLPROC is to perform the cleanup actions associated
  2042. with other exceptions.  After these cleanup actions, the shell
  2043. can interpret a shell procedure itself without exec'ing a new
  2044. copy of the shell.
  2045.  
  2046. INTERRUPTS:  In an interactive shell, an interrupt will cause an
  2047. EXINT exception to return to the main command loop.  (Exception:
  2048. EXINT is not raised if the user traps interrupts using the trap
  2049. command.)  The INTOFF and INTON macros (defined in exception.h)
  2050. provide uninterruptable critical sections.  Between the execution
  2051. of INTOFF and the execution of INTON, interrupt signals will be
  2052. held for later delivery.  INTOFF and INTON can be nested.
  2053.  
  2054. MEMALLOC.C:  Memalloc.c defines versions of malloc and realloc
  2055. which call error when there is no memory left.  It also defines a
  2056. stack oriented memory allocation scheme.  Allocating off a stack
  2057. is probably more efficient than allocation using malloc, but the
  2058. big advantage is that when an exception occurs all we have to do
  2059. to free up the memory in use at the time of the exception is to
  2060. restore the stack pointer.  The stack is implemented using a
  2061. linked list of blocks.
  2062.  
  2063. STPUTC:  If the stack were contiguous, it would be easy to store
  2064. strings on the stack without knowing in advance how long the
  2065. string was going to be:
  2066.         p = stackptr;
  2067.         *p++ = c;       /* repeated as many times as needed */
  2068.         stackptr = p;
  2069. The folloing three macros (defined in memalloc.h) perform these
  2070. operations, but grow the stack if you run off the end:
  2071.         STARTSTACKSTR(p);
  2072.         STPUTC(c, p);   /* repeated as many times as needed */
  2073.         grabstackstr(p);
  2074.  
  2075. We now start a top-down look at the code:
  2076.  
  2077. MAIN.C:  The main routine performs some initialization, executes
  2078. the user's profile if necessary, and calls cmdloop.  Cmdloop is
  2079. repeatedly parses and executes commands.
  2080.  
  2081. OPTIONS.C:  This file contains the option processing code.  It is
  2082. called from main to parse the shell arguments when the shell is
  2083. invoked, and it also contains the set builtin.  The -i and -j op-
  2084. tions (the latter turns on job control) require changes in signal
  2085. handling.  The routines setjobctl (in jobs.c) and setinteractive
  2086. (in trap.c) are called to handle changes to these options.
  2087.  
  2088. PARSING:  The parser code is all in parser.c.  A recursive des-
  2089. cent parser is used.  Syntax tables (generated by mksyntax) are
  2090. used to classify characters during lexical analysis.  There are
  2091. three tables:  one for normal use, one for use when inside single
  2092. quotes, and one for use when inside double quotes.  The tables
  2093. are machine dependent because they are indexed by character vari-
  2094. ables and the range of a char varies from machine to machine.
  2095.  
  2096. PARSE OUTPUT:  The output of the parser consists of a tree of
  2097. nodes.  The various types of nodes are defined in the file node-
  2098. types.
  2099.  
  2100. Nodes of type NARG are used to represent both words and the con-
  2101. tents of here documents.  An early version of ash kept the con-
  2102. tents of here documents in temporary files, but keeping here do-
  2103. cuments in memory typically results in significantly better per-
  2104. formance.  It would have been nice to make it an option to use
  2105. temporary files for here documents, for the benefit of small
  2106. machines, but the code to keep track of when to delete the tem-
  2107. porary files was complex and I never fixed all the bugs in it.
  2108. (AT&T has been maintaining the Bourne shell for more than ten
  2109. years, and to the best of my knowledge they still haven't gotten
  2110. it to handle temporary files correctly in obscure cases.)
  2111.  
  2112. The text field of a NARG structure points to the text of the
  2113. word.  The text consists of ordinary characters and a number of
  2114. special codes defined in parser.h.  The special codes are:
  2115.  
  2116.         CTLVAR              Variable substitution
  2117.         CTLENDVAR           End of variable substitution
  2118.         CTLBACKQ            Command substitution
  2119.         CTLBACKQ|CTLQUOTE   Command substitution inside double quotes
  2120.         CTLESC              Escape next character
  2121.  
  2122. A variable substitution contains the following elements:
  2123.  
  2124.         CTLVAR type name '=' [ alternative-text CTLENDVAR ]
  2125.  
  2126. The type field is a single character specifying the type of sub-
  2127. stitution.  The possible types are:
  2128.  
  2129.         VSNORMAL            $var
  2130.         VSMINUS             ${var-text}
  2131.         VSMINUS|VSNUL       ${var:-text}
  2132.         VSPLUS              ${var+text}
  2133.         VSPLUS|VSNUL        ${var:+text}
  2134.         VSQUESTION          ${var?text}
  2135.         VSQUESTION|VSNUL    ${var:?text}
  2136.         VSASSIGN            ${var=text}
  2137.         VSASSIGN|VSNUL      ${var=text}
  2138.  
  2139. In addition, the type field will have the VSQUOTE flag set if the
  2140. variable is enclosed in double quotes.  The name of the variable
  2141. comes next, terminated by an equals sign.  If the type is not
  2142. VSNORMAL, then the text field in the substitution follows, ter-
  2143. minated by a CTLENDVAR byte.
  2144.  
  2145. Commands in back quotes are parsed and stored in a linked list.
  2146. The locations of these commands in the string are indicated by
  2147. CTLBACKQ and CTLBACKQ+CTLQUOTE characters, depending upon whether
  2148. the back quotes were enclosed in double quotes.
  2149.  
  2150. The character CTLESC escapes the next character, so that in case
  2151. any of the CTL characters mentioned above appear in the input,
  2152. they can be passed through transparently.  CTLESC is also used to
  2153. escape '*', '?', '[', and '!' characters which were quoted by the
  2154. user and thus should not be used for file name generation.
  2155.  
  2156. CTLESC characters have proved to be particularly tricky to get
  2157. right.  In the case of here documents which are not subject to
  2158. variable and command substitution, the parser doesn't insert any
  2159. CTLESC characters to begin with (so the contents of the text
  2160. field can be written without any processing).  Other here docu-
  2161. ments, and words which are not subject to splitting and file name
  2162. generation, have the CTLESC characters removed during the vari-
  2163. able and command substitution phase.  Words which are subject
  2164. splitting and file name generation have the CTLESC characters re-
  2165. moved as part of the file name phase.
  2166.  
  2167. EXECUTION:  Command execution is handled by the following files:
  2168.         eval.c     The top level routines.
  2169.         redir.c    Code to handle redirection of input and output.
  2170.         jobs.c     Code to handle forking, waiting, and job control.
  2171.         exec.c     Code to to path searches and the actual exec sys call.
  2172.         expand.c   Code to evaluate arguments.
  2173.         var.c      Maintains the variable symbol table.  Called from expand.c.
  2174.  
  2175. EVAL.C:  Evaltree recursively executes a parse tree.  The exit
  2176. status is returned in the global variable exitstatus.  The alter-
  2177. native entry evalbackcmd is called to evaluate commands in back
  2178. quotes.  It saves the result in memory if the command is a buil-
  2179. tin; otherwise it forks off a child to execute the command and
  2180. connects the standard output of the child to a pipe.
  2181.  
  2182. JOBS.C:  To create a process, you call makejob to return a job
  2183. structure, and then call forkshell (passing the job structure as
  2184. an argument) to create the process.  Waitforjob waits for a job
  2185. to complete.  These routines take care of process groups if job
  2186. control is defined.
  2187.  
  2188. REDIR.C:  Ash allows file descriptors to be redirected and then
  2189. restored without forking off a child process.  This is accom-
  2190. plished by duplicating the original file descriptors.  The redir-
  2191. tab structure records where the file descriptors have be dupli-
  2192. cated to.
  2193.  
  2194. EXEC.C:  The routine find_command locates a command, and enters
  2195. the command in the hash table if it is not already there.  The
  2196. third argument specifies whether it is to print an error message
  2197. if the command is not found.  (When a pipeline is set up,
  2198. find_command is called for all the commands in the pipeline be-
  2199. fore any forking is done, so to get the commands into the hash
  2200. table of the parent process.  But to make command hashing as
  2201. transparent as possible, we silently ignore errors at that point
  2202. and only print error messages if the command cannot be found
  2203. later.)
  2204.  
  2205. The routine shellexec is the interface to the exec system call.
  2206.  
  2207. EXPAND.C:  Arguments are processed in three passes.  The first
  2208. (performed by the routine argstr) performs variable and command
  2209. substitution.  The second (ifsbreakup) performs word splitting
  2210. and the third (expandmeta) performs file name generation.  If the
  2211. "/u" directory is simulated, then when "/u/username" is replaced
  2212. by the user's home directory, the flag "didudir" is set.  This
  2213. tells the cd command that it should print out the directory name,
  2214. just as it would if the "/u" directory were implemented using
  2215. symbolic links.
  2216.  
  2217. VAR.C:  Variables are stored in a hash table.  Probably we should
  2218. switch to extensible hashing.  The variable name is stored in the
  2219. same string as the value (using the format "name=value") so that
  2220. no string copying is needed to create the environment of a com-
  2221. mand.  Variables which the shell references internally are preal-
  2222. located so that the shell can reference the values of these vari-
  2223. ables without doing a lookup.
  2224.  
  2225. When a program is run, the code in eval.c sticks any environment
  2226. variables which precede the command (as in "PATH=xxx command") in
  2227. the variable table as the simplest way to strip duplicates, and
  2228. then calls "environment" to get the value of the environment.
  2229. There are two consequences of this.  First, if an assignment to
  2230. PATH precedes the command, the value of PATH before the assign-
  2231. ment must be remembered and passed to shellexec.  Second, if the
  2232. program turns out to be a shell procedure, the strings from the
  2233. environment variables which preceded the command must be pulled
  2234. out of the table and replaced with strings obtained from malloc,
  2235. since the former will automatically be freed when the stack (see
  2236. the entry on memalloc.c) is emptied.
  2237.  
  2238. BUILTIN COMMANDS:  The procedures for handling these are scat-
  2239. tered throughout the code, depending on which location appears
  2240. most appropriate.  They can be recognized because their names al-
  2241. ways end in "cmd".  The mapping from names to procedures is
  2242. specified in the file builtins, which is processed by the mkbuil-
  2243. tins command.
  2244.  
  2245. A builtin command is invoked with argc and argv set up like a
  2246. normal program.  A builtin command is allowed to overwrite its
  2247. arguments.  Builtin routines can call nextopt to do option pars-
  2248. ing.  This is kind of like getopt, but you don't pass argc and
  2249. argv to it.  Builtin routines can also call error.  This routine
  2250. normally terminates the shell (or returns to the main command
  2251. loop if the shell is interactive), but when called from a builtin
  2252. command it causes the builtin command to terminate with an exit
  2253. status of 2.
  2254.  
  2255. The directory bltins contains commands which can be compiled in-
  2256. dependently but can also be built into the shell for efficiency
  2257. reasons.  The makefile in this directory compiles these programs
  2258. in the normal fashion (so that they can be run regardless of
  2259. whether the invoker is ash), but also creates a library named
  2260. bltinlib.a which can be linked with ash.  The header file bltin.h
  2261. takes care of most of the differences between the ash and the
  2262. stand-alone environment.  The user should call the main routine
  2263. "main", and #define main to be the name of the routine to use
  2264. when the program is linked into ash.  This #define should appear
  2265. before bltin.h is included; bltin.h will #undef main if the pro-
  2266. gram is to be compiled stand-alone.
  2267.  
  2268. CD.C:  This file defines the cd and pwd builtins.  The pwd com-
  2269. mand runs /bin/pwd the first time it is invoked (unless the user
  2270. has already done a cd to an absolute pathname), but then
  2271. remembers the current directory and updates it when the cd com-
  2272. mand is run, so subsequent pwd commands run very fast.  The main
  2273. complication in the cd command is in the docd command, which
  2274. resolves symbolic links into actual names and informs the user
  2275. where the user ended up if he crossed a symbolic link.
  2276.  
  2277. SIGNALS:  Trap.c implements the trap command.  The routine set-
  2278. signal figures out what action should be taken when a signal is
  2279. received and invokes the signal system call to set the signal ac-
  2280. tion appropriately.  When a signal that a user has set a trap for
  2281. is caught, the routine "onsig" sets a flag.  The routine dotrap
  2282. is called at appropriate points to actually handle the signal.
  2283. When an interrupt is caught and no trap has been set for that
  2284. signal, the routine "onint" in error.c is called.
  2285.  
  2286. OUTPUT:  Ash uses it's own output routines.  There are three out-
  2287. put structures allocated.  "Output" represents the standard out-
  2288. put, "errout" the standard error, and "memout" contains output
  2289. which is to be stored in memory.  This last is used when a buil-
  2290. tin command appears in backquotes, to allow its output to be col-
  2291. lected without doing any I/O through the UNIX operating system.
  2292. The variables out1 and out2 normally point to output and errout,
  2293. respectively, but they are set to point to memout when appropri-
  2294. ate inside backquotes.
  2295.  
  2296. INPUT:  The basic input routine is pgetc, which reads from the
  2297. current input file.  There is a stack of input files; the current
  2298. input file is the top file on this stack.  The code allows the
  2299. input to come from a string rather than a file.  (This is for the
  2300. -c option and the "." and eval builtin commands.)  The global
  2301. variable plinno is saved and restored when files are pushed and
  2302. popped from the stack.  The parser routines store the number of
  2303. the current line in this variable.
  2304.  
  2305. DEBUGGING:  If DEBUG is defined in shell.h, then the shell will
  2306. write debugging information to the file $HOME/trace.  Most of
  2307. this is done using the TRACE macro, which takes a set of printf
  2308. arguments inside two sets of parenthesis.  Example:
  2309. "TRACE(("n=%d0, n))".  The double parenthesis are necessary be-
  2310. cause the preprocessor can't handle functions with a variable
  2311. number of arguments.  Defining DEBUG also causes the shell to
  2312. generate a core dump if it is sent a quit signal.  The tracing
  2313. code is in show.c.
  2314. EOF
  2315. if test `wc -c < TOUR` -ne 16760
  2316. then    echo 'TOUR is the wrong size'
  2317. fi
  2318. echo Archive 7 unpacked
  2319. exit
  2320.  
  2321.