Home | History | Annotate | Line # | Download | only in sh
      1 /*	$NetBSD: show.c,v 1.61 2026/11/24 13:26:11 kre Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Copyright (c) 2017 The NetBSD Foundation, Inc.  All rights reserved.
      8  *
      9  * This code is derived from software contributed to Berkeley by
     10  * Kenneth Almquist.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  */
     36 
     37 #include <sys/cdefs.h>
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)show.c	8.3 (Berkeley) 5/4/95";
     41 #else
     42 __RCSID("$NetBSD: show.c,v 1.61 2026/11/24 13:26:11 kre Exp $");
     43 #endif
     44 #endif /* not lint */
     45 
     46 #include <stdio.h>
     47 #include <stdarg.h>
     48 #include <stdlib.h>
     49 #include <unistd.h>
     50 #include <fcntl.h>
     51 #include <errno.h>
     52 #include <limits.h>
     53 
     54 #include <sys/types.h>
     55 #include <sys/uio.h>
     56 
     57 #include "shell.h"
     58 #include "parser.h"
     59 #include "nodes.h"
     60 #include "mystring.h"
     61 #include "show.h"
     62 #include "options.h"
     63 #include "redir.h"
     64 #include "error.h"
     65 #include "syntax.h"
     66 #include "input.h"
     67 #include "output.h"
     68 #include "var.h"
     69 #include "builtins.h"
     70 
     71 #define DEFINE_NODENAMES
     72 #include "nodenames.h"		/* does almost nothing if !defined(DEBUG) */
     73 
     74 #define	TR_STD_WIDTH	60	/* tend to fold lines wider than this */
     75 #define	TR_IOVECS	10	/* number of lines or trace (max) / write */
     76 
     77 typedef struct traceinfo {
     78 	int	tfd;	/* file descriptor for open trace file */
     79 	int	nxtiov;	/* the buffer we should be writing to */
     80 	char	lastc;	/* the last non-white character output */
     81 	uint8_t	supr;	/* char classes to suppress after \n */
     82 	pid_t	pid;	/* process id of process that opened that file */
     83 	size_t	llen;	/* number of chars in current output line */
     84 	size_t	blen;	/* chars used in current buffer being filled */
     85 	char *	tracefile;		/* name of the tracefile */
     86 	struct iovec lines[TR_IOVECS];	/* filled, flling, pending buffers */
     87 } TFILE;
     88 
     89 /* These are auto turned off when non white space is printed */
     90 #define	SUP_NL	0x01	/* don't print \n */
     91 #define	SUP_SP	0x03	/* suppress spaces */
     92 #define	SUP_WSP	0x04	/* suppress all white space */
     93 
     94 #ifdef DEBUG		/* from here to end of file ... */
     95 
     96 TFILE tracedata, *tracetfile;
     97 FILE *tracefile;		/* just for histedit */
     98 
     99 uint64_t	DFlags;		/* currently enabled debug flags */
    100 int ShNest;			/* depth of shell (internal) nesting */
    101 
    102 static void shtree(union node *, int, int, int, TFILE *);
    103 static void shcmd(union node *, TFILE *);
    104 static void shsubsh(union node *, TFILE *);
    105 static void shredir(union node *, TFILE *, int);
    106 static void sharg(union node *, TFILE *);
    107 static void indent(int, TFILE *);
    108 static void trstring(const char *);
    109 static void trace_putc(char, TFILE *);
    110 static void trace_puts(const char *, TFILE *);
    111 static void trace_flush(TFILE *, int);
    112 static char *trace_id(TFILE *);
    113 static void trace_fd_swap(int, int);
    114 
    115 inline static int trlinelen(TFILE *);
    116 
    117 
    118 /*
    119  * These functions are the externally visible interface
    120  *  (but only for a DEBUG shell.)
    121  */
    122 
    123 void
    124 opentrace(void)
    125 {
    126 	char *s;
    127 	const char *p;
    128 	int fd;
    129 	int i;
    130 	pid_t pid;
    131 
    132 	if (debug != 1) {
    133 		/* leave fd open because libedit might be using it */
    134 		if (tracefile)
    135 			fflush(tracefile);
    136 		if (tracetfile)
    137 			trace_flush(tracetfile, 1);
    138 		return;
    139 	}
    140 #if DBG_PID == 1		/* using old shell.h, old tracing method */
    141 	DFlags = DBG_PID;	/* just force DBG_PID on, and leave it ... */
    142 #endif
    143 	pid = getpid();
    144 	if ((p = getenv("SHELL_TRACES")) == NULL)
    145 		p = ".";
    146 	if (asprintf(&s, "%s/trace.%jd", p, (intmax_t)pid) <= 0) {
    147 		debug = 0;
    148 		error("Cannot asprintf tracefilename");
    149 	};
    150 
    151 	fd = open(s, O_WRONLY|O_APPEND|O_CREAT, 0666);
    152 	if (fd == -1) {
    153 		debug = 0;
    154 		error("Can't open tracefile: %s (%s)\n", s, strerror(errno));
    155 	}
    156 	fd = to_upper_fd(fd);
    157 	if (fd <= 2) {
    158 		(void) close(fd);
    159 		debug = 0;
    160 		error("Attempt to use fd %d as tracefile thwarted\n", fd);
    161 	}
    162 	register_sh_fd(fd, trace_fd_swap);
    163 
    164 	/*
    165 	 * This stuff is just so histedit has a FILE * to use
    166 	 */
    167 	if (tracefile)
    168 		(void) fclose(tracefile);	/* also closes tfd */
    169 	tracefile = fdopen(fd, "ae");	/* don't care if it is NULL */
    170 	if (tracefile)			/* except here... */
    171 		setlinebuf(tracefile);
    172 
    173 	/*
    174 	 * Now the real tracing setup
    175 	 */
    176 	if (tracedata.tfd > 0 && tracedata.tfd != fd)
    177 		(void) close(tracedata.tfd);	/* usually done by fclose() */
    178 
    179 	tracedata.tfd = fd;
    180 	tracedata.pid = pid;
    181 	tracedata.nxtiov = 0;
    182 	tracedata.blen = 0;
    183 	tracedata.llen = 0;
    184 	tracedata.lastc = '\0';
    185 	tracedata.supr = SUP_NL | SUP_WSP;
    186 
    187 #define	replace(f, v) do {				\
    188 		if (tracedata.f != NULL)		\
    189 			free(tracedata.f);		\
    190 		tracedata.f = v;			\
    191 	} while (0)
    192 
    193 	replace(tracefile, s);
    194 
    195 	for (i = 0; i < TR_IOVECS; i++) {
    196 		replace(lines[i].iov_base, NULL);
    197 		tracedata.lines[i].iov_len = 0;
    198 	}
    199 
    200 #undef replace
    201 
    202 	tracetfile = &tracedata;
    203 
    204 	trace_puts("\nTracing started.\n", tracetfile);
    205 }
    206 
    207 void
    208 trace(const char *fmt, ...)
    209 {
    210 	va_list va;
    211 	char *s;
    212 
    213 	if (debug != 1 || !tracetfile)
    214 		return;
    215 	va_start(va, fmt);
    216 	(void) vasprintf(&s, fmt, va);
    217 	va_end(va);
    218 
    219 	trace_puts(s, tracetfile);
    220 	free(s);
    221 	if (tracetfile->llen == 0)
    222 		trace_flush(tracetfile, 0);
    223 }
    224 
    225 void
    226 tracev(const char *fmt, va_list va)
    227 {
    228 	va_list ap;
    229 	char *s;
    230 
    231 	if (debug != 1 || !tracetfile)
    232 		return;
    233 	va_copy(ap, va);
    234 	(void) vasprintf(&s, fmt, ap);
    235 	va_end(ap);
    236 
    237 	trace_puts(s, tracetfile);
    238 	free(s);
    239 	if (tracetfile->llen == 0)
    240 		trace_flush(tracetfile, 0);
    241 }
    242 
    243 
    244 void
    245 trputs(const char *s)
    246 {
    247 	if (debug != 1 || !tracetfile)
    248 		return;
    249 	trace_puts(s, tracetfile);
    250 }
    251 
    252 void
    253 trputc(int c)
    254 {
    255 	if (debug != 1 || !tracetfile)
    256 		return;
    257 	trace_putc(c, tracetfile);
    258 }
    259 
    260 void
    261 showtree(union node *n)
    262 {
    263 	TFILE *fp;
    264 
    265 	if ((fp = tracetfile) == NULL)
    266 		return;
    267 
    268 	trace_puts("showtree(", fp);
    269 		if (n == NULL)
    270 			trace_puts("NULL", fp);
    271 		else if (n == NEOF)
    272 			trace_puts("NEOF", fp);
    273 		else
    274 			trace("%p", n);
    275 	trace_puts(") called\n", fp);
    276 	if (n != NULL && n != NEOF)
    277 		shtree(n, 1, 1, 1, fp);
    278 }
    279 
    280 void
    281 trargs(char **ap)
    282 {
    283 	if (debug != 1 || !tracetfile)
    284 		return;
    285 	while (*ap) {
    286 		trstring(*ap++);
    287 		if (*ap)
    288 			trace_putc(' ', tracetfile);
    289 	}
    290 	trace_putc('\n', tracetfile);
    291 }
    292 
    293 void
    294 trargstr(union node *n)
    295 {
    296 	sharg(n, tracetfile);
    297 }
    298 
    299 
    300 /*
    301  * Beyond here we just have the implementation of all of that
    302  */
    303 
    304 
    305 inline static int
    306 trlinelen(TFILE * fp)
    307 {
    308 	return fp->llen;
    309 }
    310 
    311 static void
    312 shtree(union node *n, int ind, int ilvl, int nl, TFILE *fp)
    313 {
    314 	struct nodelist *lp;
    315 	const char *s;
    316 
    317 	if (n == NULL) {
    318 		if (nl)
    319 			trace_putc('\n', fp);
    320 		return;
    321 	}
    322 
    323 	indent(ind, fp);
    324 	switch (n->type) {
    325 	case NSEMI:
    326 		s = NULL;
    327 		goto binop;
    328 	case NAND:
    329 		s = " && ";
    330 		goto binop;
    331 	case NOR:
    332 		s = " || ";
    333 binop:
    334 		shtree(n->nbinary.ch1, 0, ilvl, 0, fp);
    335 		if (s != NULL)
    336 			trace_puts(s, fp);
    337 		if (trlinelen(fp) >= TR_STD_WIDTH) {
    338 			trace_putc('\n', fp);
    339 			indent(ind < 0 ? 2 : ind + 1, fp);
    340 		} else if (s == NULL) {
    341 			if (fp->lastc != '&')
    342 				trace_puts("; ", fp);
    343 			else
    344 				trace_putc(' ', fp);
    345 		}
    346 		shtree(n->nbinary.ch2, 0, ilvl, nl, fp);
    347 		break;
    348 	case NCMD:
    349 		shcmd(n, fp);
    350 		if (n->ncmd.backgnd)
    351 			trace_puts(" &", fp);
    352 		if (nl && trlinelen(fp) > 0)
    353 			trace_putc('\n', fp);
    354 		break;
    355 	case NPIPE:
    356 		for (lp = n->npipe.cmdlist ; lp ; lp = lp->next) {
    357 			shtree(lp->n, 0, ilvl, 0, fp);
    358 			if (lp->next) {
    359 				trace_puts(" |", fp);
    360 				if (trlinelen(fp) >= TR_STD_WIDTH)  {
    361 					trace_putc('\n', fp);
    362 					indent((ind < 0 ? ilvl : ind) + 1, fp);
    363 				} else
    364 					trace_putc(' ', fp);
    365 			}
    366 		}
    367 		if (n->npipe.backgnd)
    368 			trace_puts(" &", fp);
    369 		if (nl || trlinelen(fp) >= TR_STD_WIDTH)
    370 			trace_putc('\n', fp);
    371 		break;
    372 	case NBACKGND:
    373 	case NSUBSHELL:
    374 		shsubsh(n, fp);
    375 		if (n->type == NBACKGND)
    376 			trace_puts(" &", fp);
    377 		if (nl && trlinelen(fp) > 0)
    378 			trace_putc('\n', fp);
    379 		break;
    380 	case NDEFUN:
    381 		trace_puts(n->narg.text, fp);
    382 		trace_puts("() {\n", fp);
    383 		indent(ind, fp);
    384 		shtree(n->narg.next, (ind < 0 ? ilvl : ind) + 1, ilvl+1, 1, fp);
    385 		indent(ind, fp);
    386 		trace_puts("}\n", fp);
    387 		break;
    388 	case NDNOT:
    389 		trace_puts("! ", fp);
    390 		/* FALLTHROUGH */
    391 	case NNOT:
    392 		trace_puts("! ", fp);
    393 		shtree(n->nnot.com, -1, ilvl, nl, fp);
    394 		break;
    395 	case NREDIR:
    396 		shtree(n->nredir.n, -1, ilvl, 0, fp);
    397 		shredir(n->nredir.redirect, fp, n->nredir.n == NULL);
    398 		if (nl)
    399 			trace_putc('\n', fp);
    400 		break;
    401 
    402 	case NIF:
    403 	itsif:
    404 		trace_puts("if ", fp);
    405 		shtree(n->nif.test, -1, ilvl, 0, fp);
    406 		if (trlinelen(fp) > 0 && trlinelen(fp) < TR_STD_WIDTH) {
    407 			if (fp->lastc != '&')
    408 				trace_puts(" ;", fp);
    409 		} else
    410 			indent(ilvl, fp);
    411 		trace_puts(" then ", fp);
    412 		if (nl || trlinelen(fp) > TR_STD_WIDTH - 24)
    413 			indent(ilvl+1, fp);
    414 		shtree(n->nif.ifpart, -1, ilvl + 1, 0, fp);
    415 		if (trlinelen(fp) > 0 && trlinelen(fp) < TR_STD_WIDTH) {
    416 			if (fp->lastc != '&')
    417 				trace_puts(" ;", fp);
    418 		} else
    419 			indent(ilvl, fp);
    420 		if (n->nif.elsepart && n->nif.elsepart->type == NIF) {
    421 			if (nl || trlinelen(fp) > TR_STD_WIDTH - 24)
    422 				indent(ilvl, fp);
    423 			n = n->nif.elsepart;
    424 			trace_puts(" el", fp);
    425 			goto itsif;
    426 		}
    427 		if (n->nif.elsepart) {
    428 			if (nl || trlinelen(fp) > TR_STD_WIDTH - 24)
    429 				indent(ilvl+1, fp);
    430 			trace_puts(" else ", fp);
    431 			shtree(n->nif.elsepart, -1, ilvl + 1, 0, fp);
    432 			if (fp->lastc != '&')
    433 				trace_puts(" ;", fp);
    434 		}
    435 		trace_puts(" fi", fp);
    436 		if (nl)
    437 			trace_putc('\n', fp);
    438 		break;
    439 
    440 	case NWHILE:
    441 		trace_puts("while ", fp);
    442 		goto aloop;
    443 	case NUNTIL:
    444 		trace_puts("until ", fp);
    445 	aloop:
    446 		shtree(n->nbinary.ch1, -1, ilvl, 0, fp);
    447 		if (trlinelen(fp) > 0 && trlinelen(fp) < TR_STD_WIDTH) {
    448 			if (fp->lastc != '&')
    449 				trace_puts(" ;", fp);
    450 		} else
    451 			trace_putc('\n', fp);
    452 		trace_puts(" do ", fp);
    453 		shtree(n->nbinary.ch1, -1, ilvl + 1, 1, fp);
    454 		trace_puts(" done ", fp);
    455 		if (nl)
    456 			trace_putc('\n', fp);
    457 		break;
    458 
    459 	case NFOR:
    460 		trace_puts("for ", fp);
    461 		trace_puts(n->nfor.var, fp);
    462 		if (n->nfor.args) {
    463 			union node *argp;
    464 
    465 			trace_puts(" in ", fp);
    466 			for (argp = n->nfor.args; argp; argp=argp->narg.next) {
    467 				sharg(argp, fp);
    468 				trace_putc(' ', fp);
    469 			}
    470 			if (trlinelen(fp) > 0 && trlinelen(fp) < TR_STD_WIDTH) {
    471 				if (fp->lastc != '&')
    472 					trace_putc(';', fp);
    473 			} else
    474 				trace_putc('\n', fp);
    475 		}
    476 		trace_puts(" do ", fp);
    477 		shtree(n->nfor.body, -1, ilvl + 1, 0, fp);
    478 		if (fp->lastc != '&')
    479 			trace_putc(';', fp);
    480 		trace_puts(" done", fp);
    481 		if (nl)
    482 			trace_putc('\n', fp);
    483 		break;
    484 
    485 	case NCASE:
    486 		trace_puts("case ", fp);
    487 		sharg(n->ncase.expr, fp);
    488 		trace_puts(" in", fp);
    489 		if (nl)
    490 			trace_putc('\n', fp);
    491 		{
    492 			union node *cp;
    493 
    494 			for (cp = n->ncase.cases ; cp ; cp = cp->nclist.next) {
    495 				union node *patp;
    496 
    497 				if (nl || trlinelen(fp) > TR_STD_WIDTH - 16)
    498 					indent(ilvl, fp);
    499 				else
    500 					trace_putc(' ', fp);
    501 				trace_putc('(', fp);
    502 				patp = cp->nclist.pattern;
    503 				while (patp != NULL) {
    504 				    trace_putc(' ', fp);
    505 				    sharg(patp, fp);
    506 				    trace_putc(' ', fp);
    507 				    if ((patp = patp->narg.next) != NULL)
    508 					trace_putc('|', fp);
    509 				}
    510 				trace_putc(')', fp);
    511 				if (nl)
    512 					indent(ilvl + 1, fp);
    513 				else
    514 					trace_putc(' ', fp);
    515 				shtree(cp->nclist.body, -1, ilvl+2, 0, fp);
    516 				if (cp->type == NCLISTCONT)
    517 					trace_puts(" ;&", fp);
    518 				else
    519 					trace_puts(" ;;", fp);
    520 				if (nl)
    521 					trace_putc('\n', fp);
    522 			}
    523 		}
    524 		if (nl) {
    525 			trace_putc('\n', fp);
    526 			indent(ind, fp);
    527 		} else
    528 			trace_putc(' ', fp);
    529 		trace_puts("esac", fp);
    530 		if (nl)
    531 			trace_putc('\n', fp);
    532 		break;
    533 
    534 	default: {
    535 			char *str;
    536 
    537 			asprintf(&str, "<node type %d [%s]>", n->type,
    538 			    NODETYPENAME(n->type));
    539 			trace_puts(str, fp);
    540 			free(str);
    541 			if (nl)
    542 				trace_putc('\n', fp);
    543 		}
    544 		break;
    545 	}
    546 }
    547 
    548 
    549 static void
    550 shcmd(union node *cmd, TFILE *fp)
    551 {
    552 	union node *np;
    553 	int first;
    554 
    555 	first = 1;
    556 	for (np = cmd->ncmd.args ; np ; np = np->narg.next) {
    557 		if (! first)
    558 			trace_putc(' ', fp);
    559 		sharg(np, fp);
    560 		first = 0;
    561 	}
    562 	shredir(cmd->ncmd.redirect, fp, first);
    563 }
    564 
    565 static void
    566 shsubsh(union node *cmd, TFILE *fp)
    567 {
    568 	trace_puts(" ( ", fp);
    569 	shtree(cmd->nredir.n, -1, 3, 0, fp);
    570 	trace_puts(" ) ", fp);
    571 	shredir(cmd->ncmd.redirect, fp, 1);
    572 }
    573 
    574 static void
    575 shredir(union node *np, TFILE *fp, int first)
    576 {
    577 	const char *s;
    578 	int dftfd;
    579 	char buf[106];
    580 
    581 	for ( ; np ; np = np->nfile.next) {
    582 		if (! first)
    583 			trace_putc(' ', fp);
    584 		switch (np->nfile.type) {
    585 			case NTO:	s = ">";  dftfd = 1; break;
    586 			case NCLOBBER:	s = ">|"; dftfd = 1; break;
    587 			case NAPPEND:	s = ">>"; dftfd = 1; break;
    588 			case NTOFD:	s = ">&"; dftfd = 1; break;
    589 			case NFROM:	s = "<";  dftfd = 0; break;
    590 			case NFROMFD:	s = "<&"; dftfd = 0; break;
    591 			case NFROMTO:	s = "<>"; dftfd = 0; break;
    592 			case NXHERE:	/* FALLTHROUGH */
    593 			case NHERE:	s = "<<"; dftfd = 0; break;
    594 			default:   s = "*error*"; dftfd = 0; break;
    595 		}
    596 		if (np->nfile.fd != dftfd) {
    597 			sprintf(buf, "%d", np->nfile.fd);
    598 			trace_puts(buf, fp);
    599 		}
    600 		trace_puts(s, fp);
    601 		if (np->nfile.type == NTOFD || np->nfile.type == NFROMFD) {
    602 			if (np->ndup.vname)
    603 				sharg(np->ndup.vname, fp);
    604 			else {
    605 				if (np->ndup.dupfd < 0)
    606 					trace_puts("-", fp);
    607 				else {
    608 					sprintf(buf, "%d", np->ndup.dupfd);
    609 					trace_puts(buf, fp);
    610 				}
    611 			}
    612 		} else
    613 		    if (np->nfile.type == NHERE || np->nfile.type == NXHERE) {
    614 			if (np->nfile.type == NHERE)
    615 				trace_putc('\\', fp);
    616 			trace_puts("!!!\n", fp);
    617 			s = np->nhere.doc->narg.text;
    618 			if (strlen(s) > 100) {
    619 				memmove(buf, s, 100);
    620 				buf[100] = '\0';
    621 				strcat(buf, " ...\n");
    622 				s = buf;
    623 			}
    624 			trace_puts(s, fp);
    625 			trace_puts("!!! ", fp);
    626 		} else {
    627 			sharg(np->nfile.fname, fp);
    628 		}
    629 		first = 0;
    630 	}
    631 }
    632 
    633 static void
    634 sharg(union node *arg, TFILE *fp)
    635 {
    636 	char *p, *s;
    637 	struct nodelist *bqlist;
    638 	int subtype = 0;
    639 	int quoted = 0;
    640 
    641 	if (arg->type != NARG) {
    642 		asprintf(&s, "<node type %d> ! NARG\n", arg->type);
    643 		trace_puts(s, fp);
    644 		abort();	/* no need to free s, better not to */
    645 	}
    646 
    647 	bqlist = arg->narg.backquote;
    648 	for (p = arg->narg.text ; *p ; p++) {
    649 		switch (*p) {
    650 		case CTLESC:
    651 			if (BASESYNTAX[(int)p[1]] != CCTL)
    652 				trace_putc('\\', fp);
    653 			trace_putc(*++p, fp);
    654 			break;
    655 
    656 		case CTLNONL:
    657 			trace_putc('\\', fp);
    658 			trace_putc('\n', fp);
    659 			break;
    660 
    661 		case CTLVAR:
    662 			subtype = *++p;
    663 			if (!quoted != !(subtype & VSQUOTE))
    664 				trace_putc('"', fp);
    665 			trace_putc('$', fp);
    666 			trace_putc('{', fp);	/*}*/
    667 			if ((subtype & VSTYPE) == VSLENGTH)
    668 				trace_putc('#', fp);
    669 
    670 			while (*++p != '=')
    671 				trace_putc(*p, fp);
    672 
    673 			if (subtype & VSNUL)
    674 				trace_putc(':', fp);
    675 
    676 			switch (subtype & VSTYPE) {
    677 			case VSNORMAL:
    678 				/* { */
    679 				trace_putc('}', fp);
    680 				if (!quoted != !(subtype & VSQUOTE))
    681 					trace_putc('"', fp);
    682 				break;
    683 			case VSMINUS:
    684 				trace_putc('-', fp);
    685 				break;
    686 			case VSPLUS:
    687 				trace_putc('+', fp);
    688 				break;
    689 			case VSQUESTION:
    690 				trace_putc('?', fp);
    691 				break;
    692 			case VSASSIGN:
    693 				trace_putc('=', fp);
    694 				break;
    695 			case VSTRIMLEFTMAX:
    696 				trace_putc('#', fp);
    697 				/* FALLTHROUGH */
    698 			case VSTRIMLEFT:
    699 				trace_putc('#', fp);
    700 				break;
    701 			case VSTRIMRIGHTMAX:
    702 				trace_putc('%', fp);
    703 				/* FALLTHROUGH */
    704 			case VSTRIMRIGHT:
    705 				trace_putc('%', fp);
    706 				break;
    707 			case VSLENGTH:
    708 				break;
    709 			default: {
    710 					char str[32];
    711 
    712 					snprintf(str, sizeof str,
    713 					    "<subtype %d>", subtype);
    714 					trace_puts(str, fp);
    715 				}
    716 				break;
    717 			}
    718 			break;
    719 		case CTLENDVAR:
    720 			/* { */
    721 			trace_putc('}', fp);
    722 			if (!quoted != !(subtype & VSQUOTE))
    723 				trace_putc('"', fp);
    724 			subtype = 0;
    725 			break;
    726 
    727 		case CTLBACKQ|CTLQUOTE:
    728 			if (!quoted)
    729 				trace_putc('"', fp);
    730 			/* FALLTHRU */
    731 		case CTLBACKQ:
    732 			trace_putc('$', fp);
    733 			trace_putc('(', fp);
    734 			if (bqlist) {
    735 				shtree(bqlist->n, -1, 3, 0, fp);
    736 				bqlist = bqlist->next;
    737 			} else
    738 				trace_puts("???", fp);
    739 			trace_putc(')', fp);
    740 			if (!quoted && *p == (CTLBACKQ|CTLQUOTE))
    741 				trace_putc('"', fp);
    742 			break;
    743 
    744 		case CTLQUOTEMARK:
    745 			if (subtype != 0 || !quoted) {
    746 				trace_putc('"', fp);
    747 				quoted++;
    748 			}
    749 			break;
    750 		case CTLQUOTEEND:
    751 			trace_putc('"', fp);
    752 			quoted--;
    753 			break;
    754 		case CTLARI:
    755 			if (*p == ' ')
    756 				p++;
    757 			trace_puts("$(( ", fp);
    758 			break;
    759 		case CTLENDARI:
    760 			trace_puts(" ))", fp);
    761 			break;
    762 
    763 		default:
    764 			if (*p == '$')
    765 				trace_putc('\\', fp);
    766 			trace_putc(*p, fp);
    767 			break;
    768 		}
    769 	}
    770 	if (quoted)
    771 		trace_putc('"', fp);
    772 }
    773 
    774 
    775 static void
    776 indent(int amount, TFILE *fp)
    777 {
    778 	int i;
    779 
    780 	if (amount <= 0)
    781 		return;
    782 
    783 	amount <<= 2;	/* indent slots -> chars */
    784 
    785 	i = trlinelen(fp);
    786 	fp->supr = SUP_NL;
    787 	if (i > amount) {
    788 		trace_putc('\n', fp);
    789 		i = 0;
    790 	}
    791 	fp->supr = 0;
    792 	for (; i < amount - 7 ; i++) {
    793 		trace_putc('\t', fp);
    794 		i |= 7;
    795 	}
    796 	while (i < amount) {
    797 		trace_putc(' ', fp);
    798 		i++;
    799 	}
    800 	fp->supr = SUP_WSP;
    801 }
    802 
    803 static void
    804 trace_putc(char c, TFILE *fp)
    805 {
    806 	char *p;
    807 
    808 	if (c == '\0')
    809 		return;
    810 	if (debug == 0 || fp == NULL)
    811 		return;
    812 
    813 	if (fp->llen == 0) {
    814 		if (fp->blen != 0)
    815 			abort();
    816 
    817 		if ((fp->supr & SUP_NL) && c == '\n')
    818 			return;
    819 		if ((fp->supr & (SUP_WSP|SUP_SP)) && c == ' ')
    820 			return;
    821 		if ((fp->supr & SUP_WSP) && c == '\t')
    822 			return;
    823 
    824 		if (fp->nxtiov >= TR_IOVECS - 1)	/* should be rare */
    825 			trace_flush(fp, 0);
    826 
    827 		p = trace_id(fp);
    828 		if (p != NULL) {
    829 			fp->lines[fp->nxtiov].iov_base = p;
    830 			fp->lines[fp->nxtiov].iov_len = strlen(p);
    831 			fp->nxtiov++;
    832 		}
    833 	} else if (fp->blen && fp->blen >= fp->lines[fp->nxtiov].iov_len) {
    834 		fp->blen = 0;
    835 		if (++fp->nxtiov >= TR_IOVECS)
    836 			trace_flush(fp, 0);
    837 	}
    838 
    839 	if (fp->lines[fp->nxtiov].iov_len == 0) {
    840 		p = (char *)malloc(2 * TR_STD_WIDTH);
    841 		if (p == NULL) {
    842 			trace_flush(fp, 1);
    843 			debug = 0;
    844 			return;
    845 		}
    846 		*p = '\0';
    847 		fp->lines[fp->nxtiov].iov_base = p;
    848 		fp->lines[fp->nxtiov].iov_len = 2 * TR_STD_WIDTH;
    849 		fp->blen = 0;
    850 	}
    851 
    852 	p = (char *)fp->lines[fp->nxtiov].iov_base + fp->blen++;
    853 	*p++ = c;
    854 	*p = 0;
    855 
    856 	if (c != ' ' && c != '\t' && c != '\n') {
    857 		fp->lastc = c;
    858 		fp->supr = 0;
    859 	}
    860 
    861 	if (c == '\n') {
    862 		fp->lines[fp->nxtiov++].iov_len = fp->blen;
    863 		fp->blen = 0;
    864 		fp->llen = 0;
    865 		fp->supr |= SUP_NL;
    866 		return;
    867 	}
    868 
    869 	if (c == '\t')
    870 		fp->llen |=  7;
    871 	fp->llen++;
    872 }
    873 
    874 void
    875 trace_flush(TFILE *fp, int all)
    876 {
    877 	int niov, i;
    878 	ssize_t written;
    879 
    880 	niov = fp->nxtiov;
    881 	if (all && fp->blen > 0) {
    882 		fp->lines[niov].iov_len = fp->blen;
    883 		fp->blen = 0;
    884 		fp->llen = 0;
    885 		niov++;
    886 	}
    887 	if (niov == 0)
    888 		return;
    889 	if (fp->blen > 0 && --niov == 0)
    890 		return;
    891 	written = writev(fp->tfd, fp->lines, niov);
    892 	for (i = 0; i < niov; i++) {
    893 		free(fp->lines[i].iov_base);
    894 		fp->lines[i].iov_base = NULL;
    895 		fp->lines[i].iov_len = 0;
    896 	}
    897 	if (written == -1) {
    898 		if (fp->blen > 0) {
    899 			free(fp->lines[niov].iov_base);
    900 			fp->lines[niov].iov_base = NULL;
    901 			fp->lines[niov].iov_len = 0;
    902 		}
    903 		debug = 0;
    904 		fp->blen = 0;
    905 		fp->llen = 0;
    906 		return;
    907 	}
    908 	if (fp->blen > 0) {
    909 		fp->lines[0].iov_base = fp->lines[niov].iov_base;
    910 		fp->lines[0].iov_len = fp->lines[niov].iov_len;
    911 		fp->lines[niov].iov_base = NULL;
    912 		fp->lines[niov].iov_len = 0;
    913 	}
    914 	fp->nxtiov = 0;
    915 }
    916 
    917 void
    918 trace_puts(const char *s, TFILE *fp)
    919 {
    920 	char c;
    921 
    922 	while ((c = *s++) != '\0')
    923 		trace_putc(c, fp);
    924 }
    925 
    926 inline static char *
    927 trace_id(TFILE *tf)
    928 {
    929 	int i;
    930 	char indent[16];
    931 	char *p;
    932 	int lno;
    933 	char c;
    934 
    935 	if (DFlags & DBG_NEST) {
    936 		if ((unsigned)ShNest >= sizeof indent - 1) {
    937 			(void) snprintf(indent, sizeof indent,
    938 			    "### %*d ###", (int)(sizeof indent) - 9, ShNest);
    939 			p = strchr(indent, '\0');
    940 		} else {
    941 			p = indent;
    942 			for (i = 0; i < 6; i++)
    943 				*p++ = (i < ShNest) ? '#' : ' ';
    944 			while (i++ < ShNest && p < &indent[sizeof indent - 1])
    945 				*p++ = '#';
    946 			*p = '\0';
    947 		}
    948 	} else
    949 		indent[0] = '\0';
    950 
    951 	/*
    952 	 * If we are in the parser, then plinno is the current line
    953 	 * number being processed (parser line no).
    954 	 * If we are elsewhere, then line_number gives the source
    955 	 * line of whatever we are currently doing (close enough.)
    956 	 */
    957 	if (parsing)
    958 		lno = plinno;
    959 	else
    960 		lno = line_number;
    961 
    962 	c = ((i = getpid()) == tf->pid) ? ':' : '=';
    963 
    964 	if (DFlags & DBG_PID) {
    965 		if (DFlags & DBG_LINE)
    966 			(void) asprintf(&p, "%5d%c%s\t%4d%c@\t", i, c,
    967 			    indent, lno, parsing?'-':'+');
    968 		else
    969 			(void) asprintf(&p, "%5d%c%s\t", i, c, indent);
    970 		return p;
    971 	} else if (DFlags & DBG_NEST) {
    972 		if (DFlags & DBG_LINE)
    973 			(void) asprintf(&p, "%c%s\t%4d%c@\t", c, indent, lno,
    974 			    parsing?'-':'+');
    975 		else
    976 			(void) asprintf(&p, "%c%s\t", c, indent);
    977 		return p;
    978 	} else if (DFlags & DBG_LINE) {
    979 		(void) asprintf(&p, "%c%4d%c@\t", c, lno, parsing?'-':'+');
    980 		return p;
    981 	}
    982 	return NULL;
    983 }
    984 
    985 /*
    986  * Used only from trargs(), which itself is used only to print
    987  * arg lists (argv[]) either that passed into this shell, or
    988  * the arg list about to be given to some other command (incl
    989  * builtin, and function) as their argv[].  If any of the CTL*
    990  * chars seem to appear, they really should be just treated as data,
    991  * not special...   But this is just debug, so, who cares!
    992  */
    993 static void
    994 trstring(const char *s)
    995 {
    996 	const char *p;
    997 	char c;
    998 	TFILE *fp;
    999 
   1000 	if (debug != 1 || !tracetfile)
   1001 		return;
   1002 	fp = tracetfile;
   1003 	trace_putc('"', fp);
   1004 	for (p = s ; *p ; p++) {
   1005 		switch (*p) {
   1006 		case '\n':  c = 'n';  goto backslash;
   1007 		case '\t':  c = 't';  goto backslash;
   1008 		case '\r':  c = 'r';  goto backslash;
   1009 		case '"':  c = '"';  goto backslash;
   1010 		case '\\':  c = '\\';  goto backslash;
   1011 		case CTLESC:  c = 'e';  goto backslash;
   1012 		case CTLVAR:  c = 'v';  goto backslash;
   1013 		case CTLVAR+CTLQUOTE:  c = 'V';  goto backslash;
   1014 		case CTLBACKQ:  c = 'q';  goto backslash;
   1015 		case CTLBACKQ+CTLQUOTE:  c = 'Q';  goto backslash;
   1016 backslash:		trace_putc('\\', fp);
   1017 			trace_putc(c, fp);
   1018 			break;
   1019 		default:
   1020 			if (*p >= ' ' && *p <= '~')
   1021 				trace_putc(*p, fp);
   1022 			else {
   1023 				trace_putc('\\', fp);
   1024 				trace_putc(*p >> 6 & 03, fp);
   1025 				trace_putc(*p >> 3 & 07, fp);
   1026 				trace_putc(*p & 07, fp);
   1027 			}
   1028 			break;
   1029 		}
   1030 	}
   1031 	trace_putc('"', fp);
   1032 }
   1033 
   1034 /*
   1035  * deal with the user "accidentally" picking our fd to use.
   1036  */
   1037 static void
   1038 trace_fd_swap(int from, int to)
   1039 {
   1040 	if (tracetfile == NULL || from == to)
   1041 		return;
   1042 
   1043 	tracetfile->tfd = to;
   1044 
   1045 	/*
   1046 	 * This is just so histedit has a stdio FILE* to use.
   1047 	 */
   1048 	if (tracefile)
   1049 		fclose(tracefile);
   1050 	tracefile = fdopen(to, "a");
   1051 	if (tracefile)
   1052 		setlinebuf(tracefile);
   1053 }
   1054 
   1055 
   1056 static struct debug_flag {
   1057 	char		label;
   1058 	uint64_t	flag;
   1059 } debug_flags[] = {
   1060 	{ 'a',	DBG_ARITH	},	/* arithmetic ( $(( )) ) */
   1061 	{ 'c',	DBG_CMDS	},	/* command searching, ... */
   1062 	{ 'e',	DBG_EVAL	},	/* evaluation of the parse tree */
   1063 	{ 'f',	DBG_REDIR	},	/* file descriptors & redirections */
   1064 	{ 'g',	DBG_MATCH	},	/* pattern matching (glob) */
   1065 	{ 'h',	DBG_HISTORY	},	/* history & cmd line editing */
   1066 	{ 'i',	DBG_INPUT	},	/* shell input routines */
   1067 	{ 'j',	DBG_JOBS	},	/* job control, structures */
   1068 	{ 'l',	DBG_LEXER	},	/* lexical analysis */
   1069 	{ 'm',	DBG_MEM		},	/* memory management */
   1070 	{ 'o',	DBG_OUTPUT	},	/* output routines */
   1071 	{ 'p',	DBG_PROCS	},	/* process management, fork, ... */
   1072 	{ 'r',	DBG_PARSE	},	/* parser, lexer, ... tree building */
   1073 	{ 's',	DBG_SIG		},	/* signals and everything related */
   1074 	{ 't',	DBG_TRAP	},	/* traps & signals */
   1075 	{ 'v',	DBG_VARS	},	/* variables and parameters */
   1076 	{ 'w',	DBG_WAIT	},	/* waits for processes to finish */
   1077 	{ 'x',	DBG_EXPAND	},	/* word expansion ${} $() $(( )) */
   1078 	{ 'z',	DBG_ERRS	},	/* error control, jumps, cleanup */
   1079 
   1080 	{ '0',	DBG_U0		},	/* ad-hoc temp debug flag #0 */
   1081 	{ '1',	DBG_U1		},	/* ad-hoc temp debug flag #1 */
   1082 	{ '2',	DBG_U2		},	/* ad-hoc temp debug flag #2 */
   1083 	{ '3',	DBG_U3		},	/* ad-hoc temp debug flag #3 */
   1084 
   1085 	{ '@',	DBG_LINE	},	/* prefix trace lines with line# */
   1086 	{ '$',	DBG_PID		},	/* prefix trace lines with sh pid */
   1087 	{ '^',	DBG_NEST	},	/* show shell nesting level */
   1088 
   1089 			/* alpha options only - but not DBG_LEXER */
   1090 	{ '_',	DBG_PARSE | DBG_EVAL | DBG_EXPAND | DBG_JOBS | DBG_SIG |
   1091 		    DBG_PROCS | DBG_REDIR | DBG_CMDS | DBG_ERRS |
   1092 		    DBG_WAIT | DBG_TRAP | DBG_VARS | DBG_MEM | DBG_MATCH |
   1093 		    DBG_INPUT | DBG_OUTPUT | DBG_ARITH | DBG_HISTORY },
   1094 
   1095    /*   { '*',	DBG_ALLVERBOSE	}, 	   is handled in the code */
   1096 
   1097 	{ '#',	DBG_U0 | DBG_U1 | DBG_U2 | DBG_U3 },
   1098 
   1099 	{ 0,	0		}
   1100 };
   1101 
   1102 void
   1103 set_debug(const char * flags, int on)
   1104 {
   1105 	char f;
   1106 	struct debug_flag *df;
   1107 	int verbose;
   1108 
   1109 	while ((f = *flags++) != '\0') {
   1110 		verbose = 0;
   1111 		if (is_upper(f)) {
   1112 			verbose = 1;
   1113 			f += 'a' - 'A';
   1114 		}
   1115 		if (f == '*')
   1116 			f = '_', verbose = 1;
   1117 		if (f == '+') {
   1118 			if (*flags == '+')
   1119 				flags++, verbose=1;
   1120 		}
   1121 
   1122 		/*
   1123 		 * Note: turning on any debug option also enables DBG_ALWAYS
   1124 		 * turning on any verbose option also enables DBG_VERBOSE
   1125 		 * Once enabled, those flags cannot be disabled.
   1126 		 * (tracing can still be turned off with "set +o debug")
   1127 		 */
   1128 		for (df = debug_flags; df->label != '\0'; df++) {
   1129 			if (f == '+' || df->label == f) {
   1130 				if (on) {
   1131 					DFlags |= DBG_ALWAYS | df->flag;
   1132 					if (verbose)
   1133 					    DFlags |= DBG_VERBOSE |
   1134 						(df->flag << DBG_VBOSE_SHIFT);
   1135 				} else {
   1136 					DFlags &= ~(df->flag<<DBG_VBOSE_SHIFT);
   1137 					if (!verbose)
   1138 						DFlags &= ~df->flag;
   1139 				}
   1140 			}
   1141 		}
   1142 	}
   1143 }
   1144 
   1145 
   1146 int
   1147 debugcmd(int argc, char **argv)
   1148 {
   1149 	if (argc == 1) {
   1150 		struct debug_flag *df;
   1151 
   1152 		out1fmt("Debug: %sabled.  Flags: ", debug ? "en" : "dis");
   1153 		for (df = debug_flags; df->label != '\0'; df++) {
   1154 			if (df->flag & (df->flag - 1))
   1155 				continue;
   1156 			if (is_alpha(df->label) &&
   1157 			    (df->flag << DBG_VBOSE_SHIFT) & DFlags)
   1158 				out1c(df->label - ('a' - 'A'));
   1159 			else if (df->flag & DFlags)
   1160 				out1c(df->label);
   1161 		}
   1162 		out1c('\n');
   1163 		return 0;
   1164 	}
   1165 
   1166 	while (*++argv) {
   1167 		if (**argv == '-')
   1168 			set_debug(*argv + 1, 1);
   1169 		else if (**argv == '+')
   1170 			set_debug(*argv + 1, 0);
   1171 		else
   1172 			return 1;
   1173 	}
   1174 	return 0;
   1175 }
   1176 
   1177 #endif /* DEBUG */
   1178