[BACK]Return to run.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / awk

Annotation of src/usr.bin/awk/run.c, Revision 1.20

1.20    ! pvalchev    1: /*     $OpenBSD: run.c,v 1.19 2003/04/04 00:42:34 deraadt Exp $        */
1.1       tholo       2: /****************************************************************
1.13      kstailey    3: Copyright (C) Lucent Technologies 1997
1.1       tholo       4: All Rights Reserved
                      5:
                      6: Permission to use, copy, modify, and distribute this software and
                      7: its documentation for any purpose and without fee is hereby
                      8: granted, provided that the above copyright notice appear in all
                      9: copies and that both that the copyright notice and this
                     10: permission notice and warranty disclaimer appear in supporting
1.13      kstailey   11: documentation, and that the name Lucent Technologies or any of
                     12: its entities not be used in advertising or publicity pertaining
                     13: to distribution of the software without specific, written prior
                     14: permission.
                     15:
                     16: LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
                     17: INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
                     18: IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
                     19: SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     20: WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
                     21: IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
                     22: ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
                     23: THIS SOFTWARE.
1.1       tholo      24: ****************************************************************/
                     25:
                     26: #define DEBUG
                     27: #include <stdio.h>
                     28: #include <ctype.h>
                     29: #include <setjmp.h>
                     30: #include <math.h>
                     31: #include <string.h>
                     32: #include <stdlib.h>
                     33: #include <time.h>
                     34: #include "awk.h"
1.13      kstailey   35: #include "ytab.h"
1.1       tholo      36:
                     37: #define tempfree(x)    if (istemp(x)) tfree(x); else
                     38:
                     39: /*
                     40: #undef tempfree
                     41:
                     42: void tempfree(Cell *p) {
                     43:        if (p->ctype == OCELL && (p->csub < CUNK || p->csub > CFREE)) {
1.16      millert    44:                WARNING("bad csub %d in Cell %d %s",
                     45:                        p->csub, p->ctype, p->sval);
1.1       tholo      46:        }
                     47:        if (istemp(p))
                     48:                tfree(p);
                     49: }
                     50: */
                     51:
                     52: #ifdef _NFILE
                     53: #ifndef FOPEN_MAX
                     54: #define FOPEN_MAX _NFILE
                     55: #endif
                     56: #endif
                     57:
                     58: #ifndef        FOPEN_MAX
                     59: #define        FOPEN_MAX       40      /* max number of open files */
                     60: #endif
                     61:
                     62: #ifndef RAND_MAX
                     63: #define RAND_MAX       32767   /* all that ansi guarantees */
                     64: #endif
                     65:
                     66: jmp_buf env;
1.13      kstailey   67: extern int     pairstack[];
1.1       tholo      68:
                     69: Node   *winner = NULL; /* root of parse tree */
                     70: Cell   *tmps;          /* free temporary cells for execution */
                     71:
                     72: static Cell    truecell        ={ OBOOL, BTRUE, 0, 0, 1.0, NUM };
1.15      millert    73: Cell   *True   = &truecell;
1.1       tholo      74: static Cell    falsecell       ={ OBOOL, BFALSE, 0, 0, 0.0, NUM };
1.15      millert    75: Cell   *False  = &falsecell;
1.1       tholo      76: static Cell    breakcell       ={ OJUMP, JBREAK, 0, 0, 0.0, NUM };
                     77: Cell   *jbreak = &breakcell;
                     78: static Cell    contcell        ={ OJUMP, JCONT, 0, 0, 0.0, NUM };
                     79: Cell   *jcont  = &contcell;
                     80: static Cell    nextcell        ={ OJUMP, JNEXT, 0, 0, 0.0, NUM };
                     81: Cell   *jnext  = &nextcell;
                     82: static Cell    nextfilecell    ={ OJUMP, JNEXTFILE, 0, 0, 0.0, NUM };
                     83: Cell   *jnextfile      = &nextfilecell;
                     84: static Cell    exitcell        ={ OJUMP, JEXIT, 0, 0, 0.0, NUM };
                     85: Cell   *jexit  = &exitcell;
                     86: static Cell    retcell         ={ OJUMP, JRET, 0, 0, 0.0, NUM };
                     87: Cell   *jret   = &retcell;
1.13      kstailey   88: static Cell    tempcell        ={ OCELL, CTEMP, 0, "", 0.0, NUM|STR|DONTFREE };
1.1       tholo      89:
                     90: Node   *curnode = NULL;        /* the node being executed, for debugging */
                     91:
1.13      kstailey   92: /* buffer memory management */
                     93: int adjbuf(char **pbuf, int *psiz, int minlen, int quantum, char **pbptr,
1.18      millert    94:        const char *whatrtn)
1.13      kstailey   95: /* pbuf:    address of pointer to buffer being managed
                     96:  * psiz:    address of buffer size variable
                     97:  * minlen:  minimum length of buffer needed
                     98:  * quantum: buffer size quantum
                     99:  * pbptr:   address of movable pointer into buffer, or 0 if none
                    100:  * whatrtn: name of the calling routine if failure should cause fatal error
                    101:  *
                    102:  * return   0 for realloc failure, !=0 for success
                    103:  */
                    104: {
                    105:        if (minlen > *psiz) {
                    106:                char *tbuf;
                    107:                int rminlen = quantum ? minlen % quantum : 0;
                    108:                int boff = pbptr ? *pbptr - *pbuf : 0;
                    109:                /* round up to next multiple of quantum */
                    110:                if (rminlen)
                    111:                        minlen += quantum - rminlen;
1.15      millert   112:                tbuf = (char *) realloc(*pbuf, minlen);
1.13      kstailey  113:                if (tbuf == NULL) {
                    114:                        if (whatrtn)
1.16      millert   115:                                FATAL("out of memory in %s", whatrtn);
1.13      kstailey  116:                        return 0;
                    117:                }
                    118:                *pbuf = tbuf;
                    119:                *psiz = minlen;
                    120:                if (pbptr)
                    121:                        *pbptr = tbuf + boff;
                    122:        }
                    123:        return 1;
                    124: }
                    125:
1.1       tholo     126: void run(Node *a)      /* execution of parse tree starts here */
                    127: {
1.16      millert   128:        extern void stdinit(void);
                    129:
                    130:        stdinit();
1.1       tholo     131:        execute(a);
                    132:        closeall();
                    133: }
                    134:
                    135: Cell *execute(Node *u) /* execute a node of the parse tree */
                    136: {
                    137:        Cell *(*proc)(Node **, int);
                    138:        Cell *x;
                    139:        Node *a;
                    140:
                    141:        if (u == NULL)
1.15      millert   142:                return(True);
1.1       tholo     143:        for (a = u; ; a = a->nnext) {
                    144:                curnode = a;
                    145:                if (isvalue(a)) {
1.2       millert   146:                        x = (Cell *) (a->narg[0]);
1.13      kstailey  147:                        if (isfld(x) && !donefld)
1.1       tholo     148:                                fldbld();
1.13      kstailey  149:                        else if (isrec(x) && !donerec)
1.1       tholo     150:                                recbld();
                    151:                        return(x);
                    152:                }
                    153:                if (notlegal(a->nobj))  /* probably a Cell* but too risky to print */
1.16      millert   154:                        FATAL("illegal statement");
1.1       tholo     155:                proc = proctab[a->nobj-FIRSTTOKEN];
                    156:                x = (*proc)(a->narg, a->nobj);
1.13      kstailey  157:                if (isfld(x) && !donefld)
1.1       tholo     158:                        fldbld();
1.13      kstailey  159:                else if (isrec(x) && !donerec)
1.1       tholo     160:                        recbld();
                    161:                if (isexpr(a))
                    162:                        return(x);
                    163:                if (isjump(x))
                    164:                        return(x);
                    165:                if (a->nnext == NULL)
                    166:                        return(x);
                    167:                tempfree(x);
                    168:        }
                    169: }
                    170:
                    171:
                    172: Cell *program(Node **a, int n) /* execute an awk program */
                    173: {                              /* a[0] = BEGIN, a[1] = body, a[2] = END */
                    174:        Cell *x;
                    175:
                    176:        if (setjmp(env) != 0)
                    177:                goto ex;
                    178:        if (a[0]) {             /* BEGIN */
                    179:                x = execute(a[0]);
                    180:                if (isexit(x))
1.15      millert   181:                        return(True);
1.1       tholo     182:                if (isjump(x))
1.16      millert   183:                        FATAL("illegal break, continue, next or nextfile from BEGIN");
1.1       tholo     184:                tempfree(x);
                    185:        }
                    186:        if (a[1] || a[2])
1.13      kstailey  187:                while (getrec(&record, &recsize, 1) > 0) {
1.1       tholo     188:                        x = execute(a[1]);
                    189:                        if (isexit(x))
                    190:                                break;
                    191:                        tempfree(x);
                    192:                }
                    193:   ex:
                    194:        if (setjmp(env) != 0)   /* handles exit within END */
                    195:                goto ex1;
                    196:        if (a[2]) {             /* END */
                    197:                x = execute(a[2]);
                    198:                if (isbreak(x) || isnext(x) || iscont(x))
1.16      millert   199:                        FATAL("illegal break, continue, next or nextfile from END");
1.1       tholo     200:                tempfree(x);
                    201:        }
                    202:   ex1:
1.15      millert   203:        return(True);
1.1       tholo     204: }
                    205:
                    206: struct Frame { /* stack frame for awk function calls */
                    207:        int nargs;      /* number of arguments in this call */
                    208:        Cell *fcncell;  /* pointer to Cell for function */
                    209:        Cell **args;    /* pointer to array of arguments after execute */
                    210:        Cell *retval;   /* return value */
                    211: };
                    212:
                    213: #define        NARGS   50      /* max args in a call */
                    214:
                    215: struct Frame *frame = NULL;    /* base of stack frames; dynamically allocated */
                    216: int    nframe = 0;             /* number of frames allocated */
                    217: struct Frame *fp = NULL;       /* frame pointer. bottom level unused */
                    218:
                    219: Cell *call(Node **a, int n)    /* function call.  very kludgy and fragile */
                    220: {
1.13      kstailey  221:        static Cell newcopycell = { OCELL, CCOPY, 0, "", 0.0, NUM|STR|DONTFREE };
1.1       tholo     222:        int i, ncall, ndef;
                    223:        Node *x;
1.13      kstailey  224:        Cell *args[NARGS], *oargs[NARGS];       /* BUG: fixed size arrays */
                    225:        Cell *y, *z, *fcn;
1.1       tholo     226:        char *s;
                    227:
                    228:        fcn = execute(a[0]);    /* the function itself */
                    229:        s = fcn->nval;
1.13      kstailey  230:        if (!isfcn(fcn))
1.16      millert   231:                FATAL("calling undefined function %s", s);
1.1       tholo     232:        if (frame == NULL) {
                    233:                fp = frame = (struct Frame *) calloc(nframe += 100, sizeof(struct Frame));
                    234:                if (frame == NULL)
1.16      millert   235:                        FATAL("out of space for stack frames calling %s", s);
1.1       tholo     236:        }
                    237:        for (ncall = 0, x = a[1]; x != NULL; x = x->nnext)      /* args in call */
                    238:                ncall++;
1.12      millert   239:        ndef = (int) fcn->fval;                 /* args in defn */
1.15      millert   240:           dprintf( ("calling %s, %d args (%d in defn), fp=%d\n", s, ncall, ndef, (int) (fp-frame)) );
1.1       tholo     241:        if (ncall > ndef)
1.16      millert   242:                WARNING("function %s called with %d args, uses only %d",
                    243:                        s, ncall, ndef);
1.1       tholo     244:        if (ncall + ndef > NARGS)
1.16      millert   245:                FATAL("function %s has %d arguments, limit %d", s, ncall+ndef, NARGS);
1.1       tholo     246:        for (i = 0, x = a[1]; x != NULL; i++, x = x->nnext) {   /* get call args */
1.15      millert   247:                   dprintf( ("evaluate args[%d], fp=%d:\n", i, (int) (fp-frame)) );
1.1       tholo     248:                y = execute(x);
                    249:                oargs[i] = y;
1.13      kstailey  250:                   dprintf( ("args[%d]: %s %f <%s>, t=%o\n",
1.18      millert   251:                           i, NN(y->nval), y->fval, isarr(y) ? "(array)" : NN(y->sval), y->tval) );
1.13      kstailey  252:                if (isfcn(y))
1.16      millert   253:                        FATAL("can't use function %s as argument in %s", y->nval, s);
1.1       tholo     254:                if (isarr(y))
                    255:                        args[i] = y;    /* arrays by ref */
                    256:                else
                    257:                        args[i] = copycell(y);
                    258:                tempfree(y);
                    259:        }
                    260:        for ( ; i < ndef; i++) {        /* add null args for ones not provided */
                    261:                args[i] = gettemp();
                    262:                *args[i] = newcopycell;
                    263:        }
                    264:        fp++;   /* now ok to up frame */
                    265:        if (fp >= frame + nframe) {
                    266:                int dfp = fp - frame;   /* old index */
                    267:                frame = (struct Frame *)
                    268:                        realloc((char *) frame, (nframe += 100) * sizeof(struct Frame));
                    269:                if (frame == NULL)
1.16      millert   270:                        FATAL("out of space for stack frames in %s", s);
1.1       tholo     271:                fp = frame + dfp;
                    272:        }
                    273:        fp->fcncell = fcn;
                    274:        fp->args = args;
                    275:        fp->nargs = ndef;       /* number defined with (excess are locals) */
                    276:        fp->retval = gettemp();
                    277:
1.15      millert   278:           dprintf( ("start exec of %s, fp=%d\n", s, (int) (fp-frame)) );
1.1       tholo     279:        y = execute((Node *)(fcn->sval));       /* execute body */
1.15      millert   280:           dprintf( ("finished exec of %s, fp=%d\n", s, (int) (fp-frame)) );
1.1       tholo     281:
                    282:        for (i = 0; i < ndef; i++) {
                    283:                Cell *t = fp->args[i];
                    284:                if (isarr(t)) {
                    285:                        if (t->csub == CCOPY) {
                    286:                                if (i >= ncall) {
                    287:                                        freesymtab(t);
                    288:                                        t->csub = CTEMP;
1.14      millert   289:                                        tempfree(t);
1.1       tholo     290:                                } else {
                    291:                                        oargs[i]->tval = t->tval;
                    292:                                        oargs[i]->tval &= ~(STR|NUM|DONTFREE);
                    293:                                        oargs[i]->sval = t->sval;
                    294:                                        tempfree(t);
                    295:                                }
                    296:                        }
                    297:                } else if (t != y) {    /* kludge to prevent freeing twice */
                    298:                        t->csub = CTEMP;
                    299:                        tempfree(t);
                    300:                }
                    301:        }
                    302:        tempfree(fcn);
1.17      millert   303:        if (isexit(y) || isnext(y))
1.1       tholo     304:                return y;
                    305:        tempfree(y);            /* this can free twice! */
                    306:        z = fp->retval;                 /* return value */
1.13      kstailey  307:           dprintf( ("%s returns %g |%s| %o\n", s, getfval(z), getsval(z), z->tval) );
1.1       tholo     308:        fp--;
                    309:        return(z);
                    310: }
                    311:
                    312: Cell *copycell(Cell *x)        /* make a copy of a cell in a temp */
                    313: {
                    314:        Cell *y;
                    315:
                    316:        y = gettemp();
                    317:        y->csub = CCOPY;        /* prevents freeing until call is over */
1.13      kstailey  318:        y->nval = x->nval;      /* BUG? */
1.17      millert   319:        if (isstr(x))
                    320:                y->sval = tostring(x->sval);
1.1       tholo     321:        y->fval = x->fval;
                    322:        y->tval = x->tval & ~(CON|FLD|REC|DONTFREE);    /* copy is not constant or field */
                    323:                                                        /* is DONTFREE right? */
                    324:        return y;
                    325: }
                    326:
                    327: Cell *arg(Node **a, int n)     /* nth argument of a function */
                    328: {
                    329:
1.15      millert   330:        n = ptoi(a[0]); /* argument number, counting from 0 */
1.13      kstailey  331:           dprintf( ("arg(%d), fp->nargs=%d\n", n, fp->nargs) );
1.1       tholo     332:        if (n+1 > fp->nargs)
1.16      millert   333:                FATAL("argument #%d of function %s was not supplied",
                    334:                        n+1, fp->fcncell->nval);
1.1       tholo     335:        return fp->args[n];
                    336: }
                    337:
                    338: Cell *jump(Node **a, int n)    /* break, continue, next, nextfile, return */
                    339: {
                    340:        Cell *y;
                    341:
                    342:        switch (n) {
                    343:        case EXIT:
                    344:                if (a[0] != NULL) {
                    345:                        y = execute(a[0]);
1.14      millert   346:                        errorflag = (int) getfval(y);
1.1       tholo     347:                        tempfree(y);
                    348:                }
                    349:                longjmp(env, 1);
                    350:        case RETURN:
                    351:                if (a[0] != NULL) {
                    352:                        y = execute(a[0]);
                    353:                        if ((y->tval & (STR|NUM)) == (STR|NUM)) {
                    354:                                setsval(fp->retval, getsval(y));
                    355:                                fp->retval->fval = getfval(y);
                    356:                                fp->retval->tval |= NUM;
                    357:                        }
                    358:                        else if (y->tval & STR)
                    359:                                setsval(fp->retval, getsval(y));
                    360:                        else if (y->tval & NUM)
                    361:                                setfval(fp->retval, getfval(y));
                    362:                        else            /* can't happen */
1.16      millert   363:                                FATAL("bad type variable %d", y->tval);
1.1       tholo     364:                        tempfree(y);
                    365:                }
                    366:                return(jret);
                    367:        case NEXT:
                    368:                return(jnext);
                    369:        case NEXTFILE:
                    370:                nextfile();
                    371:                return(jnextfile);
                    372:        case BREAK:
                    373:                return(jbreak);
                    374:        case CONTINUE:
                    375:                return(jcont);
                    376:        default:        /* can't happen */
1.16      millert   377:                FATAL("illegal jump type %d", n);
1.1       tholo     378:        }
                    379:        return 0;       /* not reached */
                    380: }
                    381:
                    382: Cell *getline(Node **a, int n) /* get next line from specific input */
                    383: {              /* a[0] is variable, a[1] is operator, a[2] is filename */
                    384:        Cell *r, *x;
1.13      kstailey  385:        extern Cell **fldtab;
1.1       tholo     386:        FILE *fp;
1.13      kstailey  387:        char *buf;
                    388:        int bufsize = recsize;
1.15      millert   389:        int mode;
1.13      kstailey  390:
                    391:        if ((buf = (char *) malloc(bufsize)) == NULL)
1.16      millert   392:                FATAL("out of memory in getline");
1.1       tholo     393:
                    394:        fflush(stdout); /* in case someone is waiting for a prompt */
                    395:        r = gettemp();
                    396:        if (a[1] != NULL) {             /* getline < file */
                    397:                x = execute(a[2]);              /* filename */
1.15      millert   398:                mode = ptoi(a[1]);
                    399:                if (mode == '|')                /* input pipe */
                    400:                        mode = LE;      /* arbitrary flag */
                    401:                fp = openfile(mode, getsval(x));
1.1       tholo     402:                tempfree(x);
                    403:                if (fp == NULL)
                    404:                        n = -1;
                    405:                else
1.13      kstailey  406:                        n = readrec(&buf, &bufsize, fp);
1.1       tholo     407:                if (n <= 0) {
                    408:                        ;
                    409:                } else if (a[0] != NULL) {      /* getline var <file */
1.13      kstailey  410:                        x = execute(a[0]);
                    411:                        setsval(x, buf);
                    412:                        tempfree(x);
1.1       tholo     413:                } else {                        /* getline <file */
1.13      kstailey  414:                        setsval(fldtab[0], buf);
1.14      millert   415:                        if (is_number(fldtab[0]->sval)) {
1.13      kstailey  416:                                fldtab[0]->fval = atof(fldtab[0]->sval);
                    417:                                fldtab[0]->tval |= NUM;
1.1       tholo     418:                        }
                    419:                }
                    420:        } else {                        /* bare getline; use current input */
                    421:                if (a[0] == NULL)       /* getline */
1.13      kstailey  422:                        n = getrec(&record, &recsize, 1);
1.1       tholo     423:                else {                  /* getline var */
1.13      kstailey  424:                        n = getrec(&buf, &bufsize, 0);
                    425:                        x = execute(a[0]);
                    426:                        setsval(x, buf);
                    427:                        tempfree(x);
1.1       tholo     428:                }
                    429:        }
                    430:        setfval(r, (Awkfloat) n);
1.13      kstailey  431:        free(buf);
1.1       tholo     432:        return r;
                    433: }
                    434:
                    435: Cell *getnf(Node **a, int n)   /* get NF */
                    436: {
                    437:        if (donefld == 0)
                    438:                fldbld();
                    439:        return (Cell *) a[0];
                    440: }
                    441:
                    442: Cell *array(Node **a, int n)   /* a[0] is symtab, a[1] is list of subscripts */
                    443: {
                    444:        Cell *x, *y, *z;
                    445:        char *s;
                    446:        Node *np;
1.13      kstailey  447:        char *buf;
                    448:        int bufsz = recsize;
                    449:        int nsub = strlen(*SUBSEP);
                    450:
1.15      millert   451:        if ((buf = (char *) malloc(bufsz)) == NULL)
1.16      millert   452:                FATAL("out of memory in array");
1.1       tholo     453:
                    454:        x = execute(a[0]);      /* Cell* for symbol table */
                    455:        buf[0] = 0;
                    456:        for (np = a[1]; np; np = np->nnext) {
                    457:                y = execute(np);        /* subscript */
                    458:                s = getsval(y);
1.13      kstailey  459:                if (!adjbuf(&buf, &bufsz, strlen(buf)+strlen(s)+nsub+1, recsize, 0, 0))
1.16      millert   460:                        FATAL("out of memory for %s[%s...]", x->nval, buf);
1.20    ! pvalchev  461:                strlcat(buf, s, bufsz);
1.1       tholo     462:                if (np->nnext)
1.20    ! pvalchev  463:                        strlcat(buf, *SUBSEP, bufsz);
1.1       tholo     464:                tempfree(y);
                    465:        }
                    466:        if (!isarr(x)) {
1.18      millert   467:                   dprintf( ("making %s into an array\n", NN(x->nval)) );
1.1       tholo     468:                if (freeable(x))
                    469:                        xfree(x->sval);
                    470:                x->tval &= ~(STR|NUM|DONTFREE);
                    471:                x->tval |= ARR;
                    472:                x->sval = (char *) makesymtab(NSYMTAB);
                    473:        }
                    474:        z = setsymtab(buf, "", 0.0, STR|NUM, (Array *) x->sval);
                    475:        z->ctype = OCELL;
                    476:        z->csub = CVAR;
                    477:        tempfree(x);
1.13      kstailey  478:        free(buf);
1.1       tholo     479:        return(z);
                    480: }
                    481:
1.14      millert   482: Cell *awkdelete(Node **a, int n)       /* a[0] is symtab, a[1] is list of subscripts */
1.1       tholo     483: {
                    484:        Cell *x, *y;
                    485:        Node *np;
1.13      kstailey  486:        char *s;
                    487:        int nsub = strlen(*SUBSEP);
1.1       tholo     488:
                    489:        x = execute(a[0]);      /* Cell* for symbol table */
                    490:        if (!isarr(x))
1.15      millert   491:                return True;
1.1       tholo     492:        if (a[1] == 0) {        /* delete the elements, not the table */
                    493:                freesymtab(x);
                    494:                x->tval &= ~STR;
                    495:                x->tval |= ARR;
                    496:                x->sval = (char *) makesymtab(NSYMTAB);
                    497:        } else {
1.13      kstailey  498:                int bufsz = recsize;
                    499:                char *buf;
1.15      millert   500:                if ((buf = (char *) malloc(bufsz)) == NULL)
1.16      millert   501:                        FATAL("out of memory in adelete");
1.1       tholo     502:                buf[0] = 0;
                    503:                for (np = a[1]; np; np = np->nnext) {
                    504:                        y = execute(np);        /* subscript */
                    505:                        s = getsval(y);
1.13      kstailey  506:                        if (!adjbuf(&buf, &bufsz, strlen(buf)+strlen(s)+nsub+1, recsize, 0, 0))
1.16      millert   507:                                FATAL("out of memory deleting %s[%s...]", x->nval, buf);
1.20    ! pvalchev  508:                        strlcat(buf, s, bufsz);
1.1       tholo     509:                        if (np->nnext)
1.20    ! pvalchev  510:                                strlcat(buf, *SUBSEP, bufsz);
1.1       tholo     511:                        tempfree(y);
                    512:                }
                    513:                freeelem(x, buf);
1.13      kstailey  514:                free(buf);
1.1       tholo     515:        }
                    516:        tempfree(x);
1.15      millert   517:        return True;
1.1       tholo     518: }
                    519:
                    520: Cell *intest(Node **a, int n)  /* a[0] is index (list), a[1] is symtab */
                    521: {
                    522:        Cell *x, *ap, *k;
                    523:        Node *p;
1.13      kstailey  524:        char *buf;
1.1       tholo     525:        char *s;
1.13      kstailey  526:        int bufsz = recsize;
                    527:        int nsub = strlen(*SUBSEP);
1.1       tholo     528:
                    529:        ap = execute(a[1]);     /* array name */
                    530:        if (!isarr(ap)) {
1.13      kstailey  531:                   dprintf( ("making %s into an array\n", ap->nval) );
1.1       tholo     532:                if (freeable(ap))
                    533:                        xfree(ap->sval);
                    534:                ap->tval &= ~(STR|NUM|DONTFREE);
                    535:                ap->tval |= ARR;
                    536:                ap->sval = (char *) makesymtab(NSYMTAB);
                    537:        }
1.15      millert   538:        if ((buf = (char *) malloc(bufsz)) == NULL) {
1.16      millert   539:                FATAL("out of memory in intest");
1.13      kstailey  540:        }
1.1       tholo     541:        buf[0] = 0;
                    542:        for (p = a[0]; p; p = p->nnext) {
                    543:                x = execute(p); /* expr */
                    544:                s = getsval(x);
1.13      kstailey  545:                if (!adjbuf(&buf, &bufsz, strlen(buf)+strlen(s)+nsub+1, recsize, 0, 0))
1.16      millert   546:                        FATAL("out of memory deleting %s[%s...]", x->nval, buf);
1.20    ! pvalchev  547:                strlcat(buf, s, bufsz);
1.1       tholo     548:                tempfree(x);
                    549:                if (p->nnext)
1.20    ! pvalchev  550:                        strlcat(buf, *SUBSEP, bufsz);
1.1       tholo     551:        }
                    552:        k = lookup(buf, (Array *) ap->sval);
                    553:        tempfree(ap);
1.13      kstailey  554:        free(buf);
1.1       tholo     555:        if (k == NULL)
1.15      millert   556:                return(False);
1.1       tholo     557:        else
1.15      millert   558:                return(True);
1.1       tholo     559: }
                    560:
                    561:
                    562: Cell *matchop(Node **a, int n) /* ~ and match() */
                    563: {
                    564:        Cell *x, *y;
                    565:        char *s, *t;
                    566:        int i;
                    567:        fa *pfa;
1.18      millert   568:        int (*mf)(fa *, const char *) = match, mode = 0;
1.1       tholo     569:
                    570:        if (n == MATCHFCN) {
                    571:                mf = pmatch;
                    572:                mode = 1;
                    573:        }
                    574:        x = execute(a[1]);      /* a[1] = target text */
                    575:        s = getsval(x);
                    576:        if (a[0] == 0)          /* a[1] == 0: already-compiled reg expr */
                    577:                i = (*mf)((fa *) a[2], s);
                    578:        else {
                    579:                y = execute(a[2]);      /* a[2] = regular expr */
                    580:                t = getsval(y);
                    581:                pfa = makedfa(t, mode);
                    582:                i = (*mf)(pfa, s);
                    583:                tempfree(y);
                    584:        }
                    585:        tempfree(x);
                    586:        if (n == MATCHFCN) {
                    587:                int start = patbeg - s + 1;
                    588:                if (patlen < 0)
                    589:                        start = 0;
                    590:                setfval(rstartloc, (Awkfloat) start);
                    591:                setfval(rlengthloc, (Awkfloat) patlen);
                    592:                x = gettemp();
                    593:                x->tval = NUM;
                    594:                x->fval = start;
                    595:                return x;
                    596:        } else if ((n == MATCH && i == 1) || (n == NOTMATCH && i == 0))
1.15      millert   597:                return(True);
1.1       tholo     598:        else
1.15      millert   599:                return(False);
1.1       tholo     600: }
                    601:
                    602:
                    603: Cell *boolop(Node **a, int n)  /* a[0] || a[1], a[0] && a[1], !a[0] */
                    604: {
                    605:        Cell *x, *y;
                    606:        int i;
                    607:
                    608:        x = execute(a[0]);
                    609:        i = istrue(x);
                    610:        tempfree(x);
                    611:        switch (n) {
                    612:        case BOR:
1.15      millert   613:                if (i) return(True);
1.1       tholo     614:                y = execute(a[1]);
                    615:                i = istrue(y);
                    616:                tempfree(y);
1.15      millert   617:                if (i) return(True);
                    618:                else return(False);
1.1       tholo     619:        case AND:
1.15      millert   620:                if ( !i ) return(False);
1.1       tholo     621:                y = execute(a[1]);
                    622:                i = istrue(y);
                    623:                tempfree(y);
1.15      millert   624:                if (i) return(True);
                    625:                else return(False);
1.1       tholo     626:        case NOT:
1.15      millert   627:                if (i) return(False);
                    628:                else return(True);
1.1       tholo     629:        default:        /* can't happen */
1.16      millert   630:                FATAL("unknown boolean operator %d", n);
1.1       tholo     631:        }
                    632:        return 0;       /*NOTREACHED*/
                    633: }
                    634:
                    635: Cell *relop(Node **a, int n)   /* a[0 < a[1], etc. */
                    636: {
                    637:        int i;
                    638:        Cell *x, *y;
                    639:        Awkfloat j;
                    640:
                    641:        x = execute(a[0]);
                    642:        y = execute(a[1]);
                    643:        if (x->tval&NUM && y->tval&NUM) {
                    644:                j = x->fval - y->fval;
                    645:                i = j<0? -1: (j>0? 1: 0);
                    646:        } else {
                    647:                i = strcmp(getsval(x), getsval(y));
                    648:        }
                    649:        tempfree(x);
                    650:        tempfree(y);
                    651:        switch (n) {
1.15      millert   652:        case LT:        if (i<0) return(True);
                    653:                        else return(False);
                    654:        case LE:        if (i<=0) return(True);
                    655:                        else return(False);
                    656:        case NE:        if (i!=0) return(True);
                    657:                        else return(False);
                    658:        case EQ:        if (i == 0) return(True);
                    659:                        else return(False);
                    660:        case GE:        if (i>=0) return(True);
                    661:                        else return(False);
                    662:        case GT:        if (i>0) return(True);
                    663:                        else return(False);
1.1       tholo     664:        default:        /* can't happen */
1.16      millert   665:                FATAL("unknown relational operator %d", n);
1.1       tholo     666:        }
                    667:        return 0;       /*NOTREACHED*/
                    668: }
                    669:
                    670: void tfree(Cell *a)    /* free a tempcell */
                    671: {
1.13      kstailey  672:        if (freeable(a)) {
1.18      millert   673:                   dprintf( ("freeing %s %s %o\n", NN(a->nval), NN(a->sval), a->tval) );
1.1       tholo     674:                xfree(a->sval);
1.13      kstailey  675:        }
1.1       tholo     676:        if (a == tmps)
1.16      millert   677:                FATAL("tempcell list is curdled");
1.1       tholo     678:        a->cnext = tmps;
                    679:        tmps = a;
                    680: }
                    681:
                    682: Cell *gettemp(void)    /* get a tempcell */
                    683: {      int i;
                    684:        Cell *x;
                    685:
                    686:        if (!tmps) {
                    687:                tmps = (Cell *) calloc(100, sizeof(Cell));
                    688:                if (!tmps)
1.16      millert   689:                        FATAL("out of space for temporaries");
1.1       tholo     690:                for(i = 1; i < 100; i++)
                    691:                        tmps[i-1].cnext = &tmps[i];
                    692:                tmps[i-1].cnext = 0;
                    693:        }
                    694:        x = tmps;
                    695:        tmps = x->cnext;
                    696:        *x = tempcell;
                    697:        return(x);
                    698: }
                    699:
                    700: Cell *indirect(Node **a, int n)        /* $( a[0] ) */
                    701: {
                    702:        Cell *x;
                    703:        int m;
                    704:        char *s;
                    705:
                    706:        x = execute(a[0]);
1.14      millert   707:        m = (int) getfval(x);
                    708:        if (m == 0 && !is_number(s = getsval(x)))       /* suspicion! */
1.16      millert   709:                FATAL("illegal field $(%s), name \"%s\"", s, x->nval);
1.13      kstailey  710:                /* BUG: can x->nval ever be null??? */
1.1       tholo     711:        tempfree(x);
                    712:        x = fieldadr(m);
1.13      kstailey  713:        x->ctype = OCELL;       /* BUG?  why are these needed? */
1.1       tholo     714:        x->csub = CFLD;
                    715:        return(x);
                    716: }
                    717:
                    718: Cell *substr(Node **a, int nnn)                /* substr(a[0], a[1], a[2]) */
                    719: {
                    720:        int k, m, n;
                    721:        char *s;
                    722:        int temp;
                    723:        Cell *x, *y, *z = 0;
                    724:
                    725:        x = execute(a[0]);
                    726:        y = execute(a[1]);
                    727:        if (a[2] != 0)
                    728:                z = execute(a[2]);
                    729:        s = getsval(x);
                    730:        k = strlen(s) + 1;
                    731:        if (k <= 1) {
                    732:                tempfree(x);
                    733:                tempfree(y);
1.17      millert   734:                if (a[2] != 0) {
1.1       tholo     735:                        tempfree(z);
1.17      millert   736:                }
1.1       tholo     737:                x = gettemp();
                    738:                setsval(x, "");
                    739:                return(x);
                    740:        }
1.14      millert   741:        m = (int) getfval(y);
1.1       tholo     742:        if (m <= 0)
                    743:                m = 1;
                    744:        else if (m > k)
                    745:                m = k;
                    746:        tempfree(y);
                    747:        if (a[2] != 0) {
1.14      millert   748:                n = (int) getfval(z);
1.1       tholo     749:                tempfree(z);
                    750:        } else
                    751:                n = k - 1;
                    752:        if (n < 0)
                    753:                n = 0;
                    754:        else if (n > k - m)
                    755:                n = k - m;
1.13      kstailey  756:           dprintf( ("substr: m=%d, n=%d, s=%s\n", m, n, s) );
1.1       tholo     757:        y = gettemp();
                    758:        temp = s[n+m-1];        /* with thanks to John Linderman */
                    759:        s[n+m-1] = '\0';
                    760:        setsval(y, s + m - 1);
                    761:        s[n+m-1] = temp;
                    762:        tempfree(x);
                    763:        return(y);
                    764: }
                    765:
                    766: Cell *sindex(Node **a, int nnn)                /* index(a[0], a[1]) */
                    767: {
                    768:        Cell *x, *y, *z;
                    769:        char *s1, *s2, *p1, *p2, *q;
                    770:        Awkfloat v = 0.0;
                    771:
                    772:        x = execute(a[0]);
                    773:        s1 = getsval(x);
                    774:        y = execute(a[1]);
                    775:        s2 = getsval(y);
                    776:
                    777:        z = gettemp();
                    778:        for (p1 = s1; *p1 != '\0'; p1++) {
                    779:                for (q=p1, p2=s2; *p2 != '\0' && *q == *p2; q++, p2++)
                    780:                        ;
                    781:                if (*p2 == '\0') {
                    782:                        v = (Awkfloat) (p1 - s1 + 1);   /* origin 1 */
                    783:                        break;
                    784:                }
                    785:        }
                    786:        tempfree(x);
                    787:        tempfree(y);
                    788:        setfval(z, v);
                    789:        return(z);
                    790: }
                    791:
1.13      kstailey  792: #define        MAXNUMSIZE      50
                    793:
1.18      millert   794: int format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conversions */
1.1       tholo     795: {
1.13      kstailey  796:        char *fmt;
1.18      millert   797:        char *p, *t;
                    798:        const char *os;
1.1       tholo     799:        Cell *x;
1.10      kstailey  800:        int flag = 0, n;
1.13      kstailey  801:        int fmtwd; /* format width */
                    802:        int fmtsz = recsize;
                    803:        char *buf = *pbuf;
                    804:        int bufsize = *pbufsize;
1.1       tholo     805:
                    806:        os = s;
                    807:        p = buf;
1.15      millert   808:        if ((fmt = (char *) malloc(fmtsz)) == NULL)
1.16      millert   809:                FATAL("out of memory in format()");
1.1       tholo     810:        while (*s) {
1.13      kstailey  811:                adjbuf(&buf, &bufsize, MAXNUMSIZE+1+p-buf, recsize, &p, "format");
1.1       tholo     812:                if (*s != '%') {
                    813:                        *p++ = *s++;
                    814:                        continue;
                    815:                }
                    816:                if (*(s+1) == '%') {
                    817:                        *p++ = '%';
                    818:                        s += 2;
                    819:                        continue;
                    820:                }
1.13      kstailey  821:                /* have to be real careful in case this is a huge number, eg, %100000d */
                    822:                fmtwd = atoi(s+1);
                    823:                if (fmtwd < 0)
                    824:                        fmtwd = -fmtwd;
                    825:                adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format");
                    826:                for (t = fmt; (*t++ = *s) != '\0'; s++) {
                    827:                        if (!adjbuf(&fmt, &fmtsz, MAXNUMSIZE+1+t-fmt, recsize, &t, 0))
1.16      millert   828:                                FATAL("format item %.30s... ran format() out of memory", os);
1.17      millert   829:                        if (isalpha((uschar)*s) && *s != 'l' && *s != 'h' && *s != 'L')
1.1       tholo     830:                                break;  /* the ansi panoply */
                    831:                        if (*s == '*') {
                    832:                                x = execute(a);
                    833:                                a = a->nnext;
1.13      kstailey  834:                                sprintf(t-1, "%d", fmtwd=(int) getfval(x));
                    835:                                if (fmtwd < 0)
                    836:                                        fmtwd = -fmtwd;
                    837:                                adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format");
1.1       tholo     838:                                t = fmt + strlen(fmt);
                    839:                                tempfree(x);
                    840:                        }
                    841:                }
                    842:                *t = '\0';
1.13      kstailey  843:                if (fmtwd < 0)
                    844:                        fmtwd = -fmtwd;
                    845:                adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format");
                    846:
1.1       tholo     847:                switch (*s) {
                    848:                case 'f': case 'e': case 'g': case 'E': case 'G':
1.18      millert   849:                        flag = 'f';
1.1       tholo     850:                        break;
                    851:                case 'd': case 'i':
1.18      millert   852:                        flag = 'd';
1.1       tholo     853:                        if(*(s-1) == 'l') break;
                    854:                        *(t-1) = 'l';
                    855:                        *t = 'd';
                    856:                        *++t = '\0';
                    857:                        break;
                    858:                case 'o': case 'x': case 'X': case 'u':
1.18      millert   859:                        flag = *(s-1) == 'l' ? 'd' : 'u';
1.1       tholo     860:                        break;
                    861:                case 's':
1.18      millert   862:                        flag = 's';
1.1       tholo     863:                        break;
                    864:                case 'c':
1.18      millert   865:                        flag = 'c';
1.1       tholo     866:                        break;
                    867:                default:
1.16      millert   868:                        WARNING("weird printf conversion %s", fmt);
1.18      millert   869:                        flag = '?';
1.1       tholo     870:                        break;
                    871:                }
                    872:                if (a == NULL)
1.16      millert   873:                        FATAL("not enough args in printf(%s)", os);
1.1       tholo     874:                x = execute(a);
                    875:                a = a->nnext;
1.13      kstailey  876:                n = MAXNUMSIZE;
                    877:                if (fmtwd > n)
                    878:                        n = fmtwd;
                    879:                adjbuf(&buf, &bufsize, 1+n+p-buf, recsize, &p, "format");
1.1       tholo     880:                switch (flag) {
1.18      millert   881:                case '?':       sprintf(p, "%s", fmt);  /* unknown, so dump it too */
1.13      kstailey  882:                        t = getsval(x);
                    883:                        n = strlen(t);
                    884:                        if (fmtwd > n)
                    885:                                n = fmtwd;
                    886:                        adjbuf(&buf, &bufsize, 1+strlen(p)+n+p-buf, recsize, &p, "format");
1.5       kstailey  887:                        p += strlen(p);
1.13      kstailey  888:                        sprintf(p, "%s", t);
1.1       tholo     889:                        break;
1.18      millert   890:                case 'f':       sprintf(p, fmt, getfval(x)); break;
                    891:                case 'd':       sprintf(p, fmt, (long) getfval(x)); break;
                    892:                case 'u':       sprintf(p, fmt, (int) getfval(x)); break;
                    893:                case 's':
1.1       tholo     894:                        t = getsval(x);
                    895:                        n = strlen(t);
1.13      kstailey  896:                        if (fmtwd > n)
                    897:                                n = fmtwd;
                    898:                        if (!adjbuf(&buf, &bufsize, 1+n+p-buf, recsize, &p, 0))
1.16      millert   899:                                FATAL("huge string/format (%d chars) in printf %.30s... ran format() out of memory", n, t);
1.13      kstailey  900:                        sprintf(p, fmt, t);
1.1       tholo     901:                        break;
1.18      millert   902:                case 'c':
1.13      kstailey  903:                        if (isnum(x)) {
                    904:                                if (getfval(x))
                    905:                                        sprintf(p, fmt, (int) getfval(x));
1.18      millert   906:                                else {
                    907:                                        *p++ = '\0'; /* explicit null byte */
                    908:                                        *p = '\0';   /* next output will start here */
                    909:                                }
1.13      kstailey  910:                        } else
                    911:                                sprintf(p, fmt, getsval(x)[0]);
1.1       tholo     912:                        break;
1.18      millert   913:                default:
                    914:                        FATAL("can't happen: bad conversion %c in format()", flag);
1.1       tholo     915:                }
                    916:                tempfree(x);
1.5       kstailey  917:                p += strlen(p);
1.1       tholo     918:                s++;
                    919:        }
                    920:        *p = '\0';
1.13      kstailey  921:        free(fmt);
1.1       tholo     922:        for ( ; a; a = a->nnext)                /* evaluate any remaining args */
                    923:                execute(a);
1.13      kstailey  924:        *pbuf = buf;
                    925:        *pbufsize = bufsize;
                    926:        return p - buf;
1.1       tholo     927: }
                    928:
                    929: Cell *awksprintf(Node **a, int n)              /* sprintf(a[0]) */
                    930: {
                    931:        Cell *x;
                    932:        Node *y;
1.13      kstailey  933:        char *buf;
                    934:        int bufsz=3*recsize;
1.1       tholo     935:
1.15      millert   936:        if ((buf = (char *) malloc(bufsz)) == NULL)
1.16      millert   937:                FATAL("out of memory in awksprintf");
1.1       tholo     938:        y = a[0]->nnext;
                    939:        x = execute(a[0]);
1.13      kstailey  940:        if (format(&buf, &bufsz, getsval(x), y) == -1)
1.16      millert   941:                FATAL("sprintf string %.30s... too long.  can't happen.", buf);
1.1       tholo     942:        tempfree(x);
                    943:        x = gettemp();
1.13      kstailey  944:        x->sval = buf;
1.1       tholo     945:        x->tval = STR;
                    946:        return(x);
                    947: }
                    948:
                    949: Cell *awkprintf(Node **a, int n)               /* printf */
                    950: {      /* a[0] is list of args, starting with format string */
                    951:        /* a[1] is redirection operator, a[2] is redirection file */
                    952:        FILE *fp;
                    953:        Cell *x;
                    954:        Node *y;
1.13      kstailey  955:        char *buf;
1.9       kstailey  956:        int len;
1.13      kstailey  957:        int bufsz=3*recsize;
1.1       tholo     958:
1.15      millert   959:        if ((buf = (char *) malloc(bufsz)) == NULL)
1.16      millert   960:                FATAL("out of memory in awkprintf");
1.1       tholo     961:        y = a[0]->nnext;
                    962:        x = execute(a[0]);
1.13      kstailey  963:        if ((len = format(&buf, &bufsz, getsval(x), y)) == -1)
1.16      millert   964:                FATAL("printf string %.30s... too long.  can't happen.", buf);
1.1       tholo     965:        tempfree(x);
                    966:        if (a[1] == NULL) {
1.13      kstailey  967:                /* fputs(buf, stdout); */
1.9       kstailey  968:                fwrite(buf, len, 1, stdout);
1.8       kstailey  969:                if (ferror(stdout))
1.16      millert   970:                        FATAL("write error on stdout");
1.1       tholo     971:        } else {
1.15      millert   972:                fp = redirect(ptoi(a[1]), a[2]);
1.13      kstailey  973:                /* fputs(buf, fp); */
1.9       kstailey  974:                fwrite(buf, len, 1, fp);
1.8       kstailey  975:                fflush(fp);
                    976:                if (ferror(fp))
1.16      millert   977:                        FATAL("write error on %s", filename(fp));
1.1       tholo     978:        }
1.13      kstailey  979:        free(buf);
1.15      millert   980:        return(True);
1.1       tholo     981: }
                    982:
                    983: Cell *arith(Node **a, int n)   /* a[0] + a[1], etc.  also -a[0] */
                    984: {
                    985:        Awkfloat i, j = 0;
                    986:        double v;
                    987:        Cell *x, *y, *z;
                    988:
                    989:        x = execute(a[0]);
                    990:        i = getfval(x);
                    991:        tempfree(x);
                    992:        if (n != UMINUS) {
                    993:                y = execute(a[1]);
                    994:                j = getfval(y);
                    995:                tempfree(y);
                    996:        }
                    997:        z = gettemp();
                    998:        switch (n) {
                    999:        case ADD:
                   1000:                i += j;
                   1001:                break;
                   1002:        case MINUS:
                   1003:                i -= j;
                   1004:                break;
                   1005:        case MULT:
                   1006:                i *= j;
                   1007:                break;
                   1008:        case DIVIDE:
                   1009:                if (j == 0)
1.16      millert  1010:                        FATAL("division by zero");
1.1       tholo    1011:                i /= j;
                   1012:                break;
                   1013:        case MOD:
                   1014:                if (j == 0)
1.16      millert  1015:                        FATAL("division by zero in mod");
1.1       tholo    1016:                modf(i/j, &v);
                   1017:                i = i - j * v;
                   1018:                break;
                   1019:        case UMINUS:
                   1020:                i = -i;
                   1021:                break;
                   1022:        case POWER:
                   1023:                if (j >= 0 && modf(j, &v) == 0.0)       /* pos integer exponent */
1.12      millert  1024:                        i = ipow(i, (int) j);
1.1       tholo    1025:                else
                   1026:                        i = errcheck(pow(i, j), "pow");
                   1027:                break;
                   1028:        default:        /* can't happen */
1.16      millert  1029:                FATAL("illegal arithmetic operator %d", n);
1.1       tholo    1030:        }
                   1031:        setfval(z, i);
                   1032:        return(z);
                   1033: }
                   1034:
                   1035: double ipow(double x, int n)   /* x**n.  ought to be done by pow, but isn't always */
                   1036: {
                   1037:        double v;
                   1038:
                   1039:        if (n <= 0)
                   1040:                return 1;
                   1041:        v = ipow(x, n/2);
                   1042:        if (n % 2 == 0)
                   1043:                return v * v;
                   1044:        else
                   1045:                return x * v * v;
                   1046: }
                   1047:
                   1048: Cell *incrdecr(Node **a, int n)                /* a[0]++, etc. */
                   1049: {
                   1050:        Cell *x, *z;
                   1051:        int k;
                   1052:        Awkfloat xf;
                   1053:
                   1054:        x = execute(a[0]);
                   1055:        xf = getfval(x);
                   1056:        k = (n == PREINCR || n == POSTINCR) ? 1 : -1;
                   1057:        if (n == PREINCR || n == PREDECR) {
                   1058:                setfval(x, xf + k);
                   1059:                return(x);
                   1060:        }
                   1061:        z = gettemp();
                   1062:        setfval(z, xf);
                   1063:        setfval(x, xf + k);
                   1064:        tempfree(x);
                   1065:        return(z);
                   1066: }
                   1067:
                   1068: Cell *assign(Node **a, int n)  /* a[0] = a[1], a[0] += a[1], etc. */
                   1069: {              /* this is subtle; don't muck with it. */
                   1070:        Cell *x, *y;
                   1071:        Awkfloat xf, yf;
                   1072:        double v;
                   1073:
                   1074:        y = execute(a[1]);
                   1075:        x = execute(a[0]);
                   1076:        if (n == ASSIGN) {      /* ordinary assignment */
                   1077:                if (x == y && !(x->tval & (FLD|REC)))   /* self-assignment: */
                   1078:                        ;               /* leave alone unless it's a field */
                   1079:                else if ((y->tval & (STR|NUM)) == (STR|NUM)) {
                   1080:                        setsval(x, getsval(y));
                   1081:                        x->fval = getfval(y);
                   1082:                        x->tval |= NUM;
                   1083:                }
1.13      kstailey 1084:                else if (isstr(y))
1.1       tholo    1085:                        setsval(x, getsval(y));
1.13      kstailey 1086:                else if (isnum(y))
1.1       tholo    1087:                        setfval(x, getfval(y));
                   1088:                else
                   1089:                        funnyvar(y, "read value of");
                   1090:                tempfree(y);
                   1091:                return(x);
                   1092:        }
                   1093:        xf = getfval(x);
                   1094:        yf = getfval(y);
                   1095:        switch (n) {
                   1096:        case ADDEQ:
                   1097:                xf += yf;
                   1098:                break;
                   1099:        case SUBEQ:
                   1100:                xf -= yf;
                   1101:                break;
                   1102:        case MULTEQ:
                   1103:                xf *= yf;
                   1104:                break;
                   1105:        case DIVEQ:
                   1106:                if (yf == 0)
1.16      millert  1107:                        FATAL("division by zero in /=");
1.1       tholo    1108:                xf /= yf;
                   1109:                break;
                   1110:        case MODEQ:
                   1111:                if (yf == 0)
1.16      millert  1112:                        FATAL("division by zero in %%=");
1.1       tholo    1113:                modf(xf/yf, &v);
                   1114:                xf = xf - yf * v;
                   1115:                break;
                   1116:        case POWEQ:
                   1117:                if (yf >= 0 && modf(yf, &v) == 0.0)     /* pos integer exponent */
1.12      millert  1118:                        xf = ipow(xf, (int) yf);
1.1       tholo    1119:                else
                   1120:                        xf = errcheck(pow(xf, yf), "pow");
                   1121:                break;
                   1122:        default:
1.16      millert  1123:                FATAL("illegal assignment operator %d", n);
1.1       tholo    1124:                break;
                   1125:        }
                   1126:        tempfree(y);
                   1127:        setfval(x, xf);
                   1128:        return(x);
                   1129: }
                   1130:
                   1131: Cell *cat(Node **a, int q)     /* a[0] cat a[1] */
                   1132: {
                   1133:        Cell *x, *y, *z;
                   1134:        int n1, n2;
                   1135:        char *s;
                   1136:
                   1137:        x = execute(a[0]);
                   1138:        y = execute(a[1]);
                   1139:        getsval(x);
                   1140:        getsval(y);
                   1141:        n1 = strlen(x->sval);
                   1142:        n2 = strlen(y->sval);
                   1143:        s = (char *) malloc(n1 + n2 + 1);
                   1144:        if (s == NULL)
1.16      millert  1145:                FATAL("out of space concatenating %.15s... and %.15s...",
                   1146:                        x->sval, y->sval);
1.1       tholo    1147:        strcpy(s, x->sval);
                   1148:        strcpy(s+n1, y->sval);
                   1149:        tempfree(y);
                   1150:        z = gettemp();
                   1151:        z->sval = s;
                   1152:        z->tval = STR;
                   1153:        tempfree(x);
                   1154:        return(z);
                   1155: }
                   1156:
                   1157: Cell *pastat(Node **a, int n)  /* a[0] { a[1] } */
                   1158: {
                   1159:        Cell *x;
                   1160:
                   1161:        if (a[0] == 0)
                   1162:                x = execute(a[1]);
                   1163:        else {
                   1164:                x = execute(a[0]);
                   1165:                if (istrue(x)) {
                   1166:                        tempfree(x);
                   1167:                        x = execute(a[1]);
                   1168:                }
                   1169:        }
                   1170:        return x;
                   1171: }
                   1172:
                   1173: Cell *dopa2(Node **a, int n)   /* a[0], a[1] { a[2] } */
                   1174: {
                   1175:        Cell *x;
                   1176:        int pair;
                   1177:
1.15      millert  1178:        pair = ptoi(a[3]);
1.1       tholo    1179:        if (pairstack[pair] == 0) {
                   1180:                x = execute(a[0]);
                   1181:                if (istrue(x))
                   1182:                        pairstack[pair] = 1;
                   1183:                tempfree(x);
                   1184:        }
                   1185:        if (pairstack[pair] == 1) {
                   1186:                x = execute(a[1]);
                   1187:                if (istrue(x))
                   1188:                        pairstack[pair] = 0;
                   1189:                tempfree(x);
                   1190:                x = execute(a[2]);
                   1191:                return(x);
                   1192:        }
1.15      millert  1193:        return(False);
1.1       tholo    1194: }
                   1195:
                   1196: Cell *split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */
                   1197: {
                   1198:        Cell *x = 0, *y, *ap;
                   1199:        char *s;
                   1200:        int sep;
1.13      kstailey 1201:        char *t, temp, num[50], *fs = 0;
1.15      millert  1202:        int n, tempstat, arg3type;
1.1       tholo    1203:
                   1204:        y = execute(a[0]);      /* source string */
                   1205:        s = getsval(y);
1.15      millert  1206:        arg3type = ptoi(a[3]);
1.1       tholo    1207:        if (a[2] == 0)          /* fs string */
                   1208:                fs = *FS;
1.15      millert  1209:        else if (arg3type == STRING) {  /* split(str,arr,"string") */
1.1       tholo    1210:                x = execute(a[2]);
                   1211:                fs = getsval(x);
1.15      millert  1212:        } else if (arg3type == REGEXPR)
1.13      kstailey 1213:                fs = "(regexpr)";       /* split(str,arr,/regexpr/) */
1.1       tholo    1214:        else
1.16      millert  1215:                FATAL("illegal type of split");
1.1       tholo    1216:        sep = *fs;
                   1217:        ap = execute(a[1]);     /* array name */
                   1218:        freesymtab(ap);
1.18      millert  1219:           dprintf( ("split: s=|%s|, a=%s, sep=|%s|\n", s, NN(ap->nval), fs) );
1.1       tholo    1220:        ap->tval &= ~STR;
                   1221:        ap->tval |= ARR;
                   1222:        ap->sval = (char *) makesymtab(NSYMTAB);
                   1223:
                   1224:        n = 0;
1.15      millert  1225:        if ((*s != '\0' && strlen(fs) > 1) || arg3type == REGEXPR) {    /* reg expr */
1.1       tholo    1226:                fa *pfa;
1.15      millert  1227:                if (arg3type == REGEXPR) {      /* it's ready already */
1.1       tholo    1228:                        pfa = (fa *) a[2];
                   1229:                } else {
                   1230:                        pfa = makedfa(fs, 1);
                   1231:                }
                   1232:                if (nematch(pfa,s)) {
                   1233:                        tempstat = pfa->initstat;
                   1234:                        pfa->initstat = 2;
                   1235:                        do {
                   1236:                                n++;
1.19      deraadt  1237:                                snprintf(num, sizeof num, "%d", n);
1.1       tholo    1238:                                temp = *patbeg;
                   1239:                                *patbeg = '\0';
1.14      millert  1240:                                if (is_number(s))
1.13      kstailey 1241:                                        setsymtab(num, s, atof(s), STR|NUM, (Array *) ap->sval);
1.1       tholo    1242:                                else
                   1243:                                        setsymtab(num, s, 0.0, STR, (Array *) ap->sval);
                   1244:                                *patbeg = temp;
                   1245:                                s = patbeg + patlen;
                   1246:                                if (*(patbeg+patlen-1) == 0 || *s == 0) {
                   1247:                                        n++;
1.19      deraadt  1248:                                        snprintf(num, sizeof num, "%d", n);
1.1       tholo    1249:                                        setsymtab(num, "", 0.0, STR, (Array *) ap->sval);
                   1250:                                        pfa->initstat = tempstat;
                   1251:                                        goto spdone;
                   1252:                                }
                   1253:                        } while (nematch(pfa,s));
                   1254:                }
                   1255:                n++;
1.19      deraadt  1256:                snprintf(num, sizeof num, "%d", n);
1.14      millert  1257:                if (is_number(s))
1.13      kstailey 1258:                        setsymtab(num, s, atof(s), STR|NUM, (Array *) ap->sval);
1.1       tholo    1259:                else
                   1260:                        setsymtab(num, s, 0.0, STR, (Array *) ap->sval);
                   1261:   spdone:
                   1262:                pfa = NULL;
                   1263:        } else if (sep == ' ') {
                   1264:                for (n = 0; ; ) {
                   1265:                        while (*s == ' ' || *s == '\t' || *s == '\n')
                   1266:                                s++;
                   1267:                        if (*s == 0)
                   1268:                                break;
                   1269:                        n++;
                   1270:                        t = s;
                   1271:                        do
                   1272:                                s++;
                   1273:                        while (*s!=' ' && *s!='\t' && *s!='\n' && *s!='\0');
                   1274:                        temp = *s;
                   1275:                        *s = '\0';
1.19      deraadt  1276:                        snprintf(num, sizeof num, "%d", n);
1.14      millert  1277:                        if (is_number(t))
1.13      kstailey 1278:                                setsymtab(num, t, atof(t), STR|NUM, (Array *) ap->sval);
1.1       tholo    1279:                        else
                   1280:                                setsymtab(num, t, 0.0, STR, (Array *) ap->sval);
                   1281:                        *s = temp;
                   1282:                        if (*s != 0)
                   1283:                                s++;
                   1284:                }
                   1285:        } else if (sep == 0) {  /* new: split(s, a, "") => 1 char/elem */
                   1286:                for (n = 0; *s != 0; s++) {
                   1287:                        char buf[2];
                   1288:                        n++;
1.19      deraadt  1289:                        snprintf(num, sizeof num, "%d", n);
1.1       tholo    1290:                        buf[0] = *s;
                   1291:                        buf[1] = 0;
1.17      millert  1292:                        if (isdigit((uschar)buf[0]))
1.1       tholo    1293:                                setsymtab(num, buf, atof(buf), STR|NUM, (Array *) ap->sval);
                   1294:                        else
                   1295:                                setsymtab(num, buf, 0.0, STR, (Array *) ap->sval);
                   1296:                }
                   1297:        } else if (*s != 0) {
                   1298:                for (;;) {
                   1299:                        n++;
                   1300:                        t = s;
                   1301:                        while (*s != sep && *s != '\n' && *s != '\0')
                   1302:                                s++;
                   1303:                        temp = *s;
                   1304:                        *s = '\0';
1.19      deraadt  1305:                        snprintf(num, sizeof num, "%d", n);
1.14      millert  1306:                        if (is_number(t))
1.13      kstailey 1307:                                setsymtab(num, t, atof(t), STR|NUM, (Array *) ap->sval);
1.1       tholo    1308:                        else
                   1309:                                setsymtab(num, t, 0.0, STR, (Array *) ap->sval);
                   1310:                        *s = temp;
                   1311:                        if (*s++ == 0)
                   1312:                                break;
                   1313:                }
                   1314:        }
                   1315:        tempfree(ap);
                   1316:        tempfree(y);
1.17      millert  1317:        if (a[2] != 0 && arg3type == STRING) {
1.1       tholo    1318:                tempfree(x);
1.17      millert  1319:        }
1.1       tholo    1320:        x = gettemp();
                   1321:        x->tval = NUM;
                   1322:        x->fval = n;
                   1323:        return(x);
                   1324: }
                   1325:
                   1326: Cell *condexpr(Node **a, int n)        /* a[0] ? a[1] : a[2] */
                   1327: {
                   1328:        Cell *x;
                   1329:
                   1330:        x = execute(a[0]);
                   1331:        if (istrue(x)) {
                   1332:                tempfree(x);
                   1333:                x = execute(a[1]);
                   1334:        } else {
                   1335:                tempfree(x);
                   1336:                x = execute(a[2]);
                   1337:        }
                   1338:        return(x);
                   1339: }
                   1340:
                   1341: Cell *ifstat(Node **a, int n)  /* if (a[0]) a[1]; else a[2] */
                   1342: {
                   1343:        Cell *x;
                   1344:
                   1345:        x = execute(a[0]);
                   1346:        if (istrue(x)) {
                   1347:                tempfree(x);
                   1348:                x = execute(a[1]);
                   1349:        } else if (a[2] != 0) {
                   1350:                tempfree(x);
                   1351:                x = execute(a[2]);
                   1352:        }
                   1353:        return(x);
                   1354: }
                   1355:
                   1356: Cell *whilestat(Node **a, int n)       /* while (a[0]) a[1] */
                   1357: {
                   1358:        Cell *x;
                   1359:
                   1360:        for (;;) {
                   1361:                x = execute(a[0]);
                   1362:                if (!istrue(x))
                   1363:                        return(x);
                   1364:                tempfree(x);
                   1365:                x = execute(a[1]);
                   1366:                if (isbreak(x)) {
1.15      millert  1367:                        x = True;
1.1       tholo    1368:                        return(x);
                   1369:                }
                   1370:                if (isnext(x) || isexit(x) || isret(x))
                   1371:                        return(x);
                   1372:                tempfree(x);
                   1373:        }
                   1374: }
                   1375:
                   1376: Cell *dostat(Node **a, int n)  /* do a[0]; while(a[1]) */
                   1377: {
                   1378:        Cell *x;
                   1379:
                   1380:        for (;;) {
                   1381:                x = execute(a[0]);
                   1382:                if (isbreak(x))
1.15      millert  1383:                        return True;
1.17      millert  1384:                if (isnext(x) || isexit(x) || isret(x))
1.1       tholo    1385:                        return(x);
                   1386:                tempfree(x);
                   1387:                x = execute(a[1]);
                   1388:                if (!istrue(x))
                   1389:                        return(x);
                   1390:                tempfree(x);
                   1391:        }
                   1392: }
                   1393:
                   1394: Cell *forstat(Node **a, int n) /* for (a[0]; a[1]; a[2]) a[3] */
                   1395: {
                   1396:        Cell *x;
                   1397:
                   1398:        x = execute(a[0]);
                   1399:        tempfree(x);
                   1400:        for (;;) {
                   1401:                if (a[1]!=0) {
                   1402:                        x = execute(a[1]);
                   1403:                        if (!istrue(x)) return(x);
                   1404:                        else tempfree(x);
                   1405:                }
                   1406:                x = execute(a[3]);
                   1407:                if (isbreak(x))         /* turn off break */
1.15      millert  1408:                        return True;
1.1       tholo    1409:                if (isnext(x) || isexit(x) || isret(x))
                   1410:                        return(x);
                   1411:                tempfree(x);
                   1412:                x = execute(a[2]);
                   1413:                tempfree(x);
                   1414:        }
                   1415: }
                   1416:
                   1417: Cell *instat(Node **a, int n)  /* for (a[0] in a[1]) a[2] */
                   1418: {
                   1419:        Cell *x, *vp, *arrayp, *cp, *ncp;
                   1420:        Array *tp;
                   1421:        int i;
                   1422:
                   1423:        vp = execute(a[0]);
                   1424:        arrayp = execute(a[1]);
                   1425:        if (!isarr(arrayp)) {
1.15      millert  1426:                return True;
1.1       tholo    1427:        }
                   1428:        tp = (Array *) arrayp->sval;
                   1429:        tempfree(arrayp);
                   1430:        for (i = 0; i < tp->size; i++) {        /* this routine knows too much */
                   1431:                for (cp = tp->tab[i]; cp != NULL; cp = ncp) {
                   1432:                        setsval(vp, cp->nval);
                   1433:                        ncp = cp->cnext;
                   1434:                        x = execute(a[2]);
                   1435:                        if (isbreak(x)) {
                   1436:                                tempfree(vp);
1.15      millert  1437:                                return True;
1.1       tholo    1438:                        }
                   1439:                        if (isnext(x) || isexit(x) || isret(x)) {
                   1440:                                tempfree(vp);
                   1441:                                return(x);
                   1442:                        }
                   1443:                        tempfree(x);
                   1444:                }
                   1445:        }
1.15      millert  1446:        return True;
1.1       tholo    1447: }
                   1448:
                   1449: Cell *bltin(Node **a, int n)   /* builtin functions. a[0] is type, a[1] is arg list */
                   1450: {
                   1451:        Cell *x, *y;
                   1452:        Awkfloat u;
                   1453:        int t;
1.13      kstailey 1454:        char *p, *buf;
1.1       tholo    1455:        Node *nextarg;
                   1456:        FILE *fp;
1.18      millert  1457:        void flush_all(void);
1.1       tholo    1458:
1.15      millert  1459:        t = ptoi(a[0]);
1.1       tholo    1460:        x = execute(a[1]);
                   1461:        nextarg = a[1]->nnext;
                   1462:        switch (t) {
                   1463:        case FLENGTH:
1.18      millert  1464:                if (isarr(x))
                   1465:                        u = ((Array *) x->sval)->nelem; /* GROT.  should be function*/
                   1466:                else
                   1467:                        u = strlen(getsval(x));
                   1468:                break;
1.1       tholo    1469:        case FLOG:
                   1470:                u = errcheck(log(getfval(x)), "log"); break;
                   1471:        case FINT:
                   1472:                modf(getfval(x), &u); break;
                   1473:        case FEXP:
                   1474:                u = errcheck(exp(getfval(x)), "exp"); break;
                   1475:        case FSQRT:
                   1476:                u = errcheck(sqrt(getfval(x)), "sqrt"); break;
                   1477:        case FSIN:
                   1478:                u = sin(getfval(x)); break;
                   1479:        case FCOS:
                   1480:                u = cos(getfval(x)); break;
                   1481:        case FATAN:
                   1482:                if (nextarg == 0) {
1.16      millert  1483:                        WARNING("atan2 requires two arguments; returning 1.0");
1.1       tholo    1484:                        u = 1.0;
                   1485:                } else {
                   1486:                        y = execute(a[1]->nnext);
                   1487:                        u = atan2(getfval(x), getfval(y));
                   1488:                        tempfree(y);
                   1489:                        nextarg = nextarg->nnext;
                   1490:                }
                   1491:                break;
                   1492:        case FSYSTEM:
                   1493:                fflush(stdout);         /* in case something is buffered already */
1.13      kstailey 1494:                u = (Awkfloat) system(getsval(x)) / 256;   /* 256 is unix-dep */
1.1       tholo    1495:                break;
                   1496:        case FRAND:
                   1497:                /* in principle, rand() returns something in 0..RAND_MAX */
                   1498:                u = (Awkfloat) (rand() % RAND_MAX) / RAND_MAX;
                   1499:                break;
                   1500:        case FSRAND:
1.13      kstailey 1501:                if (isrec(x))   /* no argument provided */
1.1       tholo    1502:                        u = time((time_t *)0);
                   1503:                else
                   1504:                        u = getfval(x);
1.14      millert  1505:                srand((unsigned int) u);
1.1       tholo    1506:                break;
                   1507:        case FTOUPPER:
                   1508:        case FTOLOWER:
1.13      kstailey 1509:                buf = tostring(getsval(x));
1.1       tholo    1510:                if (t == FTOUPPER) {
                   1511:                        for (p = buf; *p; p++)
1.17      millert  1512:                                if (islower((uschar) *p))
1.1       tholo    1513:                                        *p = toupper(*p);
                   1514:                } else {
                   1515:                        for (p = buf; *p; p++)
1.17      millert  1516:                                if (isupper((uschar) *p))
1.1       tholo    1517:                                        *p = tolower(*p);
                   1518:                }
                   1519:                tempfree(x);
                   1520:                x = gettemp();
                   1521:                setsval(x, buf);
1.13      kstailey 1522:                free(buf);
1.1       tholo    1523:                return x;
                   1524:        case FFLUSH:
1.18      millert  1525:                if (isrec(x) || strlen(getsval(x)) == 0) {
                   1526:                        flush_all();    /* fflush() or fflush("") -> all */
                   1527:                        u = 0;
                   1528:                } else if ((fp = openfile(FFLUSH, getsval(x))) == NULL)
1.1       tholo    1529:                        u = EOF;
                   1530:                else
                   1531:                        u = fflush(fp);
                   1532:                break;
                   1533:        default:        /* can't happen */
1.16      millert  1534:                FATAL("illegal function type %d", t);
1.1       tholo    1535:                break;
                   1536:        }
                   1537:        tempfree(x);
                   1538:        x = gettemp();
                   1539:        setfval(x, u);
                   1540:        if (nextarg != 0) {
1.16      millert  1541:                WARNING("warning: function has too many arguments");
1.1       tholo    1542:                for ( ; nextarg; nextarg = nextarg->nnext)
                   1543:                        execute(nextarg);
                   1544:        }
                   1545:        return(x);
                   1546: }
                   1547:
                   1548: Cell *printstat(Node **a, int n)       /* print a[0] */
                   1549: {
                   1550:        Node *x;
                   1551:        Cell *y;
                   1552:        FILE *fp;
                   1553:
                   1554:        if (a[1] == 0)  /* a[1] is redirection operator, a[2] is file */
                   1555:                fp = stdout;
                   1556:        else
1.15      millert  1557:                fp = redirect(ptoi(a[1]), a[2]);
1.1       tholo    1558:        for (x = a[0]; x != NULL; x = x->nnext) {
                   1559:                y = execute(x);
1.18      millert  1560:                fputs(getpssval(y), fp);
1.1       tholo    1561:                tempfree(y);
                   1562:                if (x->nnext == NULL)
1.13      kstailey 1563:                        fputs(*ORS, fp);
1.1       tholo    1564:                else
1.13      kstailey 1565:                        fputs(*OFS, fp);
1.1       tholo    1566:        }
                   1567:        if (a[1] != 0)
                   1568:                fflush(fp);
                   1569:        if (ferror(fp))
1.16      millert  1570:                FATAL("write error on %s", filename(fp));
1.15      millert  1571:        return(True);
1.1       tholo    1572: }
                   1573:
                   1574: Cell *nullproc(Node **a, int n)
                   1575: {
1.15      millert  1576:        n = n;
                   1577:        a = a;
1.1       tholo    1578:        return 0;
                   1579: }
                   1580:
                   1581:
                   1582: FILE *redirect(int a, Node *b) /* set up all i/o redirections */
                   1583: {
                   1584:        FILE *fp;
                   1585:        Cell *x;
                   1586:        char *fname;
                   1587:
                   1588:        x = execute(b);
                   1589:        fname = getsval(x);
                   1590:        fp = openfile(a, fname);
                   1591:        if (fp == NULL)
1.16      millert  1592:                FATAL("can't open file %s", fname);
1.1       tholo    1593:        tempfree(x);
                   1594:        return fp;
                   1595: }
                   1596:
                   1597: struct files {
                   1598:        FILE    *fp;
1.18      millert  1599:        const char      *fname;
1.1       tholo    1600:        int     mode;   /* '|', 'a', 'w' => LE/LT, GT */
                   1601: } files[FOPEN_MAX] ={
1.16      millert  1602:        { NULL,  "/dev/stdin",  LT },   /* watch out: don't free this! */
                   1603:        { NULL, "/dev/stdout", GT },
                   1604:        { NULL, "/dev/stderr", GT }
1.1       tholo    1605: };
                   1606:
1.16      millert  1607: void stdinit(void)     /* in case stdin, etc., are not constants */
                   1608: {
                   1609:        files[0].fp = stdin;
                   1610:        files[1].fp = stdout;
                   1611:        files[2].fp = stderr;
                   1612: }
                   1613:
1.18      millert  1614: FILE *openfile(int a, const char *us)
1.1       tholo    1615: {
1.18      millert  1616:        const char *s = us;
1.1       tholo    1617:        int i, m;
                   1618:        FILE *fp = 0;
                   1619:
                   1620:        if (*s == '\0')
1.16      millert  1621:                FATAL("null file name in print or getline");
1.1       tholo    1622:        for (i=0; i < FOPEN_MAX; i++)
1.13      kstailey 1623:                if (files[i].fname && strcmp(s, files[i].fname) == 0) {
1.1       tholo    1624:                        if (a == files[i].mode || (a==APPEND && files[i].mode==GT))
                   1625:                                return files[i].fp;
1.13      kstailey 1626:                        if (a == FFLUSH)
                   1627:                                return files[i].fp;
                   1628:                }
                   1629:        if (a == FFLUSH)        /* didn't find it, so don't create it! */
                   1630:                return NULL;
                   1631:
1.1       tholo    1632:        for (i=0; i < FOPEN_MAX; i++)
                   1633:                if (files[i].fp == 0)
                   1634:                        break;
                   1635:        if (i >= FOPEN_MAX)
1.16      millert  1636:                FATAL("%s makes too many open files", s);
1.1       tholo    1637:        fflush(stdout); /* force a semblance of order */
                   1638:        m = a;
                   1639:        if (a == GT) {
                   1640:                fp = fopen(s, "w");
                   1641:        } else if (a == APPEND) {
                   1642:                fp = fopen(s, "a");
                   1643:                m = GT; /* so can mix > and >> */
                   1644:        } else if (a == '|') {  /* output pipe */
                   1645:                fp = popen(s, "w");
                   1646:        } else if (a == LE) {   /* input pipe */
                   1647:                fp = popen(s, "r");
                   1648:        } else if (a == LT) {   /* getline <file */
                   1649:                fp = strcmp(s, "-") == 0 ? stdin : fopen(s, "r");       /* "-" is stdin */
                   1650:        } else  /* can't happen */
1.16      millert  1651:                FATAL("illegal redirection %d", a);
1.1       tholo    1652:        if (fp != NULL) {
                   1653:                files[i].fname = tostring(s);
                   1654:                files[i].fp = fp;
                   1655:                files[i].mode = m;
                   1656:        }
                   1657:        return fp;
                   1658: }
                   1659:
1.18      millert  1660: const char *filename(FILE *fp)
1.1       tholo    1661: {
                   1662:        int i;
                   1663:
                   1664:        for (i = 0; i < FOPEN_MAX; i++)
                   1665:                if (fp == files[i].fp)
                   1666:                        return files[i].fname;
                   1667:        return "???";
                   1668: }
                   1669:
                   1670: Cell *closefile(Node **a, int n)
                   1671: {
                   1672:        Cell *x;
                   1673:        int i, stat;
                   1674:
1.15      millert  1675:        n = n;
1.1       tholo    1676:        x = execute(a[0]);
                   1677:        getsval(x);
1.17      millert  1678:        stat = -1;
                   1679:        for (i = 0; i < FOPEN_MAX; i++) {
1.1       tholo    1680:                if (files[i].fname && strcmp(x->sval, files[i].fname) == 0) {
                   1681:                        if (ferror(files[i].fp))
1.16      millert  1682:                                WARNING( "i/o error occurred on %s", files[i].fname );
1.1       tholo    1683:                        if (files[i].mode == '|' || files[i].mode == LE)
                   1684:                                stat = pclose(files[i].fp);
                   1685:                        else
                   1686:                                stat = fclose(files[i].fp);
                   1687:                        if (stat == EOF)
1.16      millert  1688:                                WARNING( "i/o error occurred closing %s", files[i].fname );
1.1       tholo    1689:                        if (i > 2)      /* don't do /dev/std... */
                   1690:                                xfree(files[i].fname);
                   1691:                        files[i].fname = NULL;  /* watch out for ref thru this */
                   1692:                        files[i].fp = NULL;
                   1693:                }
1.17      millert  1694:        }
1.1       tholo    1695:        tempfree(x);
1.17      millert  1696:        x = gettemp();
                   1697:        setfval(x, (Awkfloat) stat);
                   1698:        return(x);
1.1       tholo    1699: }
                   1700:
                   1701: void closeall(void)
                   1702: {
                   1703:        int i, stat;
                   1704:
1.17      millert  1705:        for (i = 0; i < FOPEN_MAX; i++) {
1.1       tholo    1706:                if (files[i].fp) {
                   1707:                        if (ferror(files[i].fp))
1.16      millert  1708:                                WARNING( "i/o error occurred on %s", files[i].fname );
1.1       tholo    1709:                        if (files[i].mode == '|' || files[i].mode == LE)
                   1710:                                stat = pclose(files[i].fp);
                   1711:                        else
                   1712:                                stat = fclose(files[i].fp);
                   1713:                        if (stat == EOF)
1.16      millert  1714:                                WARNING( "i/o error occurred while closing %s", files[i].fname );
1.1       tholo    1715:                }
1.17      millert  1716:        }
1.18      millert  1717: }
                   1718:
                   1719: void flush_all(void)
                   1720: {
                   1721:        int i;
                   1722:
                   1723:        for (i = 0; i < FOPEN_MAX; i++)
                   1724:                if (files[i].fp)
                   1725:                        fflush(files[i].fp);
1.1       tholo    1726: }
                   1727:
1.13      kstailey 1728: void backsub(char **pb_ptr, char **sptr_ptr);
1.1       tholo    1729:
                   1730: Cell *sub(Node **a, int nnn)   /* substitute command */
                   1731: {
                   1732:        char *sptr, *pb, *q;
                   1733:        Cell *x, *y, *result;
1.13      kstailey 1734:        char *t, *buf;
1.1       tholo    1735:        fa *pfa;
1.13      kstailey 1736:        int bufsz = recsize;
1.1       tholo    1737:
1.15      millert  1738:        if ((buf = (char *) malloc(bufsz)) == NULL)
1.16      millert  1739:                FATAL("out of memory in sub");
1.1       tholo    1740:        x = execute(a[3]);      /* target string */
                   1741:        t = getsval(x);
                   1742:        if (a[0] == 0)          /* 0 => a[1] is already-compiled regexpr */
                   1743:                pfa = (fa *) a[1];      /* regular expression */
                   1744:        else {
                   1745:                y = execute(a[1]);
                   1746:                pfa = makedfa(getsval(y), 1);
                   1747:                tempfree(y);
                   1748:        }
                   1749:        y = execute(a[2]);      /* replacement string */
1.15      millert  1750:        result = False;
1.1       tholo    1751:        if (pmatch(pfa, t)) {
1.13      kstailey 1752:                sptr = t;
                   1753:                adjbuf(&buf, &bufsz, 1+patbeg-sptr, recsize, 0, "sub");
1.1       tholo    1754:                pb = buf;
                   1755:                while (sptr < patbeg)
                   1756:                        *pb++ = *sptr++;
                   1757:                sptr = getsval(y);
1.13      kstailey 1758:                while (*sptr != 0) {
                   1759:                        adjbuf(&buf, &bufsz, 5+pb-buf, recsize, &pb, "sub");
                   1760:                        if (*sptr == '\\') {
                   1761:                                backsub(&pb, &sptr);
1.1       tholo    1762:                        } else if (*sptr == '&') {
                   1763:                                sptr++;
1.13      kstailey 1764:                                adjbuf(&buf, &bufsz, 1+patlen+pb-buf, recsize, &pb, "sub");
1.1       tholo    1765:                                for (q = patbeg; q < patbeg+patlen; )
                   1766:                                        *pb++ = *q++;
                   1767:                        } else
                   1768:                                *pb++ = *sptr++;
1.13      kstailey 1769:                }
1.1       tholo    1770:                *pb = '\0';
1.13      kstailey 1771:                if (pb > buf + bufsz)
1.16      millert  1772:                        FATAL("sub result1 %.30s too big; can't happen", buf);
1.1       tholo    1773:                sptr = patbeg + patlen;
1.13      kstailey 1774:                if ((patlen == 0 && *patbeg) || (patlen && *(sptr-1))) {
                   1775:                        adjbuf(&buf, &bufsz, 1+strlen(sptr)+pb-buf, 0, &pb, "sub");
1.1       tholo    1776:                        while ((*pb++ = *sptr++) != 0)
                   1777:                                ;
1.13      kstailey 1778:                }
                   1779:                if (pb > buf + bufsz)
1.16      millert  1780:                        FATAL("sub result2 %.30s too big; can't happen", buf);
1.13      kstailey 1781:                setsval(x, buf);        /* BUG: should be able to avoid copy */
1.15      millert  1782:                result = True;;
1.1       tholo    1783:        }
                   1784:        tempfree(x);
                   1785:        tempfree(y);
1.13      kstailey 1786:        free(buf);
1.1       tholo    1787:        return result;
                   1788: }
                   1789:
                   1790: Cell *gsub(Node **a, int nnn)  /* global substitute */
                   1791: {
                   1792:        Cell *x, *y;
1.13      kstailey 1793:        char *rptr, *sptr, *t, *pb, *q;
                   1794:        char *buf;
1.1       tholo    1795:        fa *pfa;
                   1796:        int mflag, tempstat, num;
1.13      kstailey 1797:        int bufsz = recsize;
1.1       tholo    1798:
1.15      millert  1799:        if ((buf = (char *) malloc(bufsz)) == NULL)
1.16      millert  1800:                FATAL("out of memory in gsub");
1.1       tholo    1801:        mflag = 0;      /* if mflag == 0, can replace empty string */
                   1802:        num = 0;
                   1803:        x = execute(a[3]);      /* target string */
                   1804:        t = getsval(x);
                   1805:        if (a[0] == 0)          /* 0 => a[1] is already-compiled regexpr */
                   1806:                pfa = (fa *) a[1];      /* regular expression */
                   1807:        else {
                   1808:                y = execute(a[1]);
                   1809:                pfa = makedfa(getsval(y), 1);
                   1810:                tempfree(y);
                   1811:        }
                   1812:        y = execute(a[2]);      /* replacement string */
                   1813:        if (pmatch(pfa, t)) {
                   1814:                tempstat = pfa->initstat;
                   1815:                pfa->initstat = 2;
                   1816:                pb = buf;
                   1817:                rptr = getsval(y);
                   1818:                do {
                   1819:                        if (patlen == 0 && *patbeg != 0) {      /* matched empty string */
                   1820:                                if (mflag == 0) {       /* can replace empty */
                   1821:                                        num++;
                   1822:                                        sptr = rptr;
1.13      kstailey 1823:                                        while (*sptr != 0) {
                   1824:                                                adjbuf(&buf, &bufsz, 5+pb-buf, recsize, &pb, "gsub");
                   1825:                                                if (*sptr == '\\') {
                   1826:                                                        backsub(&pb, &sptr);
1.1       tholo    1827:                                                } else if (*sptr == '&') {
                   1828:                                                        sptr++;
1.13      kstailey 1829:                                                        adjbuf(&buf, &bufsz, 1+patlen+pb-buf, recsize, &pb, "gsub");
1.1       tholo    1830:                                                        for (q = patbeg; q < patbeg+patlen; )
                   1831:                                                                *pb++ = *q++;
                   1832:                                                } else
                   1833:                                                        *pb++ = *sptr++;
1.13      kstailey 1834:                                        }
1.1       tholo    1835:                                }
                   1836:                                if (*t == 0)    /* at end */
                   1837:                                        goto done;
1.13      kstailey 1838:                                adjbuf(&buf, &bufsz, 2+pb-buf, recsize, &pb, "gsub");
1.1       tholo    1839:                                *pb++ = *t++;
1.13      kstailey 1840:                                if (pb > buf + bufsz)   /* BUG: not sure of this test */
1.16      millert  1841:                                        FATAL("gsub result0 %.30s too big; can't happen", buf);
1.1       tholo    1842:                                mflag = 0;
                   1843:                        }
                   1844:                        else {  /* matched nonempty string */
                   1845:                                num++;
                   1846:                                sptr = t;
1.13      kstailey 1847:                                adjbuf(&buf, &bufsz, 1+(patbeg-sptr)+pb-buf, recsize, &pb, "gsub");
                   1848:                                while (sptr < patbeg)
1.1       tholo    1849:                                        *pb++ = *sptr++;
                   1850:                                sptr = rptr;
1.13      kstailey 1851:                                while (*sptr != 0) {
                   1852:                                        adjbuf(&buf, &bufsz, 5+pb-buf, recsize, &pb, "gsub");
                   1853:                                        if (*sptr == '\\') {
                   1854:                                                backsub(&pb, &sptr);
1.1       tholo    1855:                                        } else if (*sptr == '&') {
                   1856:                                                sptr++;
1.13      kstailey 1857:                                                adjbuf(&buf, &bufsz, 1+patlen+pb-buf, recsize, &pb, "gsub");
1.1       tholo    1858:                                                for (q = patbeg; q < patbeg+patlen; )
                   1859:                                                        *pb++ = *q++;
                   1860:                                        } else
                   1861:                                                *pb++ = *sptr++;
1.13      kstailey 1862:                                }
1.1       tholo    1863:                                t = patbeg + patlen;
                   1864:                                if (patlen == 0 || *t == 0 || *(t-1) == 0)
                   1865:                                        goto done;
1.13      kstailey 1866:                                if (pb > buf + bufsz)
1.16      millert  1867:                                        FATAL("gsub result1 %.30s too big; can't happen", buf);
1.1       tholo    1868:                                mflag = 1;
                   1869:                        }
                   1870:                } while (pmatch(pfa,t));
                   1871:                sptr = t;
1.13      kstailey 1872:                adjbuf(&buf, &bufsz, 1+strlen(sptr)+pb-buf, 0, &pb, "gsub");
1.1       tholo    1873:                while ((*pb++ = *sptr++) != 0)
                   1874:                        ;
1.13      kstailey 1875:        done:   if (pb > buf + bufsz)
1.16      millert  1876:                        FATAL("gsub result2 %.30s too big; can't happen", buf);
1.1       tholo    1877:                *pb = '\0';
1.13      kstailey 1878:                setsval(x, buf);        /* BUG: should be able to avoid copy + free */
1.1       tholo    1879:                pfa->initstat = tempstat;
                   1880:        }
                   1881:        tempfree(x);
                   1882:        tempfree(y);
                   1883:        x = gettemp();
                   1884:        x->tval = NUM;
                   1885:        x->fval = num;
1.13      kstailey 1886:        free(buf);
1.1       tholo    1887:        return(x);
1.13      kstailey 1888: }
                   1889:
                   1890: void backsub(char **pb_ptr, char **sptr_ptr)   /* handle \\& variations */
                   1891: {                                              /* sptr[0] == '\\' */
                   1892:        char *pb = *pb_ptr, *sptr = *sptr_ptr;
                   1893:
                   1894:        if (sptr[1] == '\\') {
                   1895:                if (sptr[2] == '\\' && sptr[3] == '&') { /* \\\& -> \& */
                   1896:                        *pb++ = '\\';
                   1897:                        *pb++ = '&';
                   1898:                        sptr += 4;
                   1899:                } else if (sptr[2] == '&') {    /* \\& -> \ + matched */
                   1900:                        *pb++ = '\\';
                   1901:                        sptr += 2;
                   1902:                } else {                        /* \\x -> \\x */
                   1903:                        *pb++ = *sptr++;
                   1904:                        *pb++ = *sptr++;
                   1905:                }
                   1906:        } else if (sptr[1] == '&') {    /* literal & */
                   1907:                sptr++;
                   1908:                *pb++ = *sptr++;
                   1909:        } else                          /* literal \ */
                   1910:                *pb++ = *sptr++;
                   1911:
                   1912:        *pb_ptr = pb;
                   1913:        *sptr_ptr = sptr;
1.1       tholo    1914: }