run.c (66979B)
1 /* *************************************************************** 2 * copyright (c) lucent technologies 1997 3 * all rights reserved 4 * 5 * permission to use, copy, modify, and distribute this software and 6 * its documentation for any purpose and without fee is hereby 7 * granted, provided that the above copyright notice appear in all 8 * copies and that both that the copyright notice and this 9 * permission notice and warranty disclaimer appear in supporting 10 * documentation, and that the name lucent technologies or any of 11 * its entities not be used in advertising or publicity pertaining 12 * to distribution of the software without specific, written prior 13 * permission 14 * 15 * LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 17 * IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY 18 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER 20 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, 21 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF 22 * THIS SOFTWARE 23 * ************************************************************** */ 24 25 #ifdef __GNUC__ 26 #pragma GCC diagnostic ignored "-Wunused-parameter" 27 #endif 28 29 #define DEBUG 30 #if FEATURE_AWK_RANDOM 31 #ifndef _DEFAULT_SOURCE 32 #define _DEFAULT_SOURCE 33 #endif 34 #endif 35 #include "awk.h" 36 #include "awkgram.tab.h" 37 #include "wexec.h" 38 39 #include <ctype.h> 40 #include <fcntl.h> 41 #include <limits.h> 42 #include <math.h> 43 #include <setjmp.h> 44 #include <stdio.h> 45 #include <stdlib.h> 46 #include <string.h> 47 #include <sys/stat.h> 48 #include <sys/types.h> 49 #include <sys/wait.h> 50 #include <time.h> 51 #include <wctype.h> 52 53 static void stdinit(void); 54 static void flush_all(void); 55 static char *wide_char_to_byte_str(int rune, size_t *outlen); 56 57 #if 1 58 #define tempfree(x) \ 59 do { \ 60 if (istemp(x)) \ 61 tfree(x); \ 62 } while (/* CONSTCOND */ 0) 63 #else 64 void 65 tempfree(Cell *p) 66 { 67 if (p->ctype == OCELL && (p->csub < CUNK || p->csub > CFREE)) { 68 WARNING("bad csub %d in Cell %d %s", p->csub, p->ctype, p->sval); 69 } 70 if (istemp(p)) 71 tfree(p); 72 } 73 #endif 74 75 /* do we really need these? */ 76 /* #ifdef _NFILE */ 77 /* #ifndef FOPEN_MAX */ 78 /* #define FOPEN_MAX _NFILE */ 79 /* #endif */ 80 /* #endif */ 81 82 /* #ifndef fopen_max */ 83 /* #define fopen_max 40 */ /* max number of open files */ 84 /* #endif */ 85 86 jmp_buf env; 87 extern int pairstack[]; 88 extern Awkfloat srand_seed; 89 90 Node *winner = NULL; /* root of parse tree */ 91 Cell *tmps; /* free temporary cells for execution */ 92 93 static Cell truecell = {OBOOL, BTRUE, 0, 0, 1.0, NUM, NULL, NULL}; 94 Cell *True = &truecell; 95 static Cell falsecell = {OBOOL, BFALSE, 0, 0, 0.0, NUM, NULL, NULL}; 96 Cell *False = &falsecell; 97 static Cell breakcell = {OJUMP, JBREAK, 0, 0, 0.0, NUM, NULL, NULL}; 98 Cell *jbreak = &breakcell; 99 static Cell contcell = {OJUMP, JCONT, 0, 0, 0.0, NUM, NULL, NULL}; 100 Cell *jcont = &contcell; 101 static Cell nextcell = {OJUMP, JNEXT, 0, 0, 0.0, NUM, NULL, NULL}; 102 Cell *jnext = &nextcell; 103 static Cell nextfilecell = {OJUMP, JNEXTFILE, 0, 0, 0.0, NUM, NULL, NULL}; 104 Cell *jnextfile = &nextfilecell; 105 static Cell exitcell = {OJUMP, JEXIT, 0, 0, 0.0, NUM, NULL, NULL}; 106 Cell *jexit = &exitcell; 107 static Cell retcell = {OJUMP, JRET, 0, 0, 0.0, NUM, NULL, NULL}; 108 Cell *jret = &retcell; 109 static Cell tempcell = {OCELL, CTEMP, 0, EMPTY, 0.0, NUM | STR | DONTFREE, NULL, NULL}; 110 111 Node *curnode = NULL; /* the node being executed, for debugging */ 112 113 /* buffer memory management */ 114 int 115 adjbuf(char **pbuf, int *psiz, int minlen, int quantum, char **pbptr, const char *whatrtn) 116 /* pbuf: address of pointer to buffer being managed 117 * psiz: address of buffer size variable 118 * minlen: minimum length of buffer needed 119 * quantum: buffer size quantum 120 * pbptr: address of movable pointer into buffer, or 0 if none 121 * whatrtn: name of the calling routine if failure should cause fatal error 122 * 123 * return 0 for realloc failure, !=0 for success 124 */ 125 { 126 if (minlen > *psiz) { 127 char *tbuf; 128 int rminlen = quantum ? minlen % quantum : 0; 129 int boff = pbptr ? *pbptr - *pbuf : 0; 130 /* round up to next multiple of quantum */ 131 if (rminlen) 132 minlen += quantum - rminlen; 133 tbuf = (char *)realloc(*pbuf, minlen); 134 DPRINTF( 135 "adjbuf %s: %d %d (pbuf=%p, tbuf=%p)\n", whatrtn, *psiz, minlen, (void *)*pbuf, (void *)tbuf 136 ); 137 if (tbuf == NULL) { 138 if (whatrtn) 139 FATAL("out of memory in %s", whatrtn); 140 return 0; 141 } 142 *pbuf = tbuf; 143 *psiz = minlen; 144 if (pbptr) 145 *pbptr = tbuf + boff; 146 } 147 return 1; 148 } 149 150 void 151 run(Node *a) /* execution of parse tree starts here */ 152 { 153 stdinit(); 154 execute(a); 155 closeall(); 156 } 157 158 Cell * 159 execute(Node *u) /* execute a node of the parse tree */ 160 { 161 Cell *(*proc)(Node **, int); 162 Cell *x; 163 Node *a; 164 165 if (u == NULL) 166 return (True); 167 for (a = u;; a = a->nnext) { 168 curnode = a; 169 if (isvalue(a)) { 170 x = (Cell *)(a->narg[0]); 171 if (isfld(x) && !donefld) 172 fldbld(); 173 else if (isrec(x) && !donerec) 174 recbld(); 175 return (x); 176 } 177 if (notlegal(a->nobj)) /* probably a cell* but too risky to 178 * print */ 179 FATAL("illegal statement"); 180 proc = proctab[a->nobj - FIRSTTOKEN]; 181 x = (*proc)(a->narg, a->nobj); 182 if (isfld(x) && !donefld) 183 fldbld(); 184 else if (isrec(x) && !donerec) 185 recbld(); 186 if (isexpr(a)) 187 return (x); 188 if (isjump(x)) 189 return (x); 190 if (a->nnext == NULL) 191 return (x); 192 tempfree(x); 193 } 194 } 195 196 Cell * 197 program(Node **a, int n) /* execute an awk program */ 198 { /* a[0] = BEGIN, a[1] = body, a[2] = END */ 199 Cell *x; 200 201 if (setjmp(env) != 0) 202 goto ex; 203 if (a[0]) { /* BEGIN */ 204 x = execute(a[0]); 205 if (isexit(x)) 206 return (True); 207 if (isjump(x)) 208 FATAL( 209 "illegal break, continue, next or nextfile from " 210 "BEGIN" 211 ); 212 tempfree(x); 213 } 214 if (a[1] || a[2]) 215 while (getrec(&record, &recsize, true) > 0) { 216 x = execute(a[1]); 217 if (isexit(x)) 218 break; 219 tempfree(x); 220 } 221 ex: 222 if (setjmp(env) != 0) /* handles exit within END */ 223 goto ex1; 224 if (a[2]) { /* END */ 225 x = execute(a[2]); 226 if (isbreak(x) || isnext(x) || iscont(x)) 227 FATAL( 228 "illegal break, continue, next or nextfile from " 229 "END" 230 ); 231 tempfree(x); 232 } 233 ex1: 234 return (True); 235 } 236 237 struct Frame { /* stack frame for awk function calls */ 238 int nargs; /* number of arguments in this call */ 239 Cell *fcncell; /* pointer to cell for function */ 240 Cell **args; /* pointer to array of arguments after execute */ 241 Cell *retval; /* return value */ 242 }; 243 244 #define NARGS 50 /* max args in a call */ 245 246 struct Frame *frame = NULL; /* base of stack frames; dynamically allocated */ 247 int nframe = 0; /* number of frames allocated */ 248 struct Frame *frp = NULL; /* frame pointer. bottom level unused */ 249 250 Cell * 251 call(Node **a, int n) /* function call. very kludgy and fragile */ 252 { 253 static const Cell newcopycell = {OCELL, CCOPY, 0, EMPTY, 0.0, NUM | STR | DONTFREE, NULL, NULL}; 254 int i, ncall, ndef; 255 int freed = 0; /* handles potential double freeing when fcn & param 256 * share a tempcell */ 257 Node *x; 258 Cell *args[NARGS], *oargs[NARGS]; /* BUG: fixed size arrays */ 259 Cell *y, *z, *fcn; 260 char *s; 261 262 fcn = execute(a[0]); /* the function itself */ 263 s = fcn->nval; 264 if (!isfcn(fcn)) 265 FATAL("calling undefined function %s", s); 266 if (frame == NULL) { 267 frp = frame = (struct Frame *)calloc(nframe += 100, sizeof(*frame)); 268 if (frame == NULL) 269 FATAL("out of space for stack frames calling %s", s); 270 } 271 for (ncall = 0, x = a[1]; x != NULL; x = x->nnext) /* args in call */ 272 ncall++; 273 ndef = (int)fcn->fval; /* args in defn */ 274 DPRINTF("calling %s, %d args (%d in defn), frp=%d\n", s, ncall, ndef, (int)(frp - frame)); 275 if (ncall > ndef) 276 WARNING("function %s called with %d args, uses only %d", s, ncall, ndef); 277 if (ncall + ndef > NARGS) 278 FATAL("function %s has %d arguments, limit %d", s, ncall + ndef, NARGS); 279 for (i = 0, x = a[1]; x != NULL; i++, x = x->nnext) { /* get call args */ 280 DPRINTF("evaluate args[%d], frp=%d:\n", i, (int)(frp - frame)); 281 y = execute(x); 282 oargs[i] = y; 283 DPRINTF( 284 "args[%d]: %s %f <%s>, t=%o\n", 285 i, 286 NN(y->nval), 287 y->fval, 288 isarr(y) ? "(array)" : NN(y->sval), 289 y->tval 290 ); 291 if (isfcn(y)) 292 FATAL("can't use function %s as argument in %s", y->nval, s); 293 if (isarr(y)) 294 args[i] = y; /* arrays by ref */ 295 else 296 args[i] = copycell(y); 297 tempfree(y); 298 } 299 for (; i < ndef; i++) { /* add null args for ones not provided */ 300 args[i] = gettemp(); 301 *args[i] = newcopycell; 302 } 303 frp++; /* now ok to up frame */ 304 if (frp >= frame + nframe) { 305 int dfp = frp - frame; /* old index */ 306 frame = (struct Frame *)realloc(frame, (nframe += 100) * sizeof(*frame)); 307 if (frame == NULL) 308 FATAL("out of space for stack frames in %s", s); 309 frp = frame + dfp; 310 } 311 frp->fcncell = fcn; 312 frp->args = args; 313 frp->nargs = ndef; /* number defined with (excess are locals) */ 314 frp->retval = gettemp(); 315 316 DPRINTF("start exec of %s, frp=%d\n", s, (int)(frp - frame)); 317 y = execute((Node *)(fcn->sval)); /* execute body */ 318 DPRINTF("finished exec of %s, frp=%d\n", s, (int)(frp - frame)); 319 320 for (i = 0; i < ndef; i++) { 321 Cell *t = frp->args[i]; 322 if (isarr(t)) { 323 if (t->csub == CCOPY) { 324 if (i >= ncall) { 325 freesymtab(t); 326 t->csub = CTEMP; 327 tempfree(t); 328 } else { 329 oargs[i]->tval = t->tval; 330 oargs[i]->tval &= ~(STR | NUM | DONTFREE); 331 oargs[i]->sval = t->sval; 332 tempfree(t); 333 } 334 } 335 } else if (t != y) { /* kludge to prevent freeing twice */ 336 t->csub = CTEMP; 337 tempfree(t); 338 } else if (t == y && t->csub == CCOPY) { 339 t->csub = CTEMP; 340 tempfree(t); 341 freed = 1; 342 } 343 } 344 tempfree(fcn); 345 if (isexit(y) || isnext(y)) 346 return y; 347 if (freed == 0) { 348 tempfree(y); /* dont free twice! */ 349 } 350 z = frp->retval; /* return value */ 351 DPRINTF("%s returns %g |%s| %o\n", s, getfval(z), getsval(z), z->tval); 352 frp--; 353 return (z); 354 } 355 356 Cell * 357 copycell(Cell *x) /* make a copy of a cell in a temp */ 358 { 359 Cell *y; 360 361 /* copy is not constant or field */ 362 363 y = gettemp(); 364 y->tval = x->tval & ~(CON | FLD | REC); 365 y->csub = CCOPY; /* prevents freeing until call is over */ 366 y->nval = x->nval; /* BUG? */ 367 if (isstr(x) /* || x->ctype == OCELL */) { 368 y->sval = tostring(x->sval); 369 y->tval &= ~DONTFREE; 370 } else 371 y->tval |= DONTFREE; 372 y->fval = x->fval; 373 return y; 374 } 375 376 Cell * 377 arg(Node **a, int n) /* nth argument of a function */ 378 { 379 n = ptoi(a[0]); /* argument number, counting from 0 */ 380 DPRINTF("arg(%d), frp->nargs=%d\n", n, frp->nargs); 381 if (n + 1 > frp->nargs) 382 FATAL("argument #%d of function %s was not supplied", n + 1, frp->fcncell->nval); 383 return frp->args[n]; 384 } 385 386 Cell * 387 jump(Node **a, int n) /* break, continue, next, nextfile, return */ 388 { 389 Cell *y; 390 391 switch (n) { 392 case EXIT: 393 if (a[0] != NULL) { 394 y = execute(a[0]); 395 errorflag = (int)getfval(y); 396 tempfree(y); 397 } 398 longjmp(env, 1); 399 case RETURN: 400 if (a[0] != NULL) { 401 y = execute(a[0]); 402 if ((y->tval & (STR | NUM)) == (STR | NUM)) { 403 setsval(frp->retval, getsval(y)); 404 frp->retval->fval = getfval(y); 405 frp->retval->tval |= NUM; 406 } else if (y->tval & STR) 407 setsval(frp->retval, getsval(y)); 408 else if (y->tval & NUM) 409 setfval(frp->retval, getfval(y)); 410 else /* cant happen */ 411 FATAL("bad type variable %d", y->tval); 412 tempfree(y); 413 } 414 return (jret); 415 case NEXT: 416 return (jnext); 417 case NEXTFILE: 418 nextfile(); 419 return (jnextfile); 420 case BREAK: 421 return (jbreak); 422 case CONTINUE: 423 return (jcont); 424 default: /* cant happen */ 425 FATAL("illegal jump type %d", n); 426 } 427 return 0; /* not reached */ 428 } 429 430 Cell * 431 awkgetline(Node **a, int n) /* get next line from specific input */ 432 { /* a[0] is variable, a[1] is operator, a[2] is filename */ 433 Cell *r, *x; 434 extern Cell **fldtab; 435 FILE *fp; 436 char *buf; 437 int bufsize = recsize; 438 int mode; 439 bool newflag; 440 double result; 441 442 if ((buf = (char *)malloc(bufsize)) == NULL) 443 FATAL("out of memory in getline"); 444 445 fflush(stdout); /* in case someone is waiting for a prompt */ 446 r = gettemp(); 447 if (a[1] != NULL) { /* getline < file */ 448 x = execute(a[2]); /* filename */ 449 mode = ptoi(a[1]); 450 if (mode == '|') /* input pipe */ 451 mode = LE; /* arbitrary flag */ 452 fp = openfile(mode, getsval(x), &newflag); 453 tempfree(x); 454 if (fp == NULL) 455 n = -1; 456 else 457 n = readrec(&buf, &bufsize, fp, newflag); 458 if (n <= 0) { 459 ; 460 } else if (a[0] != NULL) { /* getline var <file */ 461 x = execute(a[0]); 462 setsval(x, buf); 463 if (is_number(x->sval, &result)) { 464 x->fval = result; 465 x->tval |= NUM; 466 } 467 tempfree(x); 468 } else { /* getline <file */ 469 setsval(fldtab[0], buf); 470 if (is_number(fldtab[0]->sval, &result)) { 471 fldtab[0]->fval = result; 472 fldtab[0]->tval |= NUM; 473 } 474 } 475 } else { /* bare getline; use current input */ 476 if (a[0] == NULL) /* getline */ 477 n = getrec(&record, &recsize, true); 478 else { /* getline var */ 479 n = getrec(&buf, &bufsize, false); 480 if (n > 0) { 481 x = execute(a[0]); 482 setsval(x, buf); 483 if (is_number(x->sval, &result)) { 484 x->fval = result; 485 x->tval |= NUM; 486 } 487 tempfree(x); 488 } 489 } 490 } 491 setfval(r, (Awkfloat)n); 492 free(buf); 493 return r; 494 } 495 496 Cell * 497 getnf(Node **a, int n) /* get NF */ 498 { 499 if (!donefld) 500 fldbld(); 501 return (Cell *)a[0]; 502 } 503 504 static char * 505 makearraystring(Node *p, const char *func) 506 { 507 char *buf; 508 int bufsz = recsize; 509 size_t blen; 510 511 if ((buf = (char *)malloc(bufsz)) == NULL) { 512 FATAL("%s: out of memory", func); 513 } 514 515 blen = 0; 516 buf[blen] = '\0'; 517 518 for (; p; p = p->nnext) { 519 Cell *x = execute(p); /* expr */ 520 char *s = getsval(x); 521 size_t seplen = strlen(getsval(subseploc)); 522 size_t nsub = p->nnext ? seplen : 0; 523 size_t slen = strlen(s); 524 size_t tlen = blen + slen + nsub; 525 526 if (!adjbuf(&buf, &bufsz, tlen + 1, recsize, 0, func)) { 527 FATAL("%s: out of memory %s[%s...]", func, x->nval, buf); 528 } 529 memcpy(buf + blen, s, slen); 530 if (nsub) { 531 memcpy(buf + blen + slen, *SUBSEP, nsub); 532 } 533 buf[tlen] = '\0'; 534 blen = tlen; 535 tempfree(x); 536 } 537 return buf; 538 } 539 540 Cell * 541 array(Node **a, int n) /* a[0] is symtab, a[1] is list of subscripts */ 542 { 543 Cell *x, *z; 544 char *buf; 545 546 x = execute(a[0]); /* cell* for symbol table */ 547 buf = makearraystring(a[1], __func__); 548 if (!isarr(x)) { 549 DPRINTF("making %s into an array\n", NN(x->nval)); 550 if (freeable(x)) 551 xfree(x->sval); 552 x->tval &= ~(STR | NUM | DONTFREE); 553 x->tval |= ARR; 554 x->sval = (char *)makesymtab(NSYMTAB); 555 } 556 z = setsymtab(buf, "", 0.0, STR | NUM, (Array *)x->sval); 557 z->ctype = OCELL; 558 z->csub = CVAR; 559 tempfree(x); 560 free(buf); 561 return (z); 562 } 563 564 Cell * 565 awkdelete(Node **a, int n) /* a[0] is symtab, a[1] is list of subscripts */ 566 { 567 Cell *x; 568 569 x = execute(a[0]); /* cell* for symbol table */ 570 if (x == symtabloc) { 571 FATAL("cannot delete SYMTAB or its elements"); 572 } 573 if (!isarr(x)) 574 return True; 575 if (a[1] == NULL) { /* delete the elements, not the table */ 576 freesymtab(x); 577 x->tval &= ~STR; 578 x->tval |= ARR; 579 x->sval = (char *)makesymtab(NSYMTAB); 580 } else { 581 char *buf = makearraystring(a[1], __func__); 582 freeelem(x, buf); 583 free(buf); 584 } 585 tempfree(x); 586 return True; 587 } 588 589 Cell * 590 intest(Node **a, int n) /* a[0] is index (list), a[1] is symtab */ 591 { 592 Cell *ap, *k; 593 char *buf; 594 595 ap = execute(a[1]); /* array name */ 596 if (!isarr(ap)) { 597 DPRINTF("making %s into an array\n", ap->nval); 598 if (freeable(ap)) 599 xfree(ap->sval); 600 ap->tval &= ~(STR | NUM | DONTFREE); 601 ap->tval |= ARR; 602 ap->sval = (char *)makesymtab(NSYMTAB); 603 } 604 buf = makearraystring(a[0], __func__); 605 k = lookup(buf, (Array *)ap->sval); 606 tempfree(ap); 607 free(buf); 608 if (k == NULL) 609 return (False); 610 else 611 return (True); 612 } 613 614 /* ======== utf-8 code ========== */ 615 616 /* 617 * awk strings can contain ascii, random 8-bit items (eg latin-1), 618 * or utf-8. u8_isutf tests whether a string starts with a valid 619 * utf-8 sequence, and returns 0 if not (e.g., high bit set) 620 * u8_nextlen returns length of next valid sequence, which is 621 * 1 for ascii, 2..4 for utf-8, or 1 for high bit non-utf 622 * u8_strlen returns length of string in valid utf-8 sequences 623 * and/or high-bit bytes. conversion functions go between byte 624 * number and character number 625 * 626 * in theory, this behaves the same as before for non-utf8 bytes 627 * 628 * limited checking! this is a potential security hole 629 */ 630 631 /* is s the beginning of a valid utf-8 string? */ 632 /* return length 1..4 if yes, 0 if no */ 633 int 634 u8_isutf(const char *s) 635 { 636 int n, ret; 637 unsigned char c; 638 639 c = s[0]; 640 if (c < 128 || awk_mb_cur_max == 1) 641 return 1; /* what if its 0? */ 642 643 n = strlen(s); 644 if (n >= 2 && ((c >> 5) & 0x7) == 0x6 && (s[1] & 0xC0) == 0x80) { 645 ret = 2; /* 110xxxxx 10xxxxxx */ 646 } else if (n >= 3 && ((c >> 4) & 0xF) == 0xE && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80) { 647 ret = 3; /* 1110xxxx 10xxxxxx 10xxxxxx */ 648 } else if ( 649 n >= 4 && ((c >> 3) & 0x1F) == 0x1E && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80 650 && (s[3] & 0xC0) == 0x80 651 ) { 652 ret = 4; /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ 653 } else { 654 ret = 0; 655 } 656 return ret; 657 } 658 659 /* convert (prefix of) utf8 string to utf-32 rune */ 660 /* sets *rune to the value, returns the length */ 661 /* no error checking: watch out */ 662 int 663 u8_rune(int *rune, const char *s) 664 { 665 int n, ret; 666 unsigned char c; 667 668 c = s[0]; 669 if (c < 128 || awk_mb_cur_max == 1) { 670 *rune = c; 671 return 1; 672 } 673 674 n = strlen(s); 675 if (n >= 2 && ((c >> 5) & 0x7) == 0x6 && (s[1] & 0xC0) == 0x80) { 676 *rune = ((c & 0x1F) << 6) | (s[1] & 0x3F); /* 110xxxxx 10xxxxxx */ 677 ret = 2; 678 } else if (n >= 3 && ((c >> 4) & 0xF) == 0xE && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80) { 679 *rune = ((c & 0xF) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F); 680 /* 1110xxxx 10xxxxxx 10xxxxxx */ 681 ret = 3; 682 } else if ( 683 n >= 4 && ((c >> 3) & 0x1F) == 0x1E && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80 684 && (s[3] & 0xC0) == 0x80 685 ) { 686 *rune = ((c & 0x7) << 18) | ((s[1] & 0x3F) << 12) | ((s[2] & 0x3F) << 6) | (s[3] & 0x3F); 687 /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ 688 ret = 4; 689 } else { 690 *rune = c; 691 ret = 1; 692 } 693 return ret; /* returns one byte if sequence doesnt look like utf */ 694 } 695 696 /* return length of next sequence: 1 for ascii or random, 2..4 for valid utf8 */ 697 int 698 u8_nextlen(const char *s) 699 { 700 int len; 701 702 len = u8_isutf(s); 703 if (len == 0) 704 len = 1; 705 return len; 706 } 707 708 /* return number of utf characters or single non-utf bytes */ 709 int 710 u8_strlen(const char *s) 711 { 712 int i, len, n, totlen; 713 unsigned char c; 714 715 n = strlen(s); 716 totlen = 0; 717 for (i = 0; i < n; i += len) { 718 c = s[i]; 719 if (c < 128 || awk_mb_cur_max == 1) { 720 len = 1; 721 } else { 722 len = u8_nextlen(&s[i]); 723 } 724 totlen++; 725 if (i > n) 726 FATAL("bad utf count [%s] n=%d i=%d\n", s, n, i); 727 } 728 return totlen; 729 } 730 731 /* convert utf-8 char number in a string to its byte offset */ 732 int 733 u8_char2byte(const char *s, int charnum) 734 { 735 int n; 736 int bytenum = 0; 737 738 while (charnum > 0) { 739 n = u8_nextlen(s); 740 s += n; 741 bytenum += n; 742 charnum--; 743 } 744 return bytenum; 745 } 746 747 /* convert byte offset in s to utf-8 char number that starts there */ 748 int 749 u8_byte2char(const char *s, int bytenum) 750 { 751 int i, len, b; 752 int charnum = 0; /* BUG: what origin? */ 753 /* should be 0 to match start==0 which means no match */ 754 755 b = strlen(s); 756 if (bytenum > b) { 757 return -1; /* ??? */ 758 } 759 for (i = 0; i <= bytenum; i += len) { 760 len = u8_nextlen(s + i); 761 charnum++; 762 } 763 return charnum; 764 } 765 766 /* runetochar() adapted from rune.c in the plan 9 distribution */ 767 768 enum { 769 Runeerror = 128, /* from somewhere else */ 770 Runemax = 0x10FFFF, 771 772 Bit1 = 7, 773 Bitx = 6, 774 Bit2 = 5, 775 Bit3 = 4, 776 Bit4 = 3, 777 Bit5 = 2, 778 779 T1 = ((1 << (Bit1 + 1)) - 1) ^ 0xFF, /* 0000 0000 */ 780 Tx = ((1 << (Bitx + 1)) - 1) ^ 0xFF, /* 1000 0000 */ 781 T2 = ((1 << (Bit2 + 1)) - 1) ^ 0xFF, /* 1100 0000 */ 782 T3 = ((1 << (Bit3 + 1)) - 1) ^ 0xFF, /* 1110 0000 */ 783 T4 = ((1 << (Bit4 + 1)) - 1) ^ 0xFF, /* 1111 0000 */ 784 T5 = ((1 << (Bit5 + 1)) - 1) ^ 0xFF, /* 1111 1000 */ 785 786 Rune1 = (1 << (Bit1 + 0 * Bitx)) - 1, /* 0000 0000 0000 0000 0111 1111 */ 787 Rune2 = (1 << (Bit2 + 1 * Bitx)) - 1, /* 0000 0000 0000 0111 1111 1111 */ 788 Rune3 = (1 << (Bit3 + 2 * Bitx)) - 1, /* 0000 0000 1111 1111 1111 1111 */ 789 Rune4 = (1 << (Bit4 + 3 * Bitx)) - 1, /* 0011 1111 1111 1111 1111 1111 */ 790 791 Maskx = (1 << Bitx) - 1, /* 0011 1111 */ 792 Testx = Maskx ^ 0xFF, /* 1100 0000 */ 793 794 }; 795 796 int 797 runetochar(char *str, int c) 798 { 799 /* one character sequence 00000-0007F => 00-7F */ 800 if (c <= Rune1) { 801 str[0] = c; 802 return 1; 803 } 804 805 /* two character sequence 00080-007FF => T2 tx */ 806 if (c <= Rune2) { 807 str[0] = T2 | (c >> 1 * Bitx); 808 str[1] = Tx | (c & Maskx); 809 return 2; 810 } 811 812 /* three character sequence 00800-0FFFF => T3 tx tx */ 813 if (c > Runemax) 814 c = Runeerror; 815 if (c <= Rune3) { 816 str[0] = T3 | (c >> 2 * Bitx); 817 str[1] = Tx | ((c >> 1 * Bitx) & Maskx); 818 str[2] = Tx | (c & Maskx); 819 return 3; 820 } 821 822 /* four character sequence 010000-1FFFFF => T4 tx tx tx */ 823 str[0] = T4 | (c >> 3 * Bitx); 824 str[1] = Tx | ((c >> 2 * Bitx) & Maskx); 825 str[2] = Tx | ((c >> 1 * Bitx) & Maskx); 826 str[3] = Tx | (c & Maskx); 827 return 4; 828 } 829 830 /* ========== end of utf8 code =========== */ 831 832 Cell * 833 matchop(Node **a, int n) /* ~ and match() */ 834 { 835 Cell *x, *y, *z; 836 char *s, *t; 837 int i; 838 int cstart, cpatlen, len; 839 fa *pfa; 840 int (*mf)(fa *, const char *) = match, mode = 0; 841 842 if (n == MATCHFCN) { 843 mf = pmatch; 844 mode = 1; 845 } 846 x = execute(a[1]); /* a[1] = target text */ 847 s = getsval(x); 848 if (a[0] == NULL) /* a[1] == 0: already-compiled reg expr */ 849 i = (*mf)((fa *)a[2], s); 850 else { 851 y = execute(a[2]); /* a[2] = regular expr */ 852 t = getsval(y); 853 pfa = makedfa(t, mode); 854 i = (*mf)(pfa, s); 855 tempfree(y); 856 } 857 z = x; 858 if (n == MATCHFCN) { 859 int start = patbeg - s + 1; /* origin 1 */ 860 if (patlen < 0) { 861 start = 0; /* not found */ 862 } else { 863 cstart = u8_byte2char(s, start - 1); 864 cpatlen = 0; 865 for (i = 0; i < patlen; i += len) { 866 len = u8_nextlen(patbeg + i); 867 cpatlen++; 868 } 869 870 start = cstart; 871 patlen = cpatlen; 872 } 873 874 setfval(rstartloc, (Awkfloat)start); 875 setfval(rlengthloc, (Awkfloat)patlen); 876 x = gettemp(); 877 x->tval = NUM; 878 x->fval = start; 879 } else if ((n == MATCH && i == 1) || (n == NOTMATCH && i == 0)) 880 x = True; 881 else 882 x = False; 883 884 tempfree(z); 885 return x; 886 } 887 888 Cell * 889 boolop(Node **a, int n) /* a[0] || a[1], a[0] && a[1], !a[0] */ 890 { 891 Cell *x, *y; 892 int i; 893 894 x = execute(a[0]); 895 i = istrue(x); 896 tempfree(x); 897 switch (n) { 898 case BOR: 899 if (i) 900 return (True); 901 y = execute(a[1]); 902 i = istrue(y); 903 tempfree(y); 904 if (i) 905 return (True); 906 else 907 return (False); 908 case AND: 909 if (!i) 910 return (False); 911 y = execute(a[1]); 912 i = istrue(y); 913 tempfree(y); 914 if (i) 915 return (True); 916 else 917 return (False); 918 case NOT: 919 if (i) 920 return (False); 921 else 922 return (True); 923 default: /* cant happen */ 924 FATAL("unknown boolean operator %d", n); 925 } 926 return 0; /* NOTREACHED */ 927 } 928 929 Cell * 930 relop(Node **a, int n) /* a[0 < a[1], etc */ 931 { 932 int i; 933 Cell *x, *y; 934 Awkfloat j; 935 bool x_is_nan, y_is_nan; 936 937 x = execute(a[0]); 938 y = execute(a[1]); 939 x_is_nan = isnan(x->fval); 940 y_is_nan = isnan(y->fval); 941 if (x->tval & NUM && y->tval & NUM) { 942 if ((x_is_nan || y_is_nan) && n != NE) 943 return (False); 944 j = x->fval - y->fval; 945 i = j < 0 ? -1 : (j > 0 ? 1 : 0); 946 } else { 947 i = strcmp(getsval(x), getsval(y)); 948 } 949 tempfree(x); 950 tempfree(y); 951 switch (n) { 952 case LT: 953 if (i < 0) 954 return (True); 955 else 956 return (False); 957 case LE: 958 if (i <= 0) 959 return (True); 960 else 961 return (False); 962 case NE: 963 if (x_is_nan && y_is_nan) 964 return (True); 965 else if (i != 0) 966 return (True); 967 else 968 return (False); 969 case EQ: 970 if (i == 0) 971 return (True); 972 else 973 return (False); 974 case GE: 975 if (i >= 0) 976 return (True); 977 else 978 return (False); 979 case GT: 980 if (i > 0) 981 return (True); 982 else 983 return (False); 984 default: /* cant happen */ 985 FATAL("unknown relational operator %d", n); 986 } 987 return 0; /* NOTREACHED */ 988 } 989 990 void 991 tfree(Cell *a) /* free a tempcell */ 992 { 993 if (freeable(a)) { 994 DPRINTF("freeing %s %s %o\n", NN(a->nval), NN(a->sval), a->tval); 995 xfree(a->sval); 996 } 997 if (a == tmps) 998 FATAL("tempcell list is curdled"); 999 a->cnext = tmps; 1000 tmps = a; 1001 } 1002 1003 Cell * 1004 gettemp(void) /* get a tempcell */ 1005 { 1006 int i; 1007 Cell *x; 1008 1009 if (!tmps) { 1010 tmps = (Cell *)calloc(100, sizeof(*tmps)); 1011 if (!tmps) 1012 FATAL("out of space for temporaries"); 1013 for (i = 1; i < 100; i++) 1014 tmps[i - 1].cnext = &tmps[i]; 1015 tmps[i - 1].cnext = NULL; 1016 } 1017 x = tmps; 1018 tmps = x->cnext; 1019 *x = tempcell; 1020 return (x); 1021 } 1022 1023 Cell * 1024 indirect(Node **a, int n) /* $( a[0] ) */ 1025 { 1026 Awkfloat val; 1027 Cell *x; 1028 int m; 1029 1030 x = execute(a[0]); 1031 val = getfval(x); /* freebsd: defend against super large field numbers */ 1032 if ((Awkfloat)INT_MAX < val) 1033 FATAL("trying to access out of range field %s", x->nval); 1034 m = (int)val; 1035 tempfree(x); 1036 x = fieldadr(m); 1037 x->ctype = OCELL; /* BUG? why are these needed? */ 1038 x->csub = CFLD; 1039 return (x); 1040 } 1041 1042 Cell * 1043 substr(Node **a, int nnn) /* substr(a[0], a[1], a[2]) */ 1044 { 1045 int k, m, n; 1046 int mb, nb; 1047 char *s; 1048 int temp; 1049 Cell *x, *y, *z = NULL; 1050 1051 x = execute(a[0]); 1052 y = execute(a[1]); 1053 if (a[2] != NULL) 1054 z = execute(a[2]); 1055 s = getsval(x); 1056 k = u8_strlen(s) + 1; 1057 if (k <= 1) { 1058 tempfree(x); 1059 tempfree(y); 1060 if (a[2] != NULL) { 1061 tempfree(z); 1062 } 1063 x = gettemp(); 1064 setsval(x, ""); 1065 return (x); 1066 } 1067 m = (int)getfval(y); 1068 if (m <= 0) 1069 m = 1; 1070 else if (m > k) 1071 m = k; 1072 tempfree(y); 1073 if (a[2] != NULL) { 1074 n = (int)getfval(z); 1075 tempfree(z); 1076 } else 1077 n = k - 1; 1078 if (n < 0) 1079 n = 0; 1080 else if (n > k - m) 1081 n = k - m; 1082 /* m is start, n is length from there */ 1083 DPRINTF("substr: m=%d, n=%d, s=%s\n", m, n, s); 1084 y = gettemp(); 1085 mb = u8_char2byte(s, m - 1); /* byte offset of start char in s */ 1086 nb = u8_char2byte(s, m - 1 + n); /* byte offset of end+1 char in s */ 1087 1088 temp = s[nb]; /* with thanks to john linderman */ 1089 s[nb] = '\0'; 1090 setsval(y, s + mb); 1091 s[nb] = temp; 1092 tempfree(x); 1093 return (y); 1094 } 1095 1096 Cell * 1097 sindex(Node **a, int nnn) /* index(a[0], a[1]) */ 1098 { 1099 Cell *x, *y, *z; 1100 char *s1, *s2, *p1, *p2, *q; 1101 Awkfloat v = 0.0; 1102 1103 x = execute(a[0]); 1104 s1 = getsval(x); 1105 y = execute(a[1]); 1106 s2 = getsval(y); 1107 1108 z = gettemp(); 1109 for (p1 = s1; *p1 != '\0'; p1++) { 1110 for (q = p1, p2 = s2; *p2 != '\0' && *q == *p2; q++, p2++) 1111 continue; 1112 if (*p2 == '\0') { 1113 /* v = (awkfloat) (p1 - s1 + 1); origin 1 */ 1114 1115 /* should be a function: used in match() as well */ 1116 int i, len; 1117 v = 0; 1118 for (i = 0; i < p1 - s1 + 1; i += len) { 1119 len = u8_nextlen(s1 + i); 1120 v++; 1121 } 1122 break; 1123 } 1124 } 1125 tempfree(x); 1126 tempfree(y); 1127 setfval(z, v); 1128 return (z); 1129 } 1130 1131 int 1132 has_utf8(char *s) /* return 1 if s contains any utf-8 (2 bytes or more) 1133 * character */ 1134 { 1135 int n; 1136 1137 for (n = 0; *s != 0; s += n) { 1138 n = u8_nextlen(s); 1139 if (n > 1) 1140 return 1; 1141 } 1142 return 0; 1143 } 1144 1145 #define MAXNUMSIZE 50 1146 1147 int 1148 format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conversions */ 1149 { 1150 char *fmt; 1151 char *p, *t; 1152 const char *os; 1153 Cell *x; 1154 int flag = 0, n; 1155 int fmtwd; /* format width */ 1156 int fmtsz = recsize; 1157 char *buf = *pbuf; 1158 int bufsize = *pbufsize; 1159 #define FMTSZ(a) (fmtsz - ((a) - fmt)) 1160 #define BUFSZ(a) (bufsize - ((a) - buf)) 1161 1162 static bool first = true; 1163 static bool have_a_format = false; 1164 1165 if (first) { 1166 char xbuf[100]; 1167 1168 snprintf(xbuf, sizeof(xbuf), "%a", 42.0); 1169 have_a_format = (strcmp(xbuf, "0x1.5p+5") == 0); 1170 first = false; 1171 } 1172 1173 os = s; 1174 p = buf; 1175 if ((fmt = (char *)malloc(fmtsz)) == NULL) 1176 FATAL("out of memory in format()"); 1177 while (*s) { 1178 adjbuf(&buf, &bufsize, MAXNUMSIZE + 1 + p - buf, recsize, &p, "format1"); 1179 if (*s != '%') { 1180 *p++ = *s++; 1181 continue; 1182 } 1183 if (*(s + 1) == '%') { 1184 *p++ = '%'; 1185 s += 2; 1186 continue; 1187 } 1188 fmtwd = atoi(s + 1); 1189 if (fmtwd < 0) 1190 fmtwd = -fmtwd; 1191 adjbuf(&buf, &bufsize, fmtwd + 1 + p - buf, recsize, &p, "format2"); 1192 for (t = fmt; (*t++ = *s) != '\0'; s++) { 1193 if (!adjbuf(&fmt, &fmtsz, MAXNUMSIZE + 1 + t - fmt, recsize, &t, "format3")) 1194 FATAL( 1195 "format item %.30s... ran format() out " 1196 "of memory", 1197 os 1198 ); 1199 /* ignore size specifiers */ 1200 if (strchr("hjLlqtz", *s) != NULL) { /* the ansi panoply */ 1201 t--; 1202 continue; 1203 } 1204 if (isalpha((uschar)*s)) 1205 break; 1206 if (*s == '$') { 1207 FATAL("'$' not permitted in awk formats"); 1208 } 1209 if (*s == '*') { 1210 if (a == NULL) { 1211 FATAL("not enough args in printf(%s)", os); 1212 } 1213 x = execute(a); 1214 a = a->nnext; 1215 snprintf(t - 1, FMTSZ(t - 1), "%d", fmtwd = (int)getfval(x)); 1216 if (fmtwd < 0) 1217 fmtwd = -fmtwd; 1218 adjbuf(&buf, &bufsize, fmtwd + 1 + p - buf, recsize, &p, "format"); 1219 t = fmt + strlen(fmt); 1220 tempfree(x); 1221 } 1222 } 1223 *t = '\0'; 1224 if (fmtwd < 0) 1225 fmtwd = -fmtwd; 1226 adjbuf(&buf, &bufsize, fmtwd + 1 + p - buf, recsize, &p, "format4"); 1227 switch (*s) { 1228 case 'a': 1229 case 'A': 1230 if (have_a_format) 1231 flag = *s; 1232 else 1233 flag = 'f'; 1234 break; 1235 case 'f': 1236 case 'e': 1237 case 'g': 1238 case 'E': 1239 case 'G': 1240 flag = 'f'; 1241 break; 1242 case 'd': 1243 case 'i': 1244 case 'o': 1245 case 'x': 1246 case 'X': 1247 case 'u': 1248 flag = (*s == 'd' || *s == 'i') ? 'd' : 'u'; 1249 *(t - 1) = 'j'; 1250 *t = *s; 1251 *++t = '\0'; 1252 break; 1253 case 's': 1254 flag = 's'; 1255 break; 1256 case 'c': 1257 flag = 'c'; 1258 break; 1259 default: 1260 WARNING("weird printf conversion %s", fmt); 1261 flag = '?'; 1262 break; 1263 } 1264 if (a == NULL) 1265 FATAL("not enough args in printf(%s)", os); 1266 x = execute(a); 1267 a = a->nnext; 1268 n = MAXNUMSIZE; 1269 if (fmtwd > n) 1270 n = fmtwd; 1271 adjbuf(&buf, &bufsize, 1 + n + p - buf, recsize, &p, "format5"); 1272 switch (flag) { 1273 case '?': 1274 snprintf(p, BUFSZ(p), "%s", fmt); /* unknown, so dump it too */ 1275 t = getsval(x); 1276 n = strlen(t); 1277 if (fmtwd > n) 1278 n = fmtwd; 1279 adjbuf(&buf, &bufsize, 1 + strlen(p) + n + p - buf, recsize, &p, "format6"); 1280 p += strlen(p); 1281 snprintf(p, BUFSZ(p), "%s", t); 1282 break; 1283 case 'a': 1284 case 'A': 1285 case 'f': 1286 snprintf(p, BUFSZ(p), fmt, getfval(x)); 1287 break; 1288 case 'd': 1289 snprintf(p, BUFSZ(p), fmt, (intmax_t)getfval(x)); 1290 break; 1291 case 'u': 1292 snprintf(p, BUFSZ(p), fmt, (uintmax_t)getfval(x)); 1293 break; 1294 1295 case 's': { 1296 t = getsval(x); 1297 n = strlen(t); 1298 /* if simple format or no utf-8 in the string, sprintf 1299 * works */ 1300 if (!has_utf8(t) || strcmp(fmt, "%s") == 0) { 1301 if (fmtwd > n) 1302 n = fmtwd; 1303 if (!adjbuf(&buf, &bufsize, 1 + n + p - buf, recsize, &p, "format7")) 1304 FATAL( 1305 "huge string/format (%d chars) " 1306 "in printf %.30s..." 1307 " ran format() out of memory", 1308 n, 1309 t 1310 ); 1311 snprintf(p, BUFSZ(p), fmt, t); 1312 break; 1313 } 1314 1315 /* get here if string has utf-8 chars and fmt is not 1316 * plain %s */ 1317 /* "%-w.ps", where -, w and .p are all optional */ 1318 /* '0' before the w is a flag character */ 1319 /* fmt points at % */ 1320 int ljust = 0, wid = 0, prec = n, pad = 0; 1321 char *f = fmt + 1; 1322 if (f[0] == '-') { 1323 ljust = 1; 1324 f++; 1325 } 1326 /* flags '0' and '+' are recognized but skipped */ 1327 if (f[0] == '0') { 1328 f++; 1329 if (f[0] == '+') 1330 f++; 1331 } 1332 if (f[0] == '+') { 1333 f++; 1334 if (f[0] == '0') 1335 f++; 1336 } 1337 if (isdigit(f[0])) { /* there is a wid */ 1338 wid = strtol(f, &f, 10); 1339 } 1340 if (f[0] == '.') { /* there is a .prec */ 1341 prec = strtol(++f, &f, 10); 1342 } 1343 if (prec > u8_strlen(t)) 1344 prec = u8_strlen(t); 1345 pad = wid > prec ? wid - prec : 0; /* has to be >= 0 */ 1346 int i, k, n; 1347 1348 if (ljust) { /* print prec chars from t, then pad blanks */ 1349 n = u8_char2byte(t, prec); 1350 for (k = 0; k < n; k++) { 1351 /* putchar(t[k]); */ 1352 *p++ = t[k]; 1353 } 1354 for (i = 0; i < pad; i++) { 1355 /* printf(" "); */ 1356 *p++ = ' '; 1357 } 1358 } else { /* print pad blanks, then prec chars from t */ 1359 for (i = 0; i < pad; i++) { 1360 /* printf(" "); */ 1361 *p++ = ' '; 1362 } 1363 n = u8_char2byte(t, prec); 1364 for (k = 0; k < n; k++) { 1365 /* putchar(t[k]); */ 1366 *p++ = t[k]; 1367 } 1368 } 1369 *p = 0; 1370 break; 1371 } 1372 1373 case 'c': { 1374 /* 1375 * if a numeric value is given, awk should just turn 1376 * it into a character and print it: 1377 * BEGIN { printf("%c\n", 65) } 1378 * prints "a" 1379 * 1380 * but what if the numeric value is > 128 and 1381 * represents a valid unicode code point?!? we do 1382 * our best to convert it back into UTF-8. if we 1383 * cant, we output the encoding of the unicode 1384 * "invalid character", 0xfffd 1385 */ 1386 if (isnum(x)) { 1387 int charval = (int)getfval(x); 1388 1389 if (charval != 0) { 1390 if (charval < 128 || awk_mb_cur_max == 1) 1391 snprintf(p, BUFSZ(p), fmt, charval); 1392 else { 1393 /* possible unicode character */ 1394 size_t count; 1395 char *bs = wide_char_to_byte_str(charval, &count); 1396 1397 if (bs == NULL) { /* invalid character */ 1398 /* use unicode invalid 1399 * character, 0xfffd */ 1400 static char invalid_char[] = "\357\277" 1401 "\275"; 1402 bs = invalid_char; 1403 count = 3; 1404 } 1405 t = bs; 1406 n = count; 1407 goto format_percent_c; 1408 } 1409 } else { 1410 *p++ = '\0'; /* explicit null byte */ 1411 *p = '\0'; /* next output will start 1412 * here */ 1413 } 1414 break; 1415 } 1416 t = getsval(x); 1417 n = u8_nextlen(t); 1418 format_percent_c: 1419 if (n < 2) { /* not utf8 */ 1420 snprintf(p, BUFSZ(p), fmt, getsval(x)[0]); 1421 break; 1422 } 1423 1424 /* utf8 character, almost same song and dance as for %s */ 1425 int ljust = 0, wid = 0, prec = n, pad = 0; 1426 char *f = fmt + 1; 1427 if (f[0] == '-') { 1428 ljust = 1; 1429 f++; 1430 } 1431 /* flags '0' and '+' are recognized but skipped */ 1432 if (f[0] == '0') { 1433 f++; 1434 if (f[0] == '+') 1435 f++; 1436 } 1437 if (f[0] == '+') { 1438 f++; 1439 if (f[0] == '0') 1440 f++; 1441 } 1442 if (isdigit(f[0])) { /* there is a wid */ 1443 wid = strtol(f, &f, 10); 1444 } 1445 if (f[0] == '.') { /* there is a .prec */ 1446 prec = strtol(++f, &f, 10); 1447 } 1448 if (prec > 1) /* %c: only one character */ 1449 prec = 1; 1450 pad = wid > prec ? wid - prec : 0; /* has to be >= 0 */ 1451 int i; 1452 1453 if (ljust) { /* print one char from t, then pad blanks */ 1454 for (i = 0; i < n; i++) 1455 *p++ = t[i]; 1456 for (i = 0; i < pad; i++) { 1457 /* printf(" "); */ 1458 *p++ = ' '; 1459 } 1460 } else { /* print pad blanks, then prec chars from t */ 1461 for (i = 0; i < pad; i++) { 1462 /* printf(" "); */ 1463 *p++ = ' '; 1464 } 1465 for (i = 0; i < n; i++) 1466 *p++ = t[i]; 1467 } 1468 *p = 0; 1469 break; 1470 } 1471 default: 1472 FATAL("can't happen: bad conversion %c in format()", flag); 1473 } 1474 1475 tempfree(x); 1476 p += strlen(p); 1477 s++; 1478 } 1479 *p = '\0'; 1480 free(fmt); 1481 for (; a; a = a->nnext) { /* evaluate any remaining args */ 1482 x = execute(a); 1483 tempfree(x); 1484 } 1485 *pbuf = buf; 1486 *pbufsize = bufsize; 1487 return p - buf; 1488 } 1489 1490 Cell * 1491 awksprintf(Node **a, int n) /* sprintf(a[0]) */ 1492 { 1493 Cell *x; 1494 Node *y; 1495 char *buf; 1496 int bufsz = 3 * recsize; 1497 1498 if ((buf = (char *)malloc(bufsz)) == NULL) 1499 FATAL("out of memory in awksprintf"); 1500 y = a[0]->nnext; 1501 x = execute(a[0]); 1502 if (format(&buf, &bufsz, getsval(x), y) == -1) 1503 FATAL("sprintf string %.30s... too long. can't happen.", buf); 1504 tempfree(x); 1505 x = gettemp(); 1506 x->sval = buf; 1507 x->tval = STR; 1508 return (x); 1509 } 1510 1511 Cell * 1512 awkprintf(Node **a, int n) /* printf */ 1513 { /* a[0] is list of args, starting with format string */ 1514 /* a[1] is redirection operator, a[2] is redirection file */ 1515 FILE *fp; 1516 Cell *x; 1517 Node *y; 1518 char *buf; 1519 int len; 1520 int bufsz = 3 * recsize; 1521 1522 if ((buf = (char *)malloc(bufsz)) == NULL) 1523 FATAL("out of memory in awkprintf"); 1524 y = a[0]->nnext; 1525 x = execute(a[0]); 1526 if ((len = format(&buf, &bufsz, getsval(x), y)) == -1) 1527 FATAL("printf string %.30s... too long. can't happen.", buf); 1528 tempfree(x); 1529 if (a[1] == NULL) { 1530 /* fputs(buf, stdout); */ 1531 fwrite(buf, len, 1, stdout); 1532 if (ferror(stdout)) 1533 FATAL("write error on stdout"); 1534 } else { 1535 fp = redirect(ptoi(a[1]), a[2]); 1536 /* fputs(buf, fp); */ 1537 fwrite(buf, len, 1, fp); 1538 fflush(fp); 1539 if (ferror(fp)) 1540 FATAL("write error on %s", filename(fp)); 1541 } 1542 free(buf); 1543 return (True); 1544 } 1545 1546 Cell * 1547 arith(Node **a, int n) /* a[0] + a[1], etc. also -a[0] */ 1548 { 1549 Awkfloat i, j = 0; 1550 double v; 1551 Cell *x, *y, *z; 1552 1553 x = execute(a[0]); 1554 i = getfval(x); 1555 tempfree(x); 1556 if (n != UMINUS && n != UPLUS) { 1557 y = execute(a[1]); 1558 j = getfval(y); 1559 tempfree(y); 1560 } 1561 z = gettemp(); 1562 switch (n) { 1563 case ADD: 1564 i += j; 1565 break; 1566 case MINUS: 1567 i -= j; 1568 break; 1569 case MULT: 1570 i *= j; 1571 break; 1572 case DIVIDE: 1573 if (j == 0) 1574 FATAL("division by zero"); 1575 i /= j; 1576 break; 1577 case MOD: 1578 if (j == 0) 1579 FATAL("division by zero in mod"); 1580 modf(i / j, &v); 1581 i = i - j * v; 1582 break; 1583 case UMINUS: 1584 i = -i; 1585 break; 1586 case UPLUS: /* handled by getfval(), above */ 1587 break; 1588 case POWER: 1589 if (j >= 0 && modf(j, &v) == 0.0) /* pos integer exponent */ 1590 i = ipow(i, (int)j); 1591 else 1592 i = pow_errcheck(i, j); 1593 break; 1594 default: /* cant happen */ 1595 FATAL("illegal arithmetic operator %d", n); 1596 } 1597 setfval(z, i); 1598 return (z); 1599 } 1600 1601 double 1602 ipow(double x, int n) /* x**n. ought to be done by pow, but isnt always */ 1603 { 1604 double v; 1605 1606 if (n <= 0) 1607 return 1; 1608 v = ipow(x, n / 2); 1609 if (n % 2 == 0) 1610 return v * v; 1611 else 1612 return x * v * v; 1613 } 1614 1615 Cell * 1616 incrdecr(Node **a, int n) /* a[0]++, etc */ 1617 { 1618 Cell *x, *z; 1619 int k; 1620 Awkfloat xf; 1621 1622 x = execute(a[0]); 1623 xf = getfval(x); 1624 k = (n == PREINCR || n == POSTINCR) ? 1 : -1; 1625 if (n == PREINCR || n == PREDECR) { 1626 setfval(x, xf + k); 1627 return (x); 1628 } 1629 z = gettemp(); 1630 setfval(z, xf); 1631 setfval(x, xf + k); 1632 tempfree(x); 1633 return (z); 1634 } 1635 1636 Cell * 1637 assign(Node **a, int n) /* a[0] = a[1], a[0] += a[1], etc */ 1638 { /* this is subtle; dont muck with it */ 1639 Cell *x, *y; 1640 Awkfloat xf, yf; 1641 double v; 1642 1643 y = execute(a[1]); 1644 x = execute(a[0]); 1645 if (n == ASSIGN) { /* ordinary assignment */ 1646 if (x == y && !(x->tval & (FLD | REC)) && x != nfloc) 1647 ; /* self-assignment: leave alone unless its a field or 1648 * NF */ 1649 else if ((y->tval & (STR | NUM)) == (STR | NUM)) { 1650 yf = getfval(y); 1651 setsval(x, getsval(y)); 1652 x->fval = yf; 1653 x->tval |= NUM; 1654 } else if (isstr(y)) 1655 setsval(x, getsval(y)); 1656 else if (isnum(y)) 1657 setfval(x, getfval(y)); 1658 else 1659 funnyvar(y, "read value of"); 1660 tempfree(y); 1661 return (x); 1662 } 1663 xf = getfval(x); 1664 yf = getfval(y); 1665 switch (n) { 1666 case ADDEQ: 1667 xf += yf; 1668 break; 1669 case SUBEQ: 1670 xf -= yf; 1671 break; 1672 case MULTEQ: 1673 xf *= yf; 1674 break; 1675 case DIVEQ: 1676 if ((x->tval & CON) != 0) 1677 FATAL("non-constant required for left side of /="); 1678 if (yf == 0) 1679 FATAL("division by zero in /="); 1680 xf /= yf; 1681 break; 1682 case MODEQ: 1683 if (yf == 0) 1684 FATAL("division by zero in %%="); 1685 modf(xf / yf, &v); 1686 xf = xf - yf * v; 1687 break; 1688 case POWEQ: 1689 if (yf >= 0 && modf(yf, &v) == 0.0) /* pos integer exponent */ 1690 xf = ipow(xf, (int)yf); 1691 else 1692 xf = pow_errcheck(xf, yf); 1693 break; 1694 default: 1695 FATAL("illegal assignment operator %d", n); 1696 break; 1697 } 1698 tempfree(y); 1699 setfval(x, xf); 1700 return (x); 1701 } 1702 1703 Cell * 1704 cat(Node **a, int q) /* a[0] cat a[1] */ 1705 { 1706 Cell *x, *y, *z; 1707 int n1, n2; 1708 char *s = NULL; 1709 int ssz = 0; 1710 1711 x = execute(a[0]); 1712 n1 = strlen(getsval(x)); 1713 adjbuf(&s, &ssz, n1 + 1, recsize, 0, "cat1"); 1714 memcpy(s, x->sval, n1); 1715 1716 tempfree(x); 1717 1718 y = execute(a[1]); 1719 n2 = strlen(getsval(y)); 1720 adjbuf(&s, &ssz, n1 + n2 + 1, recsize, 0, "cat2"); 1721 memcpy(s + n1, y->sval, n2); 1722 s[n1 + n2] = '\0'; 1723 1724 tempfree(y); 1725 1726 z = gettemp(); 1727 z->sval = s; 1728 z->tval = STR; 1729 1730 return (z); 1731 } 1732 1733 Cell * 1734 pastat(Node **a, int n) /* a[0] { a[1] } */ 1735 { 1736 Cell *x; 1737 1738 if (a[0] == NULL) 1739 x = execute(a[1]); 1740 else { 1741 x = execute(a[0]); 1742 if (istrue(x)) { 1743 tempfree(x); 1744 x = execute(a[1]); 1745 } 1746 } 1747 return x; 1748 } 1749 1750 Cell * 1751 dopa2(Node **a, int n) /* a[0], a[1] { a[2] } */ 1752 { 1753 Cell *x; 1754 int pair; 1755 1756 pair = ptoi(a[3]); 1757 if (pairstack[pair] == 0) { 1758 x = execute(a[0]); 1759 if (istrue(x)) 1760 pairstack[pair] = 1; 1761 tempfree(x); 1762 } 1763 if (pairstack[pair] == 1) { 1764 x = execute(a[1]); 1765 if (istrue(x)) 1766 pairstack[pair] = 0; 1767 tempfree(x); 1768 x = execute(a[2]); 1769 return (x); 1770 } 1771 return (False); 1772 } 1773 1774 Cell * 1775 split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ 1776 { 1777 Cell *x = NULL, *y, *ap; 1778 const char *s, *origs, *t; 1779 const char *fs = NULL; 1780 char *origfs = NULL; 1781 int sep; 1782 char temp, num[50]; 1783 int n, tempstat, arg3type; 1784 int j; 1785 double result; 1786 1787 y = execute(a[0]); /* source string */ 1788 origs = s = strdup(getsval(y)); 1789 tempfree(y); 1790 arg3type = ptoi(a[3]); 1791 if (a[2] == NULL) { /* BUG: CSV should override implicit fs but not explicit */ 1792 fs = getsval(fsloc); 1793 } else if (arg3type == STRING) { /* split(str,arr,"string") */ 1794 x = execute(a[2]); 1795 fs = origfs = strdup(getsval(x)); 1796 tempfree(x); 1797 } else if (arg3type == REGEXPR) { 1798 fs = "(regexpr)"; /* split(str,arr,/regexpr/) */ 1799 } else { 1800 FATAL("illegal type of split"); 1801 } 1802 sep = *fs; 1803 ap = execute(a[1]); /* array name */ 1804 /* BUG 7/26/22: this appears not to reset array: see c1/asplit */ 1805 freesymtab(ap); 1806 DPRINTF("split: s=|%s|, a=%s, sep=|%s|\n", s, NN(ap->nval), fs); 1807 ap->tval &= ~STR; 1808 ap->tval |= ARR; 1809 ap->sval = (char *)makesymtab(NSYMTAB); 1810 1811 n = 0; 1812 if (arg3type == REGEXPR && strlen((char *)((fa *)a[2])->restr) == 0) { 1813 /* split(s, a, // ); have to arrange that it looks like empty sep 1814 */ 1815 arg3type = 0; 1816 fs = ""; 1817 sep = 0; 1818 } 1819 if (*s != '\0' && (strlen(fs) > 1 || arg3type == REGEXPR)) { /* reg expr */ 1820 fa *pfa; 1821 if (arg3type == REGEXPR) { /* its ready already */ 1822 pfa = (fa *)a[2]; 1823 } else { 1824 pfa = makedfa(fs, 1); 1825 } 1826 if (nematch(pfa, s)) { 1827 tempstat = pfa->initstat; 1828 pfa->initstat = 2; 1829 do { 1830 n++; 1831 snprintf(num, sizeof(num), "%d", n); 1832 temp = *patbeg; 1833 setptr(patbeg, '\0'); 1834 if (is_number(s, &result)) 1835 setsymtab(num, s, result, STR | NUM, (Array *)ap->sval); 1836 else 1837 setsymtab(num, s, 0.0, STR, (Array *)ap->sval); 1838 setptr(patbeg, temp); 1839 s = patbeg + patlen; 1840 if (*(patbeg + patlen - 1) == '\0' || *s == '\0') { 1841 n++; 1842 snprintf(num, sizeof(num), "%d", n); 1843 setsymtab(num, "", 0.0, STR, (Array *)ap->sval); 1844 pfa->initstat = tempstat; 1845 goto spdone; 1846 } 1847 } while (nematch(pfa, s)); 1848 pfa->initstat = tempstat; /* bwk: has to be here to reset */ 1849 /* cf gsub and refldbld */ 1850 } 1851 n++; 1852 snprintf(num, sizeof(num), "%d", n); 1853 if (is_number(s, &result)) 1854 setsymtab(num, s, result, STR | NUM, (Array *)ap->sval); 1855 else 1856 setsymtab(num, s, 0.0, STR, (Array *)ap->sval); 1857 spdone: 1858 pfa = NULL; 1859 1860 } else if (a[2] == NULL && CSV) { /* CSV only if no explicit separator */ 1861 char *newt = (char *)malloc(strlen(s) + 1); /* for building new string; reuse for each field */ 1862 if (newt == NULL) 1863 FATAL("out of space in split"); 1864 for (;;) { 1865 char *fr = newt; 1866 n++; 1867 if (*s == '"') { /* start of "..." */ 1868 for (s++; *s != '\0';) { 1869 if (*s == '"' && s[1] != '\0' && s[1] == '"') { 1870 s += 2; /* doubled quote */ 1871 *fr++ = '"'; 1872 } else if (*s == '"' && (s[1] == '\0' || s[1] == ',')) { 1873 s++; /* skip over closing quote 1874 */ 1875 break; 1876 } else { 1877 *fr++ = *s++; 1878 } 1879 } 1880 *fr++ = 0; 1881 } else { /* unquoted field */ 1882 while (*s != ',' && *s != '\0') 1883 *fr++ = *s++; 1884 *fr++ = 0; 1885 } 1886 snprintf(num, sizeof(num), "%d", n); 1887 if (is_number(newt, &result)) 1888 setsymtab(num, newt, result, STR | NUM, (Array *)ap->sval); 1889 else 1890 setsymtab(num, newt, 0.0, STR, (Array *)ap->sval); 1891 if (*s++ == '\0') 1892 break; 1893 } 1894 free(newt); 1895 1896 } else if (!CSV && sep == ' ') { /* usual case: split on white space */ 1897 for (n = 0;;) { 1898 #define ISWS(c) ((c) == ' ' || (c) == '\t' || (c) == '\n') 1899 while (ISWS(*s)) 1900 s++; 1901 if (*s == '\0') 1902 break; 1903 n++; 1904 t = s; 1905 do 1906 s++; 1907 while (*s != '\0' && !ISWS(*s)); 1908 temp = *s; 1909 setptr(s, '\0'); 1910 snprintf(num, sizeof(num), "%d", n); 1911 if (is_number(t, &result)) 1912 setsymtab(num, t, result, STR | NUM, (Array *)ap->sval); 1913 else 1914 setsymtab(num, t, 0.0, STR, (Array *)ap->sval); 1915 setptr(s, temp); 1916 if (*s != '\0') 1917 s++; 1918 } 1919 1920 } else if (sep == 0) { /* new: split(s, a, "") => 1 char/elem */ 1921 for (n = 0; *s != '\0'; s += u8_nextlen(s)) { 1922 char buf[10]; 1923 n++; 1924 snprintf(num, sizeof(num), "%d", n); 1925 1926 for (j = 0; j < u8_nextlen(s); j++) { 1927 buf[j] = s[j]; 1928 } 1929 buf[j] = '\0'; 1930 1931 if (isdigit((uschar)buf[0])) 1932 setsymtab(num, buf, atof(buf), STR | NUM, (Array *)ap->sval); 1933 else 1934 setsymtab(num, buf, 0.0, STR, (Array *)ap->sval); 1935 } 1936 1937 } else if (*s != '\0') { /* some random single character */ 1938 for (;;) { 1939 n++; 1940 t = s; 1941 while (*s != sep && *s != '\0') 1942 s++; 1943 temp = *s; 1944 setptr(s, '\0'); 1945 snprintf(num, sizeof(num), "%d", n); 1946 if (is_number(t, &result)) 1947 setsymtab(num, t, result, STR | NUM, (Array *)ap->sval); 1948 else 1949 setsymtab(num, t, 0.0, STR, (Array *)ap->sval); 1950 setptr(s, temp); 1951 if (*s++ == '\0') 1952 break; 1953 } 1954 } 1955 tempfree(ap); 1956 xfree(origs); 1957 xfree(origfs); 1958 x = gettemp(); 1959 x->tval = NUM; 1960 x->fval = n; 1961 return (x); 1962 } 1963 1964 Cell * 1965 condexpr(Node **a, int n) /* a[0] ? a[1] : a[2] */ 1966 { 1967 Cell *x; 1968 1969 x = execute(a[0]); 1970 if (istrue(x)) { 1971 tempfree(x); 1972 x = execute(a[1]); 1973 } else { 1974 tempfree(x); 1975 x = execute(a[2]); 1976 } 1977 return (x); 1978 } 1979 1980 Cell * 1981 ifstat(Node **a, int n) /* if (a[0]) a[1]; else a[2] */ 1982 { 1983 Cell *x; 1984 1985 x = execute(a[0]); 1986 if (istrue(x)) { 1987 tempfree(x); 1988 x = execute(a[1]); 1989 } else if (a[2] != NULL) { 1990 tempfree(x); 1991 x = execute(a[2]); 1992 } 1993 return (x); 1994 } 1995 1996 Cell * 1997 whilestat(Node **a, int n) /* while (a[0]) a[1] */ 1998 { 1999 Cell *x; 2000 2001 for (;;) { 2002 x = execute(a[0]); 2003 if (!istrue(x)) 2004 return (x); 2005 tempfree(x); 2006 x = execute(a[1]); 2007 if (isbreak(x)) { 2008 x = True; 2009 return (x); 2010 } 2011 if (isnext(x) || isexit(x) || isret(x)) 2012 return (x); 2013 tempfree(x); 2014 } 2015 } 2016 2017 Cell * 2018 dostat(Node **a, int n) /* do a[0]; while(a[1]) */ 2019 { 2020 Cell *x; 2021 2022 for (;;) { 2023 x = execute(a[0]); 2024 if (isbreak(x)) 2025 return True; 2026 if (isnext(x) || isexit(x) || isret(x)) 2027 return (x); 2028 tempfree(x); 2029 x = execute(a[1]); 2030 if (!istrue(x)) 2031 return (x); 2032 tempfree(x); 2033 } 2034 } 2035 2036 Cell * 2037 forstat(Node **a, int n) /* for (a[0]; a[1]; a[2]) a[3] */ 2038 { 2039 Cell *x; 2040 2041 x = execute(a[0]); 2042 tempfree(x); 2043 for (;;) { 2044 if (a[1] != NULL) { 2045 x = execute(a[1]); 2046 if (!istrue(x)) 2047 return (x); 2048 else 2049 tempfree(x); 2050 } 2051 x = execute(a[3]); 2052 if (isbreak(x)) /* turn off break */ 2053 return True; 2054 if (isnext(x) || isexit(x) || isret(x)) 2055 return (x); 2056 tempfree(x); 2057 x = execute(a[2]); 2058 tempfree(x); 2059 } 2060 } 2061 2062 Cell * 2063 instat(Node **a, int n) /* for (a[0] in a[1]) a[2] */ 2064 { 2065 Cell *x, *vp, *arrayp, *cp, *ncp; 2066 Array *tp; 2067 int i; 2068 2069 vp = execute(a[0]); 2070 arrayp = execute(a[1]); 2071 if (!isarr(arrayp)) { 2072 return True; 2073 } 2074 tp = (Array *)arrayp->sval; 2075 tempfree(arrayp); 2076 for (i = 0; i < tp->size; i++) { /* this routine knows too much */ 2077 for (cp = tp->tab[i]; cp != NULL; cp = ncp) { 2078 setsval(vp, cp->nval); 2079 ncp = cp->cnext; 2080 x = execute(a[2]); 2081 if (isbreak(x)) { 2082 tempfree(vp); 2083 return True; 2084 } 2085 if (isnext(x) || isexit(x) || isret(x)) { 2086 tempfree(vp); 2087 return (x); 2088 } 2089 tempfree(x); 2090 } 2091 } 2092 return True; 2093 } 2094 2095 static char * 2096 nawk_convert(const char *s, int (*fun_c)(int), wint_t (*fun_wc)(wint_t)) 2097 { 2098 char *buf = NULL; 2099 char *pbuf = NULL; 2100 const char *ps = NULL; 2101 size_t n = 0; 2102 wchar_t wc; 2103 const size_t sz = awk_mb_cur_max; 2104 2105 if (sz == 1) { 2106 buf = tostring(s); 2107 2108 for (pbuf = buf; *pbuf; pbuf++) 2109 *pbuf = fun_c((uschar)*pbuf); 2110 2111 return buf; 2112 } else { 2113 /* upper/lower character may be shorter/longer */ 2114 buf = tostringN(s, strlen(s) * sz + 1); 2115 2116 (void)mbtowc(NULL, NULL, 0); /* reset internal state */ 2117 /* the ! keeps warn_unused_result quiet, as (void) alone does not */ 2118 (void)!wctomb(NULL, L'\0'); /* reset internal state */ 2119 2120 ps = s; 2121 pbuf = buf; 2122 while (n = mbtowc(&wc, ps, sz), n > 0 && n != (size_t)-1 && n != (size_t)-2) { 2123 ps += n; 2124 2125 n = wctomb(pbuf, fun_wc(wc)); 2126 if (n == (size_t)-1) 2127 FATAL("illegal wide character %s", s); 2128 2129 pbuf += n; 2130 } 2131 2132 *pbuf = '\0'; 2133 2134 if (n) 2135 FATAL("illegal byte sequence %s", s); 2136 2137 return buf; 2138 } 2139 } 2140 2141 #ifdef __DJGPP__ 2142 static wint_t 2143 towupper(wint_t wc) 2144 { 2145 if (wc >= 0 && wc < 256) 2146 return toupper(wc & 0xFF); 2147 2148 return wc; 2149 } 2150 2151 static wint_t 2152 towlower(wint_t wc) 2153 { 2154 if (wc >= 0 && wc < 256) 2155 return tolower(wc & 0xFF); 2156 2157 return wc; 2158 } 2159 #endif 2160 2161 static char * 2162 nawk_toupper(const char *s) 2163 { 2164 return nawk_convert(s, toupper, towupper); 2165 } 2166 2167 static char * 2168 nawk_tolower(const char *s) 2169 { 2170 return nawk_convert(s, tolower, towlower); 2171 } 2172 2173 Cell * 2174 bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */ 2175 { 2176 Cell *x, *y; 2177 Awkfloat u = 0; 2178 int t; 2179 Awkfloat tmp; 2180 char *buf; 2181 Node *nextarg; 2182 FILE *fp; 2183 int estatus = 0; 2184 2185 t = ptoi(a[0]); 2186 x = execute(a[1]); 2187 nextarg = a[1]->nnext; 2188 switch (t) { 2189 case FLENGTH: 2190 if (isarr(x)) 2191 u = ((Array *)x->sval)->nelem; /* GROT. should be function */ 2192 else 2193 u = u8_strlen(getsval(x)); 2194 break; 2195 case FLOG: 2196 u = log_errcheck(getfval(x)); 2197 break; 2198 case FINT: 2199 modf(getfval(x), &u); 2200 break; 2201 case FEXP: 2202 u = exp_errcheck(getfval(x)); 2203 break; 2204 case FSQRT: 2205 u = sqrt_errcheck(getfval(x)); 2206 break; 2207 case FSIN: 2208 u = sin(getfval(x)); 2209 break; 2210 case FCOS: 2211 u = cos(getfval(x)); 2212 break; 2213 case FATAN: 2214 if (nextarg == NULL) { 2215 WARNING("atan2 requires two arguments; returning 1.0"); 2216 u = 1.0; 2217 } else { 2218 y = execute(a[1]->nnext); 2219 u = atan2(getfval(x), getfval(y)); 2220 tempfree(y); 2221 nextarg = nextarg->nnext; 2222 } 2223 break; 2224 case FSYSTEM: 2225 fflush(stdout); /* in case something is buffered already */ 2226 estatus = wsystem(getsval(x)); 2227 u = estatus; 2228 break; 2229 case FRAND: 2230 /* random() returns numbers in [0..2^31-1] 2231 * in order to get a number in [0, 1), divide it by 2^31 2232 */ 2233 do { 2234 /* exact if awkfloat wide enough */ 2235 u = (Awkfloat)random(); 2236 u /= 0x80000000; /* should be exact */ 2237 } while (u >= 1.0); /* in case awkfloat is narrow */ 2238 break; 2239 case FSRAND: 2240 if (isrec(x)) /* no argument provided */ 2241 u = time((time_t *)0); 2242 else 2243 u = getfval(x); 2244 tmp = u; 2245 srandom((unsigned long)u); 2246 u = srand_seed; 2247 srand_seed = tmp; 2248 break; 2249 case FTOUPPER: 2250 case FTOLOWER: 2251 if (t == FTOUPPER) 2252 buf = nawk_toupper(getsval(x)); 2253 else 2254 buf = nawk_tolower(getsval(x)); 2255 tempfree(x); 2256 x = gettemp(); 2257 setsval(x, buf); 2258 free(buf); 2259 return x; 2260 case FFLUSH: 2261 if (isrec(x) || strlen(getsval(x)) == 0) { 2262 flush_all(); /* fflush() or fflush("") -> all */ 2263 u = 0; 2264 } else if ((fp = openfile(FFLUSH, getsval(x), NULL)) == NULL) 2265 u = EOF; 2266 else 2267 u = fflush(fp); 2268 break; 2269 default: /* cant happen */ 2270 FATAL("illegal function type %d", t); 2271 break; 2272 } 2273 tempfree(x); 2274 x = gettemp(); 2275 setfval(x, u); 2276 if (nextarg != NULL) { 2277 WARNING("warning: function has too many arguments"); 2278 for (; nextarg; nextarg = nextarg->nnext) { 2279 y = execute(nextarg); 2280 tempfree(y); 2281 } 2282 } 2283 return (x); 2284 } 2285 2286 Cell * 2287 printstat(Node **a, int n) /* print a[0] */ 2288 { 2289 Node *x; 2290 Cell *y; 2291 FILE *fp; 2292 2293 if (a[1] == NULL) /* a[1] is redirection operator, a[2] is file */ 2294 fp = stdout; 2295 else 2296 fp = redirect(ptoi(a[1]), a[2]); 2297 for (x = a[0]; x != NULL; x = x->nnext) { 2298 y = execute(x); 2299 fputs(getpssval(y), fp); 2300 tempfree(y); 2301 if (x->nnext == NULL) 2302 fputs(getsval(orsloc), fp); 2303 else 2304 fputs(getsval(ofsloc), fp); 2305 } 2306 if (a[1] != NULL) 2307 fflush(fp); 2308 if (ferror(fp)) 2309 FATAL("write error on %s", filename(fp)); 2310 return (True); 2311 } 2312 2313 Cell * 2314 nullproc(Node **a, int n) 2315 { 2316 return 0; 2317 } 2318 2319 FILE * 2320 redirect(int a, Node *b) /* set up all i/o redirections */ 2321 { 2322 FILE *fp; 2323 Cell *x; 2324 char *fname; 2325 2326 x = execute(b); 2327 fname = getsval(x); 2328 fp = openfile(a, fname, NULL); 2329 if (fp == NULL) 2330 FATAL("can't open file %s", fname); 2331 tempfree(x); 2332 return fp; 2333 } 2334 2335 struct files { 2336 FILE *fp; 2337 const char *fname; 2338 int mode; /* '|', 'a', 'w' => LE/LT, GT */ 2339 } *files; 2340 2341 size_t nfiles; 2342 2343 static void 2344 stdinit(void) /* in case stdin, etc., are not constants */ 2345 { 2346 nfiles = FOPEN_MAX; 2347 files = (struct files *)calloc(nfiles, sizeof(*files)); 2348 if (files == NULL) 2349 FATAL("can't allocate file memory for %zu files", nfiles); 2350 files[0].fp = stdin; 2351 files[0].fname = tostring("/dev/stdin"); 2352 files[0].mode = LT; 2353 files[1].fp = stdout; 2354 files[1].fname = tostring("/dev/stdout"); 2355 files[1].mode = GT; 2356 files[2].fp = stderr; 2357 files[2].fname = tostring("/dev/stderr"); 2358 files[2].mode = GT; 2359 } 2360 2361 FILE * 2362 openfile(int a, const char *us, bool *pnewflag) 2363 { 2364 const char *s = us; 2365 size_t i; 2366 int m; 2367 FILE *fp = NULL; 2368 struct stat sbuf; 2369 2370 if (*s == '\0') 2371 FATAL("null file name in print or getline"); 2372 2373 for (i = 0; i < nfiles; i++) 2374 if (files[i].fname && strcmp(s, files[i].fname) == 0 2375 && (a == files[i].mode || (a == APPEND && files[i].mode == GT) || a == FFLUSH)) { 2376 if (pnewflag) 2377 *pnewflag = false; 2378 return files[i].fp; 2379 } 2380 if (a == FFLUSH) /* didnt find it, so dont create it! */ 2381 return NULL; 2382 for (i = 0; i < nfiles; i++) 2383 if (files[i].fp == NULL) 2384 break; 2385 if (i >= nfiles) { 2386 struct files *nf; 2387 size_t nnf = nfiles + FOPEN_MAX; 2388 nf = (struct files *)realloc(files, nnf * sizeof(*nf)); 2389 if (nf == NULL) 2390 FATAL("cannot grow files for %s and %zu files", s, nnf); 2391 memset(&nf[nfiles], 0, FOPEN_MAX * sizeof(*nf)); 2392 nfiles = nnf; 2393 files = nf; 2394 } 2395 2396 fflush(stdout); /* force a semblance of order */ 2397 2398 /* dont try to read or write a directory */ 2399 if (a == LT || a == GT || a == APPEND) 2400 if (stat(s, &sbuf) == 0 && S_ISDIR(sbuf.st_mode)) 2401 return NULL; 2402 2403 m = a; 2404 if (a == GT) { 2405 fp = fopen(s, "w"); 2406 } else if (a == APPEND) { 2407 fp = fopen(s, "a"); 2408 m = GT; /* so can mix > and >> */ 2409 } else if (a == '|') { /* output pipe */ 2410 fp = wpopen(s, NULL, "w"); 2411 } else if (a == LE) { /* input pipe */ 2412 fp = wpopen(s, NULL, "r"); 2413 } else if (a == LT) { /* getline <file */ 2414 fp = strcmp(s, "-") == 0 ? stdin : fopen(s, "r"); /* "-" is stdin */ 2415 } else /* cant happen */ 2416 FATAL("illegal redirection %d", a); 2417 if (fp != NULL) { 2418 files[i].fname = tostring(s); 2419 files[i].fp = fp; 2420 files[i].mode = m; 2421 if (pnewflag) 2422 *pnewflag = true; 2423 if (fp != stdin && fp != stdout && fp != stderr) 2424 (void)fcntl(fileno(fp), F_SETFD, FD_CLOEXEC); 2425 } 2426 return fp; 2427 } 2428 2429 const char * 2430 filename(FILE *fp) 2431 { 2432 size_t i; 2433 2434 for (i = 0; i < nfiles; i++) 2435 if (fp == files[i].fp) 2436 return files[i].fname; 2437 return "???"; 2438 } 2439 2440 Cell * 2441 closefile(Node **a, int n) 2442 { 2443 Cell *x; 2444 size_t i; 2445 bool stat; 2446 2447 x = execute(a[0]); 2448 getsval(x); 2449 stat = true; 2450 for (i = 0; i < nfiles; i++) { 2451 if (!files[i].fname || strcmp(x->sval, files[i].fname) != 0) 2452 continue; 2453 if (files[i].mode == GT || files[i].mode == '|') 2454 fflush(files[i].fp); 2455 if (ferror(files[i].fp)) { 2456 if ((files[i].mode == GT && files[i].fp != stderr) || files[i].mode == '|') 2457 FATAL("write error on %s", files[i].fname); 2458 else 2459 WARNING("i/o error occurred on %s", files[i].fname); 2460 } 2461 if (files[i].fp == stdin || files[i].fp == stdout || files[i].fp == stderr) 2462 stat = freopen("/dev/null", "r+", files[i].fp) == NULL; 2463 else if (files[i].mode == '|' || files[i].mode == LE) 2464 stat = wpclose(files[i].fp) == -1; 2465 else 2466 stat = fclose(files[i].fp) == EOF; 2467 if (stat) 2468 WARNING("i/o error occurred closing %s", files[i].fname); 2469 xfree(files[i].fname); 2470 files[i].fname = NULL; /* watch out for ref thru this */ 2471 files[i].fp = NULL; 2472 break; 2473 } 2474 tempfree(x); 2475 x = gettemp(); 2476 setfval(x, (Awkfloat)(stat ? -1 : 0)); 2477 return (x); 2478 } 2479 2480 void 2481 closeall(void) 2482 { 2483 size_t i; 2484 bool stat = false; 2485 2486 for (i = 0; i < nfiles; i++) { 2487 if (!files[i].fp) 2488 continue; 2489 if (files[i].mode == GT || files[i].mode == '|') 2490 fflush(files[i].fp); 2491 if (ferror(files[i].fp)) { 2492 if ((files[i].mode == GT && files[i].fp != stderr) || files[i].mode == '|') 2493 FATAL("write error on %s", files[i].fname); 2494 else 2495 WARNING("i/o error occurred on %s", files[i].fname); 2496 } 2497 if (files[i].fp == stdin || files[i].fp == stdout || files[i].fp == stderr) 2498 continue; 2499 if (files[i].mode == '|' || files[i].mode == LE) 2500 stat = wpclose(files[i].fp) == -1; 2501 else 2502 stat = fclose(files[i].fp) == EOF; 2503 if (stat) 2504 WARNING("i/o error occurred while closing %s", files[i].fname); 2505 } 2506 } 2507 2508 static void 2509 flush_all(void) 2510 { 2511 size_t i; 2512 2513 for (i = 0; i < nfiles; i++) 2514 if (files[i].fp) 2515 fflush(files[i].fp); 2516 } 2517 2518 void backsub(char **pb_ptr, const char **sptr_ptr); 2519 2520 Cell * 2521 dosub(Node **a, int subop) /* sub and gsub */ 2522 { 2523 fa *pfa; 2524 int tempstat = 0; 2525 char *repl; 2526 Cell *x; 2527 2528 char *buf = NULL; 2529 char *pb = NULL; 2530 int bufsz = recsize; 2531 2532 const char *r, *s; 2533 const char *start; 2534 const char *noempty = NULL; /* empty match disallowed here */ 2535 size_t m = 0; /* match count */ 2536 size_t whichm = 0; /* which match to select, 0 = global */ 2537 int mtype; /* match type */ 2538 2539 if (a[0] == NULL) { /* 0 => a[1] is already-compiled regexpr */ 2540 pfa = (fa *)a[1]; 2541 } else { 2542 x = execute(a[1]); 2543 pfa = makedfa(getsval(x), 1); 2544 tempfree(x); 2545 } 2546 2547 x = execute(a[2]); /* replacement string */ 2548 repl = tostring(getsval(x)); 2549 tempfree(x); 2550 2551 switch (subop) { 2552 case SUB: 2553 whichm = 1; 2554 x = execute(a[3]); /* source string */ 2555 break; 2556 case GSUB: 2557 whichm = 0; 2558 x = execute(a[3]); /* source string */ 2559 break; 2560 default: 2561 FATAL("dosub: unrecognized subop: %d", subop); 2562 } 2563 2564 start = getsval(x); 2565 while (pmatch(pfa, start)) { 2566 if (buf == NULL) { 2567 if ((pb = buf = (char *)malloc(bufsz)) == NULL) 2568 FATAL("out of memory in dosub"); 2569 tempstat = pfa->initstat; 2570 pfa->initstat = 2; 2571 } 2572 2573 /* match types */ 2574 #define MT_IGNORE 0 /* unselected or invalid */ 2575 #define MT_INSERT 1 /* selected, empty */ 2576 #define MT_REPLACE 2 /* selected, not empty */ 2577 2578 /* an empty match just after replacement is invalid */ 2579 2580 if (patbeg == noempty && patlen == 0) { 2581 mtype = MT_IGNORE; /* invalid, not counted */ 2582 } else if (whichm == ++m || whichm == 0) { 2583 mtype = patlen ? MT_REPLACE : MT_INSERT; 2584 } else { 2585 mtype = MT_IGNORE; /* unselected, but counted */ 2586 } 2587 2588 /* leading text: */ 2589 if (patbeg > start) { 2590 adjbuf(&buf, &bufsz, (pb - buf) + (patbeg - start), recsize, &pb, "dosub"); 2591 s = start; 2592 while (s < patbeg) 2593 *pb++ = *s++; 2594 } 2595 2596 if (mtype == MT_IGNORE) 2597 goto matching_text; /* skip replacement text */ 2598 2599 r = repl; 2600 while (*r != 0) { 2601 adjbuf(&buf, &bufsz, 5 + pb - buf, recsize, &pb, "dosub"); 2602 if (*r == '\\') { 2603 backsub(&pb, &r); 2604 } else if (*r == '&') { 2605 r++; 2606 adjbuf(&buf, &bufsz, 1 + patlen + pb - buf, recsize, &pb, "dosub"); 2607 for (s = patbeg; s < patbeg + patlen;) 2608 *pb++ = *s++; 2609 } else { 2610 *pb++ = *r++; 2611 } 2612 } 2613 2614 matching_text: 2615 if (mtype == MT_REPLACE || *patbeg == '\0') 2616 goto next_search; /* skip matching text */ 2617 2618 if (patlen == 0) 2619 patlen = u8_nextlen(patbeg); 2620 adjbuf(&buf, &bufsz, (pb - buf) + patlen, recsize, &pb, "dosub"); 2621 s = patbeg; 2622 while (s < patbeg + patlen) 2623 *pb++ = *s++; 2624 2625 next_search: 2626 start = patbeg + patlen; 2627 if (m == whichm || *patbeg == '\0') 2628 break; 2629 if (mtype == MT_REPLACE) 2630 noempty = start; 2631 2632 #undef MT_IGNORE 2633 #undef MT_INSERT 2634 #undef MT_REPLACE 2635 } 2636 2637 if (repl) { 2638 free(repl); 2639 } 2640 2641 if (buf != NULL) { 2642 pfa->initstat = tempstat; 2643 2644 /* trailing text */ 2645 adjbuf(&buf, &bufsz, 1 + strlen(start) + pb - buf, 0, &pb, "dosub"); 2646 while ((*pb++ = *start++) != '\0') 2647 ; 2648 2649 setsval(x, buf); 2650 free(buf); 2651 } 2652 2653 tempfree(x); 2654 x = gettemp(); 2655 x->tval = NUM; 2656 x->fval = m; 2657 return x; 2658 } 2659 2660 void 2661 backsub(char **pb_ptr, const char **sptr_ptr) /* handle \\& variations */ 2662 { /* sptr[0] == '\\' */ 2663 char *pb = *pb_ptr; 2664 const char *sptr = *sptr_ptr; 2665 static bool first = true; 2666 static bool do_posix = false; 2667 2668 if (first) { 2669 first = false; 2670 do_posix = (getenv("POSIXLY_CORRECT") != NULL); 2671 } 2672 2673 if (sptr[1] == '\\') { 2674 if (sptr[2] == '\\' && sptr[3] == '&') { /* \\\& -> \& */ 2675 *pb++ = '\\'; 2676 *pb++ = '&'; 2677 sptr += 4; 2678 } else if (sptr[2] == '&') { /* \\& -> \ + matched */ 2679 *pb++ = '\\'; 2680 sptr += 2; 2681 } else if (do_posix) { /* \\x -> \x */ 2682 sptr++; 2683 *pb++ = *sptr++; 2684 } else { /* \\x -> \\x */ 2685 *pb++ = *sptr++; 2686 *pb++ = *sptr++; 2687 } 2688 } else if (sptr[1] == '&') { /* literal & */ 2689 sptr++; 2690 *pb++ = *sptr++; 2691 } else /* literal \ */ 2692 *pb++ = *sptr++; 2693 2694 *pb_ptr = pb; 2695 *sptr_ptr = sptr; 2696 } 2697 2698 static char * 2699 wide_char_to_byte_str(int rune, size_t *outlen) 2700 { 2701 static char buf[5]; 2702 int len; 2703 2704 if (rune < 0 || rune > 0x10FFFF) 2705 return NULL; 2706 2707 memset(buf, 0, sizeof(buf)); 2708 2709 len = 0; 2710 if (rune <= 0x0000007F) { 2711 buf[len++] = rune; 2712 } else if (rune <= 0x000007FF) { 2713 /* 110xxxxx 10xxxxxx */ 2714 buf[len++] = 0xC0 | (rune >> 6); 2715 buf[len++] = 0x80 | (rune & 0x3F); 2716 } else if (rune <= 0x0000FFFF) { 2717 /* 1110xxxx 10xxxxxx 10xxxxxx */ 2718 buf[len++] = 0xE0 | (rune >> 12); 2719 buf[len++] = 0x80 | ((rune >> 6) & 0x3F); 2720 buf[len++] = 0x80 | (rune & 0x3F); 2721 2722 } else { 2723 /* 0x00010000 - 0x10ffff 2724 * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ 2725 buf[len++] = 0xF0 | (rune >> 18); 2726 buf[len++] = 0x80 | ((rune >> 12) & 0x3F); 2727 buf[len++] = 0x80 | ((rune >> 6) & 0x3F); 2728 buf[len++] = 0x80 | (rune & 0x3F); 2729 } 2730 2731 *outlen = len; 2732 buf[len++] = '\0'; 2733 2734 return buf; 2735 }