diff --git a/ChangeLog b/ChangeLog index 6ce9417c10da..dea4ed7e3187 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,329 +1,353 @@ 2020-07-30 Arnold D. Robbins By fiat, we use bison for $(YACC). Trying to accommodate different versions didn't work. * makefile: Significant cleanup. Replace all ytab* references with awkgram.tab.* and simplify definition of YACC. * .gitignore: Remove ytab* references. * b.c, lex.c, maketab.c, parse.c, run.c: Replace include of ytab.h with awkgram.tab.h. * lib.c, main.c, tran.c: Remove include of ytab.h, wasn't needed. 2020-01-20 Arnold D. Robbins * run.c (openfile): Set the close-on-exec flag for file and pipe redirections that aren't stdin/stdout/stderr. 2020-01-06 Arnold D. Robbins Minor fixes. * b.c (replace_repeat): Turn init_q back into an int. * lex.c (string): Use \a instead of \007. * tran.c (catstr): Use snprintf instead of sprintf. 2020-01-01 Arnold D. Robbins * tran.c (syminit, arginit, envinit): Free sval member before setting it. Thanks to valgrind. * b.c: Small formatting cleanups in several routines. 2019-12-27 Arnold D. Robbins * b.c (replace_repeat): Fix a bug whereby a{0,3} could match four a's. Thanks to Anonymous AWK fan for the report. Also, minor code formatting cleanups. * testdir/T.int-expr: New file. 2019-12-11 Arnold D. Robbins * README: Renamed to ... * README.md: ... this. Cleaned up some as well, including moving to Markdown. 2019-11-08 Arnold D. Robbins * test/T.chem: Use $oldawk instead of hardwiring 'awk'. * test/T.lilly: Remove gawk warnings from output, improves portability. +2019-10-17 Arnold D. Robbins + + Pull in systime() and strftime() from the NetBSD awk. + + * awk.1: Document the functions. + * run.c (bltin): Implement the functions. + * awk.h: Add defines for systime and strftime. + * lex.c: Add support for systime and strftime. + +2019-10-07 Arnold D. Robbins + + Integrate features from different *BSD versions of awk. + Gensub support from NetBSD. Bitwise functions from OpenBSD. + + * awk.h: Add defines for and, or, xor, compl, lshift and rshift. + * awkgram.y: Add support for gensub. + * maketab.c: Ditto. + * lex.c: Add support for gensub and bitwise functions. + * parse.c (node5, op5): New functions. + * proto.h (node5, op5): New declarations. + * run.c (bltin): Implement the bitwise functions. + (gensub): New function. + * awk.1: Document additional functions. + 2019-10-07 Arnold D. Robbins * b.c (fnematch): Change type of pbuf from unsigned char to char. * proto.h (fnematch): Ditto. 2019-10-06 Arnold D. Robbins * lib.c (readrec): Allow RS a regular expression. Imported the code from the NetBSD awk. * b.c (fnematch): New function for implementing the feature. * awk.1: Updated. * main.c (version): Updated. 2019-06-24 Arnold D. Robbins * makefile: Revise to take into account there is no more awktest.tar, add targets 'check' and 'test', and also 'testclean' to clean up after test run. Have 'clean' and 'cleaner' depend upon 'testclean'. 2019-06-23 Arnold D. Robbins * testdir: Extracted from awktest.tar and added to Git. * awktest.tar: Removed. 2019-06-06 Arnold D. Robbins * awk.1: Fix a typo, minor edits. 2019-06-05 Arnold D. Robbins * b.c (relex): Count parentheses and treat umatched right paren as a literal character. * awktest.tar (testdir/T.re): Added a test case. * main.c (version): Updated. 2019-05-29 Arnold D. Robbins * lib.c (isclvar): Remove check for additional '=' after first one. No longer needed. 2019-01-26 Arnold D. Robbins * main.c (version): Updated. 2019-01-25 Arnold D. Robbins * run.c (awkgetline): Check for numeric value in all getline variants. See the numeric-getline.* files in bugs-fixed directory. 2018-08-29 Arnold D. Robbins * REGRESS: Check for existence of a.out. If not there, run make. Enable core dumps for T.arnold system status test to work on MacOS X. 2018-08-22 Arnold D. Robbins * awktest.tar (testdir/T.expr): Fix test for unary plus. 2018-08-22 Arnold D. Robbins * REGRESS: Extract tests if necessary, set PATH to include '.'. * regdir/beebe.tar (Makefile): Fix longwrds test to prefix sort with LC_ALL=C. * awktest.tar: Updated from fixed test suite, directory it extracts is now called 'testdir' to match what's in top-level REGRESS script. * regdir: Removed, as Brian wants to keep the test suite in the tar file. 2018-08-22 Arnold D. Robbins * FIXES, lib.c, run.c, makefile, main.c: Merge from Brian's tree. * REGRESS: New file, from Brian. * awktest.tar: Restored from Brian's tree. 2018-08-22 Arnold D. Robbins * awkgram.y (UPLUS): New token. In the grammar, call op1() with it. * maketab.c (proc): Add entry for UPLUS. * run.c (arith): Handle UPLUS. * main.c (version): Updated. * bugs-fixed/unary-plus.awk, bugs-fixed/unary-plus.bad, bugs-fixed/unary-plus.ok: New files. 2018-08-10 Arnold D. Robbins * TODO: Updated. * awk.1: Improve use of macros, add some additional explanation in a few places, alphabetize list of variables. 2018-08-08 Arnold D. Robbins * awk.h (Cell): Add new field `fmt' to track xFMT value used for a string conversion. [CONVC, CONVO]: New flag macros. * bugs-fixed/README: Updated. * bugs-fixed/string-conv.awk, bugs-fixed/string-conv.bad, bugs-fixed/string-conv.ok: New files. * main.c (version): Updated. * proto.h (flags2str): Add declaration. * tran.c (setfval): Clear CONVC and CONVO flags and set vp->fmt to NULL. (setsval): Ditto. Add large comment and new code to manage correct conversion of number to string based on various flags and the value of vp->fmt. The idea is to not convert again if xFMT is the same as before and we're doing the same conversion. Otherwise, clear the old flags, set the new, and reconvert. (flags2str): New function. For debug prints and for use from a debugger. 2018-08-05 Arnold D. Robbins Fix filename conflicts in regdir where the only difference was in letter case. This caused problems on Windows systems. * regdir/Compare.T1: Renamed from regdir/Compare.T. * regdir/t.delete0: Renamed from regdir/t.delete. * regdir/t.getline1: Renamed from regdir/t.getline. * regdir/t.redir1: Renamed from regdir/t.redir. * regdir/t.split1: Renamed from regdir/t.split. * regdir/t.sub0: Renamed from regdir/t.sub. * regdir/REGRESS: Adjusted. 2018-08-04 Arnold D. Robbins With scalpel, tweasers, magnifying glass and bated breath, borrow code from the NetBSD version of nawk to fix the years-old bug whereby decrementing the value of NF did not change the record. * lib.c (fldbld): Set donerec to 1 when done. (setlastfld): New function. * proto.h (setlastfld): Add declaration. * run.c (copycell): Make code smarter about flags (from NetBSD code). * tran.c (setfree): New function. * tran.c (setfval): Normalize negative zero to positive zero. If setting NF, clear donerec and call setlastfld(). (setsval): Remove call to save_old_OFS(). If setting OFS, call recbld(). If setting NF, clear donerec and call setlastfld(). As part of the process, revert OFS-related changes of 2018-05-22: * awk.h (saveOFS, saveOFSlen, save_old_OFS): Remove declarations. * lib.c (recbld): Use *OFS instead of saveOFS. * run.c (saveOFS, saveOFSlen, save_old_OFS): Remove. * tran.c (syminit): Remove initialization of saveOFS and saveOFSlen. General stuff that goes along with all this: * bugs-fixed/README: Updated. * bugs-fixed/decr-NF.awk, bugs-fixed/decr-NF.bad, bugs-fixed/decr-NF.ok: New files. * main.c (version): Updated. * regdir/README.TESTS: Fix awk book title. * regdir/T.misc: Revise test to match fixed code. * run.c (format): Increase size of buffer used for %a test. (Unrelated to NF or OFS, but fixes a compiler complaint.) 2018-06-07 Arnold D. Robbins * regdir/beebe.tar: Fix longwrds.ok so that the test will pass. The file was incorrectly sorted. 2018-06-06 Arnold D. Robbins * regdir/T.lilly: Fix the bug again in the second instance of the code. Thanks to BWK for pointing this out. 2018-05-31 Arnold D. Robbins * regdir/T.lilly: Fix a syntax error and ordering bug in creating the 'foo' file. 2018-05-23 Arnold D. Robbins * awk.1: Remove standalone 'awk' at the top of file, it messed up the formatting. Arrange built-in variable list in alphabetical order. 2018-05-23 Arnold D. Robbins * main.c (version): Add my email address and a date so that users can tell this isn't straight BWK awk. * README.md: Minor updates. * TODO: Updated. 2018-05-22 Arnold D. Robbins Add POSIX-required formats %a and %A. * run.c (format): Check for %a support in C library. If there, allow %a and %A as valid formats. * TODO: Updated. * bugs-fixed/README: Updated. * bugs-fixed/a-format.awk, bugs-fixed/a-format.bad, bugs-fixed/a-format.ok: New files. 2018-05-22 Arnold D. Robbins * FIXES: Restored a line from a much earlier version that apparently got lost when the dates were reordered. * TODO: Updated. 2018-05-22 Arnold D. Robbins * README.md: New file. 2018-05-22 Arnold D. Robbins * regdir/echo.c, regdir/time.c: Minor fixes to compile without warning on current GCC / Linux. 2018-05-22 Arnold D. Robbins * TODO: New file. 2018-05-22 Arnold D. Robbins * makefile (gitadd, gitpush): Remove these targets. They should not be automated and were incorrect for things that would be done regularly. 2018-05-22 Arnold D. Robbins Fix nawk so that [[:blank:]] only matches space and tab instead of any whitespace character, originally made May 10, 2018. See bugs-fixed/space.awk. This appears to have been a thinko on Brian's part. * b.c (charclasses): Use xisblank() function for [[:blank:]]. * bugs-fixed/README: Updated. * bugs-fixed/space.awk, bugs-fixed/space.bad, bugs-fixed/space.ok: New files. 2018-05-22 Arnold D. Robbins * .gitignore: New file. 2018-05-22 Arnold D. Robbins Fix nawk to provide reasonable exit status for system(), a la gawk, originally made March 12, 2016. See bugs-fixed/system-status.awk. * run.c (bltin): For FSYSTEM, use the macros defined for wait(2) to produce a reasonable exit value, instead of doing a floating-point division by 256. * awk.1: Document the return status values. * bugs-fixed/README: Updated. * bugs-fixed/system-status.awk, bugs-fixed/system-status.bad, bugs-fixed/system-status.ok: New files. 2018-05-22 Arnold D. Robbins Bug fix with respect to rebuilding a record, originally made August 19, 2014. See bugs-fixed/ofs-rebuild.awk. * awk.h (saveOFS, saveOFSlen): Declare new variables. * lib.c (recbld): Use them when rebuilding the record. * run.c (saveOFS, saveOFSlen): Define new variables. (save_old_OFS): New function to save OFS aside. * tran.c (syminit): Initialize saveOFS and saveOFSlen. (setsval): If setting a field, call save_old_OFS(). * bugs-fixed/README, bugs-fixed/ofs-rebuild.awk, bugs-fixed/ofs-rebuild.bad, bugs-fixed/ofs-rebuild.ok: New files. 2018-05-22 Arnold D. Robbins * makefile (YACC): Use bison. 2018-05-22 Arnold D. Robbins * ChangeLog: Created. * regdir: Created. Based on contents of awktest.a. * .gitattributes: Created, to preserve CR LF in regdir/t.crlf. * awktest.a: Removed. * regdir/T.gawk, regdir/T.latin1: Updated from awktest.tar. * awktest.tar: Removed. diff --git a/awk.1 b/awk.1 index ef40a0104468..496a2a652379 100644 --- a/awk.1 +++ b/awk.1 @@ -1,644 +1,696 @@ .de EX .nf .ft CW .. .de EE .br .fi .ft 1 .. .de TF .IP "" "\w'\fB\\$1\ \ \fP'u" .PD 0 .. .TH AWK 1 .CT 1 files prog_other .SH NAME awk \- pattern-directed scanning and processing language .SH SYNOPSIS .B awk [ .BI \-F .I fs | .B \-\^\-csv ] [ .BI \-v .I var=value ] [ .I 'prog' | .BI \-f .I progfile ] [ .I file ... ] .SH DESCRIPTION .I Awk scans each input .I file for lines that match any of a set of patterns specified literally in .I prog or in one or more files specified as .B \-f .IR progfile . With each pattern there can be an associated action that will be performed when a line of a .I file matches the pattern. Each line is matched against the pattern portion of every pattern-action statement; the associated action is performed for each matched pattern. The file name .B \- means the standard input. Any .I file of the form .I var=value is treated as an assignment, not a filename, and is executed at the time it would have been opened if it were a filename. The option .B \-v followed by .I var=value is an assignment to be done before .I prog is executed; any number of .B \-v options may be present. The .B \-F .I fs option defines the input field separator to be the regular expression .IR fs . The .B \-\^\-csv option causes .I awk to process records using (more or less) standard comma-separated values (CSV) format. .PP An input line is normally made up of fields separated by white space, or by the regular expression .BR FS . The fields are denoted .BR $1 , .BR $2 , \&..., while .B $0 refers to the entire line. If .BR FS is null, the input line is split into one field per character. .PP A pattern-action statement has the form: .IP .IB pattern " { " action " } .PP A missing .BI { " action " } means print the line; a missing pattern always matches. Pattern-action statements are separated by newlines or semicolons. .PP An action is a sequence of statements. A statement can be one of the following: .PP .EX .ta \w'\f(CWdelete array[expression]\fR'u .RS .nf .ft CW if(\fI expression \fP)\fI statement \fP\fR[ \fPelse\fI statement \fP\fR]\fP while(\fI expression \fP)\fI statement\fP for(\fI expression \fP;\fI expression \fP;\fI expression \fP)\fI statement\fP for(\fI var \fPin\fI array \fP)\fI statement\fP do\fI statement \fPwhile(\fI expression \fP) break continue {\fR [\fP\fI statement ... \fP\fR] \fP} \fIexpression\fP #\fR commonly\fP\fI var = expression\fP print\fR [ \fP\fIexpression-list \fP\fR] \fP\fR[ \fP>\fI expression \fP\fR]\fP printf\fI format \fP\fR[ \fP,\fI expression-list \fP\fR] \fP\fR[ \fP>\fI expression \fP\fR]\fP return\fR [ \fP\fIexpression \fP\fR]\fP next #\fR skip remaining patterns on this input line\fP nextfile #\fR skip rest of this file, open next, start at top\fP delete\fI array\fP[\fI expression \fP] #\fR delete an array element\fP delete\fI array\fP #\fR delete all elements of array\fP exit\fR [ \fP\fIexpression \fP\fR]\fP #\fR exit immediately; status is \fP\fIexpression\fP .fi .RE .EE .DT .PP Statements are terminated by semicolons, newlines or right braces. An empty .I expression-list stands for .BR $0 . String constants are quoted \&\f(CW"\ "\fR, with the usual C escapes recognized within. Expressions take on string or numeric values as appropriate, and are built using the operators .B + \- * / % ^ (exponentiation), and concatenation (indicated by white space). The operators .B ! ++ \-\- += \-= *= /= %= ^= > >= < <= == != ?: are also available in expressions. Variables may be scalars, array elements (denoted .IB x [ i ] \fR) or fields. Variables are initialized to the null string. Array subscripts may be any string, not necessarily numeric; this allows for a form of associative memory. Multiple subscripts such as .B [i,j,k] are permitted; the constituents are concatenated, separated by the value of .BR SUBSEP . .PP The .B print statement prints its arguments on the standard output (or on a file if .BI > " file or .BI >> " file is present or on a pipe if .BI | " cmd is present), separated by the current output field separator, and terminated by the output record separator. .I file and .I cmd may be literal names or parenthesized expressions; identical string values in different statements denote the same open file. The .B printf statement formats its expression list according to the .I format (see .IR printf (3)). The built-in function .BI close( expr ) closes the file or pipe .IR expr . The built-in function .BI fflush( expr ) flushes any buffered output for the file or pipe .IR expr . .PP The mathematical functions .BR atan2 , .BR cos , .BR exp , .BR log , .BR sin , and .B sqrt are built in. Other built-in functions: .TF "\fBlength(\fR[\fIv\^\fR]\fB)\fR" .TP \fBlength(\fR[\fIv\^\fR]\fB)\fR the length of its argument taken as a string, number of elements in an array for an array argument, or length of .B $0 if no argument. .TP .B rand() random number on [0,1). .TP \fBsrand(\fR[\fIs\^\fR]\fB)\fR sets seed for .B rand and returns the previous seed. .TP .BI int( x\^ ) truncates to an integer value. .TP \fBsubstr(\fIs\fB, \fIm\fR [\fB, \fIn\^\fR]\fB)\fR the .IR n -character substring of .I s that begins at position .I m counted from 1. If no .IR n , use the rest of the string. .TP .BI index( s , " t" ) the position in .I s where the string .I t occurs, or 0 if it does not. .TP .BI match( s , " r" ) the position in .I s where the regular expression .I r occurs, or 0 if it does not. The variables .B RSTART and .B RLENGTH are set to the position and length of the matched string. .TP \fBsplit(\fIs\fB, \fIa \fR[\fB, \fIfs\^\fR]\fB)\fR splits the string .I s into array elements .IB a [1] \fR, .IB a [2] \fR, \&..., .IB a [ n ] \fR, and returns .IR n . The separation is done with the regular expression .I fs or with the field separator .B FS if .I fs is not given. An empty string as field separator splits the string into one array element per character. .TP \fBsub(\fIr\fB, \fIt \fR[, \fIs\^\fR]\fB) substitutes .I t for the first occurrence of the regular expression .I r in the string .IR s . If .I s is not given, .B $0 is used. .TP \fBgsub(\fIr\fB, \fIt \fR[, \fIs\^\fR]\fB) same as .B sub except that all occurrences of the regular expression are replaced; .B sub and .B gsub return the number of replacements. .TP +\fBgensub(\fIpat\fB, \fIrepl\fB, \fIhow\fR [\fB, \fItarget\fR]\fB)\fR +replaces instances of +.I pat +in +.I target +with +.IR repl . +If +.I how +is \fB"g"\fR or \fB"G"\fR, do so globally. Otherwise, +.I how +is a number indicating which occurrence to replace. If no +.IR target , +use +.BR $0 . +Return the resulting string; +.I target +is not modified. +.TP .BI sprintf( fmt , " expr" , " ...\fB) the string resulting from formatting .I expr ... according to the .IR printf (3) format .IR fmt . .TP +.B systime() +returns the current date and time as a standard +``seconds since the epoch'' value. +.TP +.BI strftime( fmt ", " timestamp\^ ) +formats +.I timestamp +(a value in seconds since the epoch) +according to +.IR fmt , +which is a format string as supported by +.IR strftime (3). +Both +.I timestamp +and +.I fmt +may be omitted; if no +.IR timestamp , +the current time of day is used, and if no +.IR fmt , +a default format of \fB"%a %b %e %H:%M:%S %Z %Y"\fR is used. +.TP .BI system( cmd ) executes .I cmd and returns its exit status. This will be \-1 upon error, .IR cmd 's exit status upon a normal exit, 256 + .I sig upon death-by-signal, where .I sig is the number of the murdering signal, or 512 + .I sig if there was a core dump. .TP .BI tolower( str ) returns a copy of .I str with all upper-case characters translated to their corresponding lower-case equivalents. .TP .BI toupper( str ) returns a copy of .I str with all lower-case characters translated to their corresponding upper-case equivalents. .PD .PP The ``function'' .B getline sets .B $0 to the next input record from the current input file; .B getline .BI < " file sets .B $0 to the next record from .IR file . .B getline .I x sets variable .I x instead. Finally, .IB cmd " | getline pipes the output of .I cmd into .BR getline ; each call of .B getline returns the next line of output from .IR cmd . In all cases, .B getline returns 1 for a successful input, 0 for end of file, and \-1 for an error. .PP +The functions +.BR compl , +.BR and , +.BR or , +.BR xor , +.BR lshift , +and +.B rshift +peform the corresponding bitwise operations on their +operands, which are first truncated to integer. +.PP Patterns are arbitrary Boolean combinations (with .BR "! || &&" ) of regular expressions and relational expressions. Regular expressions are as in .IR egrep ; see .IR grep (1). Isolated regular expressions in a pattern apply to the entire line. Regular expressions may also occur in relational expressions, using the operators .B ~ and .BR !~ . .BI / re / is a constant regular expression; any string (constant or variable) may be used as a regular expression, except in the position of an isolated regular expression in a pattern. .PP A pattern may consist of two patterns separated by a comma; in this case, the action is performed for all lines from an occurrence of the first pattern through an occurrence of the second, inclusive. .PP A relational expression is one of the following: .IP .I expression matchop regular-expression .br .I expression relop expression .br .IB expression " in " array-name .br .BI ( expr ,\| expr ,\| ... ") in " array-name .PP where a .I relop is any of the six relational operators in C, and a .I matchop is either .B ~ (matches) or .B !~ (does not match). A conditional is an arithmetic expression, a relational expression, or a Boolean combination of these. .PP The special patterns .B BEGIN and .B END may be used to capture control before the first input line is read and after the last. .B BEGIN and .B END do not combine with other patterns. They may appear multiple times in a program and execute in the order they are read by .IR awk . .PP Variable names with special meanings: .TF FILENAME .TP .B ARGC argument count, assignable. .TP .B ARGV argument array, assignable; non-null members are taken as filenames. .TP .B CONVFMT conversion format used when converting numbers (default .BR "%.6g" ). .TP .B ENVIRON array of environment variables; subscripts are names. .TP .B FILENAME the name of the current input file. .TP .B FNR ordinal number of the current record in the current file. .TP .B FS regular expression used to separate fields; also settable by option .BI \-F fs\fR. .TP .BR NF number of fields in the current record. .TP .B NR ordinal number of the current record. .TP .B OFMT output format for numbers (default .BR "%.6g" ). .TP .B OFS output field separator (default space). .TP .B ORS output record separator (default newline). .TP .B RLENGTH the length of a string matched by .BR match . .TP .B RS input record separator (default newline). If empty, blank lines separate records. If more than one character long, .B RS is treated as a regular expression, and records are separated by text matching the expression. .TP .B RSTART the start position of a string matched by .BR match . .TP .B SUBSEP separates multiple subscripts (default 034). .PD .PP Functions may be defined (at the position of a pattern-action statement) thus: .IP .B function foo(a, b, c) { ... } .PP Parameters are passed by value if scalar and by reference if array name; functions may be called recursively. Parameters are local to the function; all other variables are global. Thus local variables may be created by providing excess parameters in the function definition. .SH ENVIRONMENT VARIABLES If .B POSIXLY_CORRECT is set in the environment, then .I awk follows the POSIX rules for .B sub and .B gsub with respect to consecutive backslashes and ampersands. .SH EXAMPLES .TP .EX length($0) > 72 .EE Print lines longer than 72 characters. .TP .EX { print $2, $1 } .EE Print first two fields in opposite order. .PP .EX BEGIN { FS = ",[ \et]*|[ \et]+" } { print $2, $1 } .EE .ns .IP Same, with input fields separated by comma and/or spaces and tabs. .PP .EX .nf { s += $1 } END { print "sum is", s, " average is", s/NR } .fi .EE .ns .IP Add up first column, print sum and average. .TP .EX /start/, /stop/ .EE Print all lines between start/stop pairs. .PP .EX .nf BEGIN { # Simulate echo(1) for (i = 1; i < ARGC; i++) printf "%s ", ARGV[i] printf "\en" exit } .fi .EE .SH SEE ALSO .IR grep (1), .IR lex (1), .IR sed (1) .br A. V. Aho, B. W. Kernighan, P. J. Weinberger, .IR "The AWK Programming Language, Second Edition" , Addison-Wesley, 2024. ISBN 978-0-13-826972-2, 0-13-826972-6. .SH BUGS There are no explicit conversions between numbers and strings. To force an expression to be treated as a number add 0 to it; to force it to be treated as a string concatenate \&\f(CW""\fP to it. .PP The scope rules for variables in functions are a botch; the syntax is worse. .PP Input is expected to be UTF-8 encoded. Other multibyte character sets are not handled. However, in eight-bit locales, .I awk treats each input byte as a separate character. .SH UNUSUAL FLOATING-POINT VALUES .I Awk was designed before IEEE 754 arithmetic defined Not-A-Number (NaN) and Infinity values, which are supported by all modern floating-point hardware. .PP Because .I awk uses .IR strtod (3) and .IR atof (3) to convert string values to double-precision floating-point values, modern C libraries also convert strings starting with .B inf and .B nan into infinity and NaN values respectively. This led to strange results, with something like this: .PP .EX .nf echo nancy | awk '{ print $1 + 0 }' .fi .EE .PP printing .B nan instead of zero. .PP .I Awk now follows GNU AWK, and prefilters string values before attempting to convert them to numbers, as follows: .TP .I "Hexadecimal values" Hexadecimal values (allowed since C99) convert to zero, as they did prior to C99. .TP .I "NaN values" The two strings .B +nan and .B \-nan (case independent) convert to NaN. No others do. (NaNs can have signs.) .TP .I "Infinity values" The two strings .B +inf and .B \-inf (case independent) convert to positive and negative infinity, respectively. No others do. diff --git a/awk.h b/awk.h index 76180e47f16a..740447ee2167 100644 --- a/awk.h +++ b/awk.h @@ -1,275 +1,283 @@ /**************************************************************** Copyright (C) Lucent Technologies 1997 All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name Lucent Technologies or any of its entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************/ #include #include #include #if __STDC_VERSION__ <= 199901L #define noreturn #else #include #endif typedef double Awkfloat; /* unsigned char is more trouble than it's worth */ typedef unsigned char uschar; #define xfree(a) { free((void *)(intptr_t)(a)); (a) = NULL; } /* * We sometimes cheat writing read-only pointers to NUL-terminate them * and then put back the original value */ #define setptr(ptr, a) (*(char *)(intptr_t)(ptr)) = (a) #define NN(p) ((p) ? (p) : "(null)") /* guaranteed non-null for DPRINTF */ #define DEBUG #ifdef DEBUG # define DPRINTF(...) if (dbg) printf(__VA_ARGS__) #else # define DPRINTF(...) #endif extern enum compile_states { RUNNING, COMPILING, ERROR_PRINTING } compile_time; extern bool safe; /* false => unsafe, true => safe */ #define RECSIZE (8 * 1024) /* sets limit on records, fields, etc., etc. */ extern int recsize; /* size of current record, orig RECSIZE */ extern size_t awk_mb_cur_max; /* max size of a multi-byte character */ extern char EMPTY[]; /* this avoid -Wwritable-strings issues */ extern char **FS; extern char **RS; extern char **ORS; extern char **OFS; extern char **OFMT; extern Awkfloat *NR; extern Awkfloat *FNR; extern Awkfloat *NF; extern char **FILENAME; extern char **SUBSEP; extern Awkfloat *RSTART; extern Awkfloat *RLENGTH; extern bool CSV; /* true for csv input */ extern char *record; /* points to $0 */ extern int lineno; /* line number in awk program */ extern int errorflag; /* 1 if error has occurred */ extern bool donefld; /* true if record broken into fields */ extern bool donerec; /* true if record is valid (no fld has changed */ extern int dbg; extern const char *patbeg; /* beginning of pattern matched */ extern int patlen; /* length of pattern matched. set in b.c */ /* Cell: all information about a variable or constant */ typedef struct Cell { uschar ctype; /* OCELL, OBOOL, OJUMP, etc. */ uschar csub; /* CCON, CTEMP, CFLD, etc. */ char *nval; /* name, for variables only */ char *sval; /* string value */ Awkfloat fval; /* value as number */ int tval; /* type info: STR|NUM|ARR|FCN|FLD|CON|DONTFREE|CONVC|CONVO */ char *fmt; /* CONVFMT/OFMT value used to convert from number */ struct Cell *cnext; /* ptr to next if chained */ } Cell; typedef struct Array { /* symbol table array */ int nelem; /* elements in table right now */ int size; /* size of tab */ Cell **tab; /* hash table pointers */ } Array; #define NSYMTAB 50 /* initial size of a symbol table */ extern Array *symtab; extern Cell *nrloc; /* NR */ extern Cell *fnrloc; /* FNR */ extern Cell *fsloc; /* FS */ extern Cell *nfloc; /* NF */ extern Cell *ofsloc; /* OFS */ extern Cell *orsloc; /* ORS */ extern Cell *rsloc; /* RS */ extern Cell *rstartloc; /* RSTART */ extern Cell *rlengthloc; /* RLENGTH */ extern Cell *subseploc; /* SUBSEP */ extern Cell *symtabloc; /* SYMTAB */ /* Cell.tval values: */ #define NUM 01 /* number value is valid */ #define STR 02 /* string value is valid */ #define DONTFREE 04 /* string space is not freeable */ #define CON 010 /* this is a constant */ #define ARR 020 /* this is an array */ #define FCN 040 /* this is a function name */ #define FLD 0100 /* this is a field $1, $2, ... */ #define REC 0200 /* this is $0 */ #define CONVC 0400 /* string was converted from number via CONVFMT */ #define CONVO 01000 /* string was converted from number via OFMT */ /* function types */ #define FLENGTH 1 #define FSQRT 2 #define FEXP 3 #define FLOG 4 #define FINT 5 #define FSYSTEM 6 #define FRAND 7 #define FSRAND 8 #define FSIN 9 #define FCOS 10 #define FATAN 11 #define FTOUPPER 12 #define FTOLOWER 13 #define FFLUSH 14 +#define FAND 15 +#define FFOR 16 +#define FXOR 17 +#define FCOMPL 18 +#define FLSHIFT 19 +#define FRSHIFT 20 +#define FSYSTIME 21 +#define FSTRFTIME 22 /* Node: parse tree is made of nodes, with Cell's at bottom */ typedef struct Node { int ntype; struct Node *nnext; int lineno; int nobj; struct Node *narg[1]; /* variable: actual size set by calling malloc */ } Node; #define NIL ((Node *) 0) extern Node *winner; extern Node *nullstat; extern Node *nullnode; /* ctypes */ #define OCELL 1 #define OBOOL 2 #define OJUMP 3 /* Cell subtypes: csub */ #define CFREE 7 #define CCOPY 6 #define CCON 5 #define CTEMP 4 #define CNAME 3 #define CVAR 2 #define CFLD 1 #define CUNK 0 /* bool subtypes */ #define BTRUE 11 #define BFALSE 12 /* jump subtypes */ #define JEXIT 21 #define JNEXT 22 #define JBREAK 23 #define JCONT 24 #define JRET 25 #define JNEXTFILE 26 /* node types */ #define NVALUE 1 #define NSTAT 2 #define NEXPR 3 extern int pairstack[], paircnt; #define notlegal(n) (n <= FIRSTTOKEN || n >= LASTTOKEN || proctab[n-FIRSTTOKEN] == nullproc) #define isvalue(n) ((n)->ntype == NVALUE) #define isexpr(n) ((n)->ntype == NEXPR) #define isjump(n) ((n)->ctype == OJUMP) #define isexit(n) ((n)->csub == JEXIT) #define isbreak(n) ((n)->csub == JBREAK) #define iscont(n) ((n)->csub == JCONT) #define isnext(n) ((n)->csub == JNEXT || (n)->csub == JNEXTFILE) #define isret(n) ((n)->csub == JRET) #define isrec(n) ((n)->tval & REC) #define isfld(n) ((n)->tval & FLD) #define isstr(n) ((n)->tval & STR) #define isnum(n) ((n)->tval & NUM) #define isarr(n) ((n)->tval & ARR) #define isfcn(n) ((n)->tval & FCN) #define istrue(n) ((n)->csub == BTRUE) #define istemp(n) ((n)->csub == CTEMP) #define isargument(n) ((n)->nobj == ARG) /* #define freeable(p) (!((p)->tval & DONTFREE)) */ #define freeable(p) ( ((p)->tval & (STR|DONTFREE)) == STR ) /* structures used by regular expression matching machinery, mostly b.c: */ #define NCHARS (1256+3) /* 256 handles 8-bit chars; 128 does 7-bit */ /* BUG: some overflows (caught) if we use 256 */ /* watch out in match(), etc. */ #define HAT (NCHARS+2) /* matches ^ in regular expr */ #define NSTATES 32 typedef struct rrow { long ltype; /* long avoids pointer warnings on 64-bit */ union { int i; Node *np; uschar *up; int *rp; /* rune representation of char class */ } lval; /* because Al stores a pointer in it! */ int *lfollow; } rrow; typedef struct gtte { /* gototab entry */ unsigned int ch; unsigned int state; } gtte; typedef struct gtt { /* gototab */ size_t allocated; size_t inuse; gtte *entries; } gtt; typedef struct fa { gtt *gototab; uschar *out; uschar *restr; int **posns; int state_count; bool anchor; int use; int initstat; int curstat; int accept; struct rrow re[1]; /* variable: actual size set by calling malloc */ } fa; #include "proto.h" diff --git a/awkgram.y b/awkgram.y index db804e117e19..233253a4307b 100644 --- a/awkgram.y +++ b/awkgram.y @@ -1,497 +1,515 @@ /**************************************************************** Copyright (C) Lucent Technologies 1997 All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name Lucent Technologies or any of its entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************/ %{ #include #include #include "awk.h" void checkdup(Node *list, Cell *item); int yywrap(void) { return(1); } Node *beginloc = 0; Node *endloc = 0; bool infunc = false; /* = true if in arglist or body of func */ int inloop = 0; /* >= 1 if in while, for, do; can't be bool, since loops can next */ char *curfname = 0; /* current function name */ Node *arglist = 0; /* list of args for current function */ %} %union { Node *p; Cell *cp; int i; char *s; } %token FIRSTTOKEN /* must be first */ %token

PROGRAM PASTAT PASTAT2 XBEGIN XEND %token NL ',' '{' '(' '|' ';' '/' ')' '}' '[' ']' %token ARRAY %token MATCH NOTMATCH MATCHOP %token FINAL DOT ALL CCL NCCL CHAR OR STAR QUEST PLUS EMPTYRE ZERO %token AND BOR APPEND EQ GE GT LE LT NE IN %token ARG BLTIN BREAK CLOSE CONTINUE DELETE DO EXIT FOR FUNC -%token SUB GSUB IF INDEX LSUBSTR MATCHFCN NEXT NEXTFILE +%token GENSUB SUB GSUB IF INDEX LSUBSTR MATCHFCN NEXT NEXTFILE %token ADD MINUS MULT DIVIDE MOD %token ASSIGN ASGNOP ADDEQ SUBEQ MULTEQ DIVEQ MODEQ POWEQ %token PRINT PRINTF SPRINTF %token

ELSE INTEST CONDEXPR %token POSTINCR PREINCR POSTDECR PREDECR %token VAR IVAR VARNF CALL NUMBER STRING %token REGEXPR %type

pas pattern ppattern plist pplist patlist prarg term re %type

pa_pat pa_stat pa_stats %type reg_expr %type

simple_stmt opt_simple_stmt stmt stmtlist %type

var varname funcname varlist %type

for if else while %type do st %type pst opt_pst lbrace rbrace rparen comma nl opt_nl and bor %type subop print %type string %right ASGNOP %right '?' %right ':' %left BOR %left AND %left GETLINE %nonassoc APPEND EQ GE GT LE LT NE MATCHOP IN '|' %left ARG BLTIN BREAK CALL CLOSE CONTINUE DELETE DO EXIT FOR FUNC %left GSUB IF INDEX LSUBSTR MATCHFCN NEXT NUMBER %left PRINT PRINTF RETURN SPLIT SPRINTF STRING SUB SUBSTR %left REGEXPR VAR VARNF IVAR WHILE '(' %left CAT %left '+' '-' %left '*' '/' '%' %left NOT UMINUS UPLUS %right POWER %right DECR INCR %left INDIRECT %token LASTTOKEN /* must be last */ %% program: pas { if (errorflag==0) winner = (Node *)stat3(PROGRAM, beginloc, $1, endloc); } | error { yyclearin; bracecheck(); SYNTAX("bailing out"); } ; and: AND | and NL ; bor: BOR | bor NL ; comma: ',' | comma NL ; do: DO | do NL ; else: ELSE | else NL ; for: FOR '(' opt_simple_stmt ';' opt_nl pattern ';' opt_nl opt_simple_stmt rparen {inloop++;} stmt { --inloop; $$ = stat4(FOR, $3, notnull($6), $9, $12); } | FOR '(' opt_simple_stmt ';' ';' opt_nl opt_simple_stmt rparen {inloop++;} stmt { --inloop; $$ = stat4(FOR, $3, NIL, $7, $10); } | FOR '(' varname IN varname rparen {inloop++;} stmt { --inloop; $$ = stat3(IN, $3, makearr($5), $8); } ; funcname: VAR { setfname($1); } | CALL { setfname($1); } ; if: IF '(' pattern rparen { $$ = notnull($3); } ; lbrace: '{' | lbrace NL ; nl: NL | nl NL ; opt_nl: /* empty */ { $$ = 0; } | nl ; opt_pst: /* empty */ { $$ = 0; } | pst ; opt_simple_stmt: /* empty */ { $$ = 0; } | simple_stmt ; pas: opt_pst { $$ = 0; } | opt_pst pa_stats opt_pst { $$ = $2; } ; pa_pat: pattern { $$ = notnull($1); } ; pa_stat: pa_pat { $$ = stat2(PASTAT, $1, stat2(PRINT, rectonode(), NIL)); } | pa_pat lbrace stmtlist '}' { $$ = stat2(PASTAT, $1, $3); } | pa_pat ',' opt_nl pa_pat { $$ = pa2stat($1, $4, stat2(PRINT, rectonode(), NIL)); } | pa_pat ',' opt_nl pa_pat lbrace stmtlist '}' { $$ = pa2stat($1, $4, $6); } | lbrace stmtlist '}' { $$ = stat2(PASTAT, NIL, $2); } | XBEGIN lbrace stmtlist '}' { beginloc = linkum(beginloc, $3); $$ = 0; } | XEND lbrace stmtlist '}' { endloc = linkum(endloc, $3); $$ = 0; } | FUNC funcname '(' varlist rparen {infunc = true;} lbrace stmtlist '}' { infunc = false; curfname=0; defn((Cell *)$2, $4, $8); $$ = 0; } ; pa_stats: pa_stat | pa_stats opt_pst pa_stat { $$ = linkum($1, $3); } ; patlist: pattern | patlist comma pattern { $$ = linkum($1, $3); } ; ppattern: var ASGNOP ppattern { $$ = op2($2, $1, $3); } | ppattern '?' ppattern ':' ppattern %prec '?' { $$ = op3(CONDEXPR, notnull($1), $3, $5); } | ppattern bor ppattern %prec BOR { $$ = op2(BOR, notnull($1), notnull($3)); } | ppattern and ppattern %prec AND { $$ = op2(AND, notnull($1), notnull($3)); } | ppattern MATCHOP reg_expr { $$ = op3($2, NIL, $1, (Node*)makedfa($3, 0)); free($3); } | ppattern MATCHOP ppattern { if (constnode($3)) { $$ = op3($2, NIL, $1, (Node*)makedfa(strnode($3), 0)); free($3); } else $$ = op3($2, (Node *)1, $1, $3); } | ppattern IN varname { $$ = op2(INTEST, $1, makearr($3)); } | '(' plist ')' IN varname { $$ = op2(INTEST, $2, makearr($5)); } | ppattern term %prec CAT { $$ = op2(CAT, $1, $2); } | re | term ; pattern: var ASGNOP pattern { $$ = op2($2, $1, $3); } | pattern '?' pattern ':' pattern %prec '?' { $$ = op3(CONDEXPR, notnull($1), $3, $5); } | pattern bor pattern %prec BOR { $$ = op2(BOR, notnull($1), notnull($3)); } | pattern and pattern %prec AND { $$ = op2(AND, notnull($1), notnull($3)); } | pattern EQ pattern { $$ = op2($2, $1, $3); } | pattern GE pattern { $$ = op2($2, $1, $3); } | pattern GT pattern { $$ = op2($2, $1, $3); } | pattern LE pattern { $$ = op2($2, $1, $3); } | pattern LT pattern { $$ = op2($2, $1, $3); } | pattern NE pattern { $$ = op2($2, $1, $3); } | pattern MATCHOP reg_expr { $$ = op3($2, NIL, $1, (Node*)makedfa($3, 0)); free($3); } | pattern MATCHOP pattern { if (constnode($3)) { $$ = op3($2, NIL, $1, (Node*)makedfa(strnode($3), 0)); free($3); } else $$ = op3($2, (Node *)1, $1, $3); } | pattern IN varname { $$ = op2(INTEST, $1, makearr($3)); } | '(' plist ')' IN varname { $$ = op2(INTEST, $2, makearr($5)); } | pattern '|' GETLINE var { if (safe) SYNTAX("cmd | getline is unsafe"); else $$ = op3(GETLINE, $4, itonp($2), $1); } | pattern '|' GETLINE { if (safe) SYNTAX("cmd | getline is unsafe"); else $$ = op3(GETLINE, (Node*)0, itonp($2), $1); } | pattern term %prec CAT { $$ = op2(CAT, $1, $2); } | re | term ; plist: pattern comma pattern { $$ = linkum($1, $3); } | plist comma pattern { $$ = linkum($1, $3); } ; pplist: ppattern | pplist comma ppattern { $$ = linkum($1, $3); } ; prarg: /* empty */ { $$ = rectonode(); } | pplist | '(' plist ')' { $$ = $2; } ; print: PRINT | PRINTF ; pst: NL | ';' | pst NL | pst ';' ; rbrace: '}' | rbrace NL ; re: reg_expr { $$ = op3(MATCH, NIL, rectonode(), (Node*)makedfa($1, 0)); free($1); } | NOT re { $$ = op1(NOT, notnull($2)); } ; reg_expr: '/' {startreg();} REGEXPR '/' { $$ = $3; } ; rparen: ')' | rparen NL ; simple_stmt: print prarg '|' term { if (safe) SYNTAX("print | is unsafe"); else $$ = stat3($1, $2, itonp($3), $4); } | print prarg APPEND term { if (safe) SYNTAX("print >> is unsafe"); else $$ = stat3($1, $2, itonp($3), $4); } | print prarg GT term { if (safe) SYNTAX("print > is unsafe"); else $$ = stat3($1, $2, itonp($3), $4); } | print prarg { $$ = stat3($1, $2, NIL, NIL); } | DELETE varname '[' patlist ']' { $$ = stat2(DELETE, makearr($2), $4); } | DELETE varname { $$ = stat2(DELETE, makearr($2), 0); } | pattern { $$ = exptostat($1); } | error { yyclearin; SYNTAX("illegal statement"); } ; st: nl | ';' opt_nl ; stmt: BREAK st { if (!inloop) SYNTAX("break illegal outside of loops"); $$ = stat1(BREAK, NIL); } | CONTINUE st { if (!inloop) SYNTAX("continue illegal outside of loops"); $$ = stat1(CONTINUE, NIL); } | do {inloop++;} stmt {--inloop;} WHILE '(' pattern ')' st { $$ = stat2(DO, $3, notnull($7)); } | EXIT pattern st { $$ = stat1(EXIT, $2); } | EXIT st { $$ = stat1(EXIT, NIL); } | for | if stmt else stmt { $$ = stat3(IF, $1, $2, $4); } | if stmt { $$ = stat3(IF, $1, $2, NIL); } | lbrace stmtlist rbrace { $$ = $2; } | NEXT st { if (infunc) SYNTAX("next is illegal inside a function"); $$ = stat1(NEXT, NIL); } | NEXTFILE st { if (infunc) SYNTAX("nextfile is illegal inside a function"); $$ = stat1(NEXTFILE, NIL); } | RETURN pattern st { $$ = stat1(RETURN, $2); } | RETURN st { $$ = stat1(RETURN, NIL); } | simple_stmt st | while {inloop++;} stmt { --inloop; $$ = stat2(WHILE, $1, $3); } | ';' opt_nl { $$ = 0; } ; stmtlist: stmt | stmtlist stmt { $$ = linkum($1, $2); } ; subop: SUB | GSUB ; string: STRING | string STRING { $$ = catstr($1, $2); } ; term: term '/' ASGNOP term { $$ = op2(DIVEQ, $1, $4); } | term '+' term { $$ = op2(ADD, $1, $3); } | term '-' term { $$ = op2(MINUS, $1, $3); } | term '*' term { $$ = op2(MULT, $1, $3); } | term '/' term { $$ = op2(DIVIDE, $1, $3); } | term '%' term { $$ = op2(MOD, $1, $3); } | term POWER term { $$ = op2(POWER, $1, $3); } | '-' term %prec UMINUS { $$ = op1(UMINUS, $2); } | '+' term %prec UMINUS { $$ = op1(UPLUS, $2); } | NOT term %prec UMINUS { $$ = op1(NOT, notnull($2)); } | BLTIN '(' ')' { $$ = op2(BLTIN, itonp($1), rectonode()); } | BLTIN '(' patlist ')' { $$ = op2(BLTIN, itonp($1), $3); } | BLTIN { $$ = op2(BLTIN, itonp($1), rectonode()); } | CALL '(' ')' { $$ = op2(CALL, celltonode($1,CVAR), NIL); } | CALL '(' patlist ')' { $$ = op2(CALL, celltonode($1,CVAR), $3); } | CLOSE term { $$ = op1(CLOSE, $2); } | DECR var { $$ = op1(PREDECR, $2); } | INCR var { $$ = op1(PREINCR, $2); } | var DECR { $$ = op1(POSTDECR, $1); } | var INCR { $$ = op1(POSTINCR, $1); } + | GENSUB '(' reg_expr comma pattern comma pattern ')' + { $$ = op5(GENSUB, NIL, (Node*)makedfa($3, 1), $5, $7, rectonode()); } + | GENSUB '(' pattern comma pattern comma pattern ')' + { if (constnode($3)) { + $$ = op5(GENSUB, NIL, (Node *)makedfa(strnode($3), 1), $5, $7, rectonode()); + free($3); + } else + $$ = op5(GENSUB, (Node *)1, $3, $5, $7, rectonode()); + } + | GENSUB '(' reg_expr comma pattern comma pattern comma pattern ')' + { $$ = op5(GENSUB, NIL, (Node*)makedfa($3, 1), $5, $7, $9); } + | GENSUB '(' pattern comma pattern comma pattern comma pattern ')' + { if (constnode($3)) { + $$ = op5(GENSUB, NIL, (Node *)makedfa(strnode($3),1), $5,$7,$9); + free($3); + } else + $$ = op5(GENSUB, (Node *)1, $3, $5, $7, $9); + } | GETLINE var LT term { $$ = op3(GETLINE, $2, itonp($3), $4); } | GETLINE LT term { $$ = op3(GETLINE, NIL, itonp($2), $3); } | GETLINE var { $$ = op3(GETLINE, $2, NIL, NIL); } | GETLINE { $$ = op3(GETLINE, NIL, NIL, NIL); } | INDEX '(' pattern comma pattern ')' { $$ = op2(INDEX, $3, $5); } | INDEX '(' pattern comma reg_expr ')' { SYNTAX("index() doesn't permit regular expressions"); $$ = op2(INDEX, $3, (Node*)$5); } | '(' pattern ')' { $$ = $2; } | MATCHFCN '(' pattern comma reg_expr ')' { $$ = op3(MATCHFCN, NIL, $3, (Node*)makedfa($5, 1)); free($5); } | MATCHFCN '(' pattern comma pattern ')' { if (constnode($5)) { $$ = op3(MATCHFCN, NIL, $3, (Node*)makedfa(strnode($5), 1)); free($5); } else $$ = op3(MATCHFCN, (Node *)1, $3, $5); } | NUMBER { $$ = celltonode($1, CCON); } | SPLIT '(' pattern comma varname comma pattern ')' /* string */ { $$ = op4(SPLIT, $3, makearr($5), $7, (Node*)STRING); } | SPLIT '(' pattern comma varname comma reg_expr ')' /* const /regexp/ */ { $$ = op4(SPLIT, $3, makearr($5), (Node*)makedfa($7, 1), (Node *)REGEXPR); free($7); } | SPLIT '(' pattern comma varname ')' { $$ = op4(SPLIT, $3, makearr($5), NIL, (Node*)STRING); } /* default */ | SPRINTF '(' patlist ')' { $$ = op1($1, $3); } | string { $$ = celltonode($1, CCON); } | subop '(' reg_expr comma pattern ')' { $$ = op4($1, NIL, (Node*)makedfa($3, 1), $5, rectonode()); free($3); } | subop '(' pattern comma pattern ')' { if (constnode($3)) { $$ = op4($1, NIL, (Node*)makedfa(strnode($3), 1), $5, rectonode()); free($3); } else $$ = op4($1, (Node *)1, $3, $5, rectonode()); } | subop '(' reg_expr comma pattern comma var ')' { $$ = op4($1, NIL, (Node*)makedfa($3, 1), $5, $7); free($3); } | subop '(' pattern comma pattern comma var ')' { if (constnode($3)) { $$ = op4($1, NIL, (Node*)makedfa(strnode($3), 1), $5, $7); free($3); } else $$ = op4($1, (Node *)1, $3, $5, $7); } | SUBSTR '(' pattern comma pattern comma pattern ')' { $$ = op3(SUBSTR, $3, $5, $7); } | SUBSTR '(' pattern comma pattern ')' { $$ = op3(SUBSTR, $3, $5, NIL); } | var ; var: varname | varname '[' patlist ']' { $$ = op2(ARRAY, makearr($1), $3); } | IVAR { $$ = op1(INDIRECT, celltonode($1, CVAR)); } | INDIRECT term { $$ = op1(INDIRECT, $2); } ; varlist: /* nothing */ { arglist = $$ = 0; } | VAR { arglist = $$ = celltonode($1,CVAR); } | varlist comma VAR { checkdup($1, $3); arglist = $$ = linkum($1,celltonode($3,CVAR)); } ; varname: VAR { $$ = celltonode($1, CVAR); } | ARG { $$ = op1(ARG, itonp($1)); } | VARNF { $$ = op1(VARNF, (Node *) $1); } ; while: WHILE '(' pattern rparen { $$ = notnull($3); } ; %% void setfname(Cell *p) { if (isarr(p)) SYNTAX("%s is an array, not a function", p->nval); else if (isfcn(p)) SYNTAX("you can't define function %s more than once", p->nval); curfname = p->nval; } int constnode(Node *p) { return isvalue(p) && ((Cell *) (p->narg[0]))->csub == CCON; } char *strnode(Node *p) { return ((Cell *)(p->narg[0]))->sval; } Node *notnull(Node *n) { switch (n->nobj) { case LE: case LT: case EQ: case NE: case GT: case GE: case BOR: case AND: case NOT: return n; default: return op2(NE, n, nullnode); } } void checkdup(Node *vl, Cell *cp) /* check if name already in list */ { char *s = cp->nval; for ( ; vl; vl = vl->nnext) { if (strcmp(s, ((Cell *)(vl->narg[0]))->nval) == 0) { SYNTAX("duplicate argument %s", s); break; } } } diff --git a/lex.c b/lex.c index 0473a338c906..141cc81d2b59 100644 --- a/lex.c +++ b/lex.c @@ -1,637 +1,646 @@ /**************************************************************** Copyright (C) Lucent Technologies 1997 All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name Lucent Technologies or any of its entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************/ #include #include #include #include #include "awk.h" #include "awkgram.tab.h" extern YYSTYPE yylval; extern bool infunc; int lineno = 1; int bracecnt = 0; int brackcnt = 0; int parencnt = 0; typedef struct Keyword { const char *word; int sub; int type; } Keyword; const Keyword keywords[] = { /* keep sorted: binary searched */ { "BEGIN", XBEGIN, XBEGIN }, { "END", XEND, XEND }, { "NF", VARNF, VARNF }, + { "and", FAND, BLTIN }, { "atan2", FATAN, BLTIN }, { "break", BREAK, BREAK }, { "close", CLOSE, CLOSE }, + { "compl", FCOMPL, BLTIN }, { "continue", CONTINUE, CONTINUE }, { "cos", FCOS, BLTIN }, { "delete", DELETE, DELETE }, { "do", DO, DO }, { "else", ELSE, ELSE }, { "exit", EXIT, EXIT }, { "exp", FEXP, BLTIN }, { "fflush", FFLUSH, BLTIN }, { "for", FOR, FOR }, { "func", FUNC, FUNC }, { "function", FUNC, FUNC }, + { "gensub", GENSUB, GENSUB }, { "getline", GETLINE, GETLINE }, { "gsub", GSUB, GSUB }, { "if", IF, IF }, { "in", IN, IN }, { "index", INDEX, INDEX }, { "int", FINT, BLTIN }, { "length", FLENGTH, BLTIN }, { "log", FLOG, BLTIN }, + { "lshift", FLSHIFT, BLTIN }, { "match", MATCHFCN, MATCHFCN }, { "next", NEXT, NEXT }, { "nextfile", NEXTFILE, NEXTFILE }, + { "or", FFOR, BLTIN }, { "print", PRINT, PRINT }, { "printf", PRINTF, PRINTF }, { "rand", FRAND, BLTIN }, { "return", RETURN, RETURN }, + { "rshift", FRSHIFT, BLTIN }, { "sin", FSIN, BLTIN }, { "split", SPLIT, SPLIT }, { "sprintf", SPRINTF, SPRINTF }, { "sqrt", FSQRT, BLTIN }, { "srand", FSRAND, BLTIN }, + { "strftime", FSTRFTIME, BLTIN }, { "sub", SUB, SUB }, { "substr", SUBSTR, SUBSTR }, { "system", FSYSTEM, BLTIN }, + { "systime", FSYSTIME, BLTIN }, { "tolower", FTOLOWER, BLTIN }, { "toupper", FTOUPPER, BLTIN }, { "while", WHILE, WHILE }, + { "xor", FXOR, BLTIN }, }; #define RET(x) { if(dbg)printf("lex %s\n", tokname(x)); return(x); } static int peek(void) { int c = input(); unput(c); return c; } static int gettok(char **pbuf, int *psz) /* get next input token */ { int c, retc; char *buf = *pbuf; int sz = *psz; char *bp = buf; c = input(); if (c == 0) return 0; buf[0] = c; buf[1] = 0; if (!isalnum(c) && c != '.' && c != '_') return c; *bp++ = c; if (isalpha(c) || c == '_') { /* it's a varname */ for ( ; (c = input()) != 0; ) { if (bp-buf >= sz) if (!adjbuf(&buf, &sz, bp-buf+2, 100, &bp, "gettok")) FATAL( "out of space for name %.10s...", buf ); if (isalnum(c) || c == '_') *bp++ = c; else { *bp = 0; unput(c); break; } } *bp = 0; retc = 'a'; /* alphanumeric */ } else { /* maybe it's a number, but could be . */ char *rem; /* read input until can't be a number */ for ( ; (c = input()) != 0; ) { if (bp-buf >= sz) if (!adjbuf(&buf, &sz, bp-buf+2, 100, &bp, "gettok")) FATAL( "out of space for number %.10s...", buf ); if (isdigit(c) || c == 'e' || c == 'E' || c == '.' || c == '+' || c == '-') *bp++ = c; else { unput(c); break; } } *bp = 0; strtod(buf, &rem); /* parse the number */ if (rem == buf) { /* it wasn't a valid number at all */ buf[1] = 0; /* return one character as token */ retc = (uschar)buf[0]; /* character is its own type */ unputstr(rem+1); /* put rest back for later */ } else { /* some prefix was a number */ unputstr(rem); /* put rest back for later */ rem[0] = 0; /* truncate buf after number part */ retc = '0'; /* type is number */ } } *pbuf = buf; *psz = sz; return retc; } int word(char *); int string(void); int regexpr(void); bool sc = false; /* true => return a } right now */ bool reg = false; /* true => return a REGEXPR now */ int yylex(void) { int c; static char *buf = NULL; static int bufsize = 5; /* BUG: setting this small causes core dump! */ if (buf == NULL && (buf = (char *) malloc(bufsize)) == NULL) FATAL( "out of space in yylex" ); if (sc) { sc = false; RET('}'); } if (reg) { reg = false; return regexpr(); } for (;;) { c = gettok(&buf, &bufsize); if (c == 0) return 0; if (isalpha(c) || c == '_') return word(buf); if (isdigit(c)) { char *cp = tostring(buf); double result; if (is_number(cp, & result)) yylval.cp = setsymtab(buf, cp, result, CON|NUM, symtab); else yylval.cp = setsymtab(buf, cp, 0.0, STR, symtab); free(cp); /* should this also have STR set? */ RET(NUMBER); } yylval.i = c; switch (c) { case '\n': /* {EOL} */ lineno++; RET(NL); case '\r': /* assume \n is coming */ case ' ': /* {WS}+ */ case '\t': break; case '#': /* #.* strip comments */ while ((c = input()) != '\n' && c != 0) ; unput(c); /* * Next line is a hack, itcompensates for * unput's treatment of \n. */ lineno++; break; case ';': RET(';'); case '\\': if (peek() == '\n') { input(); lineno++; } else if (peek() == '\r') { input(); input(); /* \n */ lineno++; } else { RET(c); } break; case '&': if (peek() == '&') { input(); RET(AND); } else RET('&'); case '|': if (peek() == '|') { input(); RET(BOR); } else RET('|'); case '!': if (peek() == '=') { input(); yylval.i = NE; RET(NE); } else if (peek() == '~') { input(); yylval.i = NOTMATCH; RET(MATCHOP); } else RET(NOT); case '~': yylval.i = MATCH; RET(MATCHOP); case '<': if (peek() == '=') { input(); yylval.i = LE; RET(LE); } else { yylval.i = LT; RET(LT); } case '=': if (peek() == '=') { input(); yylval.i = EQ; RET(EQ); } else { yylval.i = ASSIGN; RET(ASGNOP); } case '>': if (peek() == '=') { input(); yylval.i = GE; RET(GE); } else if (peek() == '>') { input(); yylval.i = APPEND; RET(APPEND); } else { yylval.i = GT; RET(GT); } case '+': if (peek() == '+') { input(); yylval.i = INCR; RET(INCR); } else if (peek() == '=') { input(); yylval.i = ADDEQ; RET(ASGNOP); } else RET('+'); case '-': if (peek() == '-') { input(); yylval.i = DECR; RET(DECR); } else if (peek() == '=') { input(); yylval.i = SUBEQ; RET(ASGNOP); } else RET('-'); case '*': if (peek() == '=') { /* *= */ input(); yylval.i = MULTEQ; RET(ASGNOP); } else if (peek() == '*') { /* ** or **= */ input(); /* eat 2nd * */ if (peek() == '=') { input(); yylval.i = POWEQ; RET(ASGNOP); } else { RET(POWER); } } else RET('*'); case '/': RET('/'); case '%': if (peek() == '=') { input(); yylval.i = MODEQ; RET(ASGNOP); } else RET('%'); case '^': if (peek() == '=') { input(); yylval.i = POWEQ; RET(ASGNOP); } else RET(POWER); case '$': /* BUG: awkward, if not wrong */ c = gettok(&buf, &bufsize); if (isalpha(c)) { if (strcmp(buf, "NF") == 0) { /* very special */ unputstr("(NF)"); RET(INDIRECT); } c = peek(); if (c == '(' || c == '[' || (infunc && isarg(buf) >= 0)) { unputstr(buf); RET(INDIRECT); } yylval.cp = setsymtab(buf, "", 0.0, STR|NUM, symtab); RET(IVAR); } else if (c == 0) { /* */ SYNTAX( "unexpected end of input after $" ); RET(';'); } else { unputstr(buf); RET(INDIRECT); } case '}': if (--bracecnt < 0) SYNTAX( "extra }" ); sc = true; RET(';'); case ']': if (--brackcnt < 0) SYNTAX( "extra ]" ); RET(']'); case ')': if (--parencnt < 0) SYNTAX( "extra )" ); RET(')'); case '{': bracecnt++; RET('{'); case '[': brackcnt++; RET('['); case '(': parencnt++; RET('('); case '"': return string(); /* BUG: should be like tran.c ? */ default: RET(c); } } } extern int runetochar(char *str, int c); int string(void) { int c, n; char *s, *bp; static char *buf = NULL; static int bufsz = 500; if (buf == NULL && (buf = (char *) malloc(bufsz)) == NULL) FATAL("out of space for strings"); for (bp = buf; (c = input()) != '"'; ) { if (!adjbuf(&buf, &bufsz, bp-buf+2, 500, &bp, "string")) FATAL("out of space for string %.10s...", buf); switch (c) { case '\n': case '\r': case 0: *bp = '\0'; SYNTAX( "non-terminated string %.10s...", buf ); if (c == 0) /* hopeless */ FATAL( "giving up" ); lineno++; break; case '\\': c = input(); switch (c) { case '\n': break; case '"': *bp++ = '"'; break; case 'n': *bp++ = '\n'; break; case 't': *bp++ = '\t'; break; case 'f': *bp++ = '\f'; break; case 'r': *bp++ = '\r'; break; case 'b': *bp++ = '\b'; break; case 'v': *bp++ = '\v'; break; case 'a': *bp++ = '\a'; break; case '\\': *bp++ = '\\'; break; case '0': case '1': case '2': /* octal: \d \dd \ddd */ case '3': case '4': case '5': case '6': case '7': n = c - '0'; if ((c = peek()) >= '0' && c < '8') { n = 8 * n + input() - '0'; if ((c = peek()) >= '0' && c < '8') n = 8 * n + input() - '0'; } *bp++ = n; break; case 'x': /* hex \x0-9a-fA-F (exactly two) */ { int i; if (!isxdigit(peek())) { unput(c); break; } n = 0; for (i = 0; i < 2; i++) { c = input(); if (c == 0) break; if (isxdigit(c)) { c = tolower(c); n *= 16; if (isdigit(c)) n += (c - '0'); else n += 10 + (c - 'a'); } else { unput(c); break; } } if (i) *bp++ = n; break; } case 'u': /* utf \u0-9a-fA-F (1..8) */ { int i; n = 0; for (i = 0; i < 8; i++) { c = input(); if (!isxdigit(c) || c == 0) break; c = tolower(c); n *= 16; if (isdigit(c)) n += (c - '0'); else n += 10 + (c - 'a'); } unput(c); bp += runetochar(bp, n); break; } default: *bp++ = c; break; } break; default: *bp++ = c; break; } } *bp = 0; s = tostring(buf); *bp++ = ' '; *bp++ = '\0'; yylval.cp = setsymtab(buf, s, 0.0, CON|STR|DONTFREE, symtab); free(s); RET(STRING); } static int binsearch(char *w, const Keyword *kp, int n) { int cond, low, mid, high; low = 0; high = n - 1; while (low <= high) { mid = (low + high) / 2; if ((cond = strcmp(w, kp[mid].word)) < 0) high = mid - 1; else if (cond > 0) low = mid + 1; else return mid; } return -1; } int word(char *w) { const Keyword *kp; int c, n; n = binsearch(w, keywords, sizeof(keywords)/sizeof(keywords[0])); if (n != -1) { /* found in table */ kp = keywords + n; yylval.i = kp->sub; switch (kp->type) { /* special handling */ case BLTIN: if (kp->sub == FSYSTEM && safe) SYNTAX( "system is unsafe" ); RET(kp->type); case FUNC: if (infunc) SYNTAX( "illegal nested function" ); RET(kp->type); case RETURN: if (!infunc) SYNTAX( "return not in function" ); RET(kp->type); case VARNF: yylval.cp = setsymtab("NF", "", 0.0, NUM, symtab); RET(VARNF); default: RET(kp->type); } } c = peek(); /* look for '(' */ if (c != '(' && infunc && (n=isarg(w)) >= 0) { yylval.i = n; RET(ARG); } else { yylval.cp = setsymtab(w, "", 0.0, STR|NUM|DONTFREE, symtab); if (c == '(') { RET(CALL); } else { RET(VAR); } } } void startreg(void) /* next call to yylex will return a regular expression */ { reg = true; } int regexpr(void) { int c; static char *buf = NULL; static int bufsz = 500; char *bp; if (buf == NULL && (buf = (char *) malloc(bufsz)) == NULL) FATAL("out of space for reg expr"); bp = buf; for ( ; (c = input()) != '/' && c != 0; ) { if (!adjbuf(&buf, &bufsz, bp-buf+3, 500, &bp, "regexpr")) FATAL("out of space for reg expr %.10s...", buf); if (c == '\n') { *bp = '\0'; SYNTAX( "newline in regular expression %.10s...", buf ); unput('\n'); break; } else if (c == '\\') { *bp++ = '\\'; *bp++ = input(); } else { *bp++ = c; } } *bp = 0; if (c == 0) SYNTAX("non-terminated regular expression %.10s...", buf); yylval.s = tostring(buf); unput('/'); RET(REGEXPR); } /* low-level lexical stuff, sort of inherited from lex */ char ebuf[300]; char *ep = ebuf; char yysbuf[100]; /* pushback buffer */ char *yysptr = yysbuf; FILE *yyin = NULL; int input(void) /* get next lexical input character */ { int c; extern char *lexprog; if (yysptr > yysbuf) c = (uschar)*--yysptr; else if (lexprog != NULL) { /* awk '...' */ if ((c = (uschar)*lexprog) != 0) lexprog++; } else /* awk -f ... */ c = pgetc(); if (c == EOF) c = 0; if (ep >= ebuf + sizeof ebuf) ep = ebuf; *ep = c; if (c != 0) { ep++; } return (c); } void unput(int c) /* put lexical character back on input */ { if (c == '\n') lineno--; if (yysptr >= yysbuf + sizeof(yysbuf)) FATAL("pushed back too much: %.20s...", yysbuf); *yysptr++ = c; if (--ep < ebuf) ep = ebuf + sizeof(ebuf) - 1; } void unputstr(const char *s) /* put a string back on input */ { int i; for (i = strlen(s)-1; i >= 0; i--) unput(s[i]); } diff --git a/maketab.c b/maketab.c index 3747efa03702..3a80c87725ac 100644 --- a/maketab.c +++ b/maketab.c @@ -1,192 +1,193 @@ /**************************************************************** Copyright (C) Lucent Technologies 1997 All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name Lucent Technologies or any of its entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************/ /* * this program makes the table to link function names * and type indices that is used by execute() in run.c. * it finds the indices in awkgram.tab.h, produced by bison. */ #include #include #include #include "awk.h" #include "awkgram.tab.h" struct xx { int token; const char *name; const char *pname; } proc[] = { { PROGRAM, "program", NULL }, { BOR, "boolop", " || " }, { AND, "boolop", " && " }, { NOT, "boolop", " !" }, { NE, "relop", " != " }, { EQ, "relop", " == " }, { LE, "relop", " <= " }, { LT, "relop", " < " }, { GE, "relop", " >= " }, { GT, "relop", " > " }, { ARRAY, "array", NULL }, { INDIRECT, "indirect", "$(" }, { SUBSTR, "substr", "substr" }, { SUB, "dosub", "sub" }, { GSUB, "dosub", "gsub" }, { INDEX, "sindex", "sindex" }, { SPRINTF, "awksprintf", "sprintf " }, { ADD, "arith", " + " }, { MINUS, "arith", " - " }, { MULT, "arith", " * " }, { DIVIDE, "arith", " / " }, { MOD, "arith", " % " }, { UMINUS, "arith", " -" }, { UPLUS, "arith", " +" }, { POWER, "arith", " **" }, { PREINCR, "incrdecr", "++" }, { POSTINCR, "incrdecr", "++" }, { PREDECR, "incrdecr", "--" }, { POSTDECR, "incrdecr", "--" }, { CAT, "cat", " " }, { PASTAT, "pastat", NULL }, { PASTAT2, "dopa2", NULL }, { MATCH, "matchop", " ~ " }, { NOTMATCH, "matchop", " !~ " }, { MATCHFCN, "matchop", "matchop" }, { INTEST, "intest", "intest" }, { PRINTF, "awkprintf", "printf" }, { PRINT, "printstat", "print" }, { CLOSE, "closefile", "closefile" }, { DELETE, "awkdelete", "awkdelete" }, { SPLIT, "split", "split" }, { ASSIGN, "assign", " = " }, { ADDEQ, "assign", " += " }, { SUBEQ, "assign", " -= " }, { MULTEQ, "assign", " *= " }, { DIVEQ, "assign", " /= " }, { MODEQ, "assign", " %= " }, { POWEQ, "assign", " ^= " }, { CONDEXPR, "condexpr", " ?: " }, { IF, "ifstat", "if(" }, { WHILE, "whilestat", "while(" }, { FOR, "forstat", "for(" }, { DO, "dostat", "do" }, { IN, "instat", "instat" }, { NEXT, "jump", "next" }, { NEXTFILE, "jump", "nextfile" }, { EXIT, "jump", "exit" }, { BREAK, "jump", "break" }, { CONTINUE, "jump", "continue" }, { RETURN, "jump", "ret" }, { BLTIN, "bltin", "bltin" }, { CALL, "call", "call" }, { ARG, "arg", "arg" }, { VARNF, "getnf", "NF" }, { GETLINE, "awkgetline", "getline" }, + { GENSUB, "gensub", "gensub" }, { 0, "", "" }, }; #define SIZE (LASTTOKEN - FIRSTTOKEN + 1) const char *table[SIZE]; char *names[SIZE]; int main(int argc, char *argv[]) { const struct xx *p; int i, n, tok; char c; FILE *fp; char buf[200], name[200], def[200]; enum { TOK_UNKNOWN, TOK_ENUM, TOK_DEFINE } tokentype = TOK_UNKNOWN; printf("#include \n"); printf("#include \"awk.h\"\n"); printf("#include \"awkgram.tab.h\"\n\n"); if (argc != 2) { fprintf(stderr, "usage: maketab YTAB_H\n"); exit(1); } if ((fp = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "maketab can't open %s!\n", argv[1]); exit(1); } printf("static const char * const printname[%d] = {\n", SIZE); i = 0; while (fgets(buf, sizeof buf, fp) != NULL) { // 199 is sizeof(def) - 1 if (tokentype != TOK_ENUM) { n = sscanf(buf, "%1c %199s %199s %d", &c, def, name, &tok); if (n == 4 && c == '#' && strcmp(def, "define") == 0) { tokentype = TOK_DEFINE; } else if (tokentype != TOK_UNKNOWN) { continue; } } if (tokentype != TOK_DEFINE) { /* not a valid #define, bison uses enums now */ n = sscanf(buf, "%199s = %d,\n", name, &tok); if (n != 2) continue; tokentype = TOK_ENUM; } if (strcmp(name, "YYSTYPE_IS_DECLARED") == 0) { tokentype = TOK_UNKNOWN; continue; } if (tok < FIRSTTOKEN || tok > LASTTOKEN) { tokentype = TOK_UNKNOWN; /* fprintf(stderr, "maketab funny token %d %s ignored\n", tok, buf); */ continue; } names[tok-FIRSTTOKEN] = strdup(name); if (names[tok-FIRSTTOKEN] == NULL) { fprintf(stderr, "maketab out of space copying %s", name); continue; } printf("\t\"%s\",\t/* %d */\n", name, tok); i++; } printf("};\n\n"); for (p=proc; p->token!=0; p++) table[p->token-FIRSTTOKEN] = p->name; printf("\nCell *(*proctab[%d])(Node **, int) = {\n", SIZE); for (i=0; i LASTTOKEN) {\n"); printf("\t\tsnprintf(buf, sizeof(buf), \"token %%d\", n);\n"); printf("\t\treturn buf;\n"); printf("\t}\n"); printf("\treturn printname[n-FIRSTTOKEN];\n"); printf("}\n"); return 0; } diff --git a/parse.c b/parse.c index 14608be7570a..2b7fd1928930 100644 --- a/parse.c +++ b/parse.c @@ -1,276 +1,299 @@ /**************************************************************** Copyright (C) Lucent Technologies 1997 All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name Lucent Technologies or any of its entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************/ #define DEBUG #include #include #include #include "awk.h" #include "awkgram.tab.h" Node *nodealloc(size_t n) { Node *x; x = (Node *) malloc(sizeof(*x) + (n-1) * sizeof(x)); if (x == NULL) FATAL("out of space in nodealloc"); x->nnext = NULL; x->lineno = lineno; return(x); } Node *exptostat(Node *a) { a->ntype = NSTAT; return(a); } Node *node1(int a, Node *b) { Node *x; x = nodealloc(1); x->nobj = a; x->narg[0]=b; return(x); } Node *node2(int a, Node *b, Node *c) { Node *x; x = nodealloc(2); x->nobj = a; x->narg[0] = b; x->narg[1] = c; return(x); } Node *node3(int a, Node *b, Node *c, Node *d) { Node *x; x = nodealloc(3); x->nobj = a; x->narg[0] = b; x->narg[1] = c; x->narg[2] = d; return(x); } Node *node4(int a, Node *b, Node *c, Node *d, Node *e) { Node *x; x = nodealloc(4); x->nobj = a; x->narg[0] = b; x->narg[1] = c; x->narg[2] = d; x->narg[3] = e; return(x); } +Node *node5(int a, Node *b, Node *c, Node *d, Node *e, Node *f) +{ + Node *x; + + x = nodealloc(5); + x->nobj = a; + x->narg[0] = b; + x->narg[1] = c; + x->narg[2] = d; + x->narg[3] = e; + x->narg[4] = f; + return(x); +} + Node *stat1(int a, Node *b) { Node *x; x = node1(a,b); x->ntype = NSTAT; return(x); } Node *stat2(int a, Node *b, Node *c) { Node *x; x = node2(a,b,c); x->ntype = NSTAT; return(x); } Node *stat3(int a, Node *b, Node *c, Node *d) { Node *x; x = node3(a,b,c,d); x->ntype = NSTAT; return(x); } Node *stat4(int a, Node *b, Node *c, Node *d, Node *e) { Node *x; x = node4(a,b,c,d,e); x->ntype = NSTAT; return(x); } Node *op1(int a, Node *b) { Node *x; x = node1(a,b); x->ntype = NEXPR; return(x); } Node *op2(int a, Node *b, Node *c) { Node *x; x = node2(a,b,c); x->ntype = NEXPR; return(x); } Node *op3(int a, Node *b, Node *c, Node *d) { Node *x; x = node3(a,b,c,d); x->ntype = NEXPR; return(x); } Node *op4(int a, Node *b, Node *c, Node *d, Node *e) { Node *x; x = node4(a,b,c,d,e); x->ntype = NEXPR; return(x); } +Node *op5(int a, Node *b, Node *c, Node *d, Node *e, Node *f) +{ + Node *x; + + x = node5(a,b,c,d,e,f); + x->ntype = NEXPR; + return(x); +} + Node *celltonode(Cell *a, int b) { Node *x; a->ctype = OCELL; a->csub = b; x = node1(0, (Node *) a); x->ntype = NVALUE; return(x); } Node *rectonode(void) /* make $0 into a Node */ { extern Cell *literal0; return op1(INDIRECT, celltonode(literal0, CUNK)); } Node *makearr(Node *p) { Cell *cp; if (isvalue(p)) { cp = (Cell *) (p->narg[0]); if (isfcn(cp)) SYNTAX( "%s is a function, not an array", cp->nval ); else if (!isarr(cp)) { xfree(cp->sval); cp->sval = (char *) makesymtab(NSYMTAB); cp->tval = ARR; } } return p; } #define PA2NUM 50 /* max number of pat,pat patterns allowed */ int paircnt; /* number of them in use */ int pairstack[PA2NUM]; /* state of each pat,pat */ Node *pa2stat(Node *a, Node *b, Node *c) /* pat, pat {...} */ { Node *x; x = node4(PASTAT2, a, b, c, itonp(paircnt)); if (paircnt++ >= PA2NUM) SYNTAX( "limited to %d pat,pat statements", PA2NUM ); x->ntype = NSTAT; return(x); } Node *linkum(Node *a, Node *b) { Node *c; if (errorflag) /* don't link things that are wrong */ return a; if (a == NULL) return(b); else if (b == NULL) return(a); for (c = a; c->nnext != NULL; c = c->nnext) ; c->nnext = b; return(a); } void defn(Cell *v, Node *vl, Node *st) /* turn on FCN bit in definition, */ { /* body of function, arglist */ Node *p; int n; if (isarr(v)) { SYNTAX( "`%s' is an array name and a function name", v->nval ); return; } if (isarg(v->nval) != -1) { SYNTAX( "`%s' is both function name and argument name", v->nval ); return; } v->tval = FCN; v->sval = (char *) st; n = 0; /* count arguments */ for (p = vl; p; p = p->nnext) n++; v->fval = n; DPRINTF("defining func %s (%d args)\n", v->nval, n); } int isarg(const char *s) /* is s in argument list for current function? */ { /* return -1 if not, otherwise arg # */ extern Node *arglist; Node *p = arglist; int n; for (n = 0; p != NULL; p = p->nnext, n++) if (strcmp(((Cell *)(p->narg[0]))->nval, s) == 0) return n; return -1; } int ptoi(void *p) /* convert pointer to integer */ { return (int) (long) p; /* swearing that p fits, of course */ } Node *itonp(int i) /* and vice versa */ { return (Node *) (long) i; } diff --git a/proto.h b/proto.h index ed63e7875da3..b44f9e7a5599 100644 --- a/proto.h +++ b/proto.h @@ -1,204 +1,207 @@ /**************************************************************** Copyright (C) Lucent Technologies 1997 All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name Lucent Technologies or any of its entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************/ extern int yywrap(void); extern void setfname(Cell *); extern int constnode(Node *); extern char *strnode(Node *); extern Node *notnull(Node *); extern int yyparse(void); extern int yylex(void); extern void startreg(void); extern int input(void); extern void unput(int); extern void unputstr(const char *); extern int yylook(void); extern int yyback(int *, int); extern int yyinput(void); extern fa *makedfa(const char *, bool); extern fa *mkdfa(const char *, bool); extern int makeinit(fa *, bool); extern void penter(Node *); extern void freetr(Node *); extern int quoted(const uschar **); extern int *cclenter(const char *); extern noreturn void overflo(const char *); extern void cfoll(fa *, Node *); extern int first(Node *); extern void follow(Node *); extern int member(int, int *); extern int match(fa *, const char *); extern int pmatch(fa *, const char *); extern int nematch(fa *, const char *); extern bool fnematch(fa *, FILE *, char **, int *, int); extern Node *reparse(const char *); extern Node *regexp(void); extern Node *primary(void); extern Node *concat(Node *); extern Node *alt(Node *); extern Node *unary(Node *); extern int relex(void); extern int cgoto(fa *, int, int); extern void freefa(fa *); extern int pgetc(void); extern char *cursource(void); extern Node *nodealloc(size_t); extern Node *exptostat(Node *); extern Node *node1(int, Node *); extern Node *node2(int, Node *, Node *); extern Node *node3(int, Node *, Node *, Node *); extern Node *node4(int, Node *, Node *, Node *, Node *); +extern Node *node5(int, Node *, Node *, Node *, Node *, Node *); extern Node *stat3(int, Node *, Node *, Node *); extern Node *op2(int, Node *, Node *); extern Node *op1(int, Node *); extern Node *stat1(int, Node *); extern Node *op3(int, Node *, Node *, Node *); extern Node *op4(int, Node *, Node *, Node *, Node *); +extern Node *op5(int, Node *, Node *, Node *, Node *, Node *); extern Node *stat2(int, Node *, Node *); extern Node *stat4(int, Node *, Node *, Node *, Node *); extern Node *celltonode(Cell *, int); extern Node *rectonode(void); extern Node *makearr(Node *); extern Node *pa2stat(Node *, Node *, Node *); extern Node *linkum(Node *, Node *); extern void defn(Cell *, Node *, Node *); extern int isarg(const char *); extern const char *tokname(int); extern Cell *(*proctab[])(Node **, int); extern int ptoi(void *); extern Node *itonp(int); extern void syminit(void); extern void arginit(int, char **); extern void envinit(char **); extern Array *makesymtab(int); extern void freesymtab(Cell *); extern void freeelem(Cell *, const char *); extern Cell *setsymtab(const char *, const char *, double, unsigned int, Array *); extern int hash(const char *, int); extern void rehash(Array *); extern Cell *lookup(const char *, Array *); extern double setfval(Cell *, double); extern void funnyvar(Cell *, const char *); extern char *setsval(Cell *, const char *); extern double getfval(Cell *); extern char *getsval(Cell *); extern char *getpssval(Cell *); /* for print */ extern char *tostring(const char *); extern char *tostringN(const char *, size_t); extern char *qstring(const char *, int); extern Cell *catstr(Cell *, Cell *); extern void recinit(unsigned int); extern void initgetrec(void); extern void makefields(int, int); extern void growfldtab(int n); extern void savefs(void); extern int getrec(char **, int *, bool); extern void nextfile(void); extern int readrec(char **buf, int *bufsize, FILE *inf, bool isnew); extern char *getargv(int); extern void setclvar(char *); extern void fldbld(void); extern void cleanfld(int, int); extern void newfld(int); extern void setlastfld(int); extern int refldbld(const char *, const char *); extern void recbld(void); extern Cell *fieldadr(int); extern void yyerror(const char *); extern void bracecheck(void); extern void bcheck2(int, int, int); extern void SYNTAX(const char *, ...) __attribute__((__format__(__printf__, 1, 2))); extern noreturn void FATAL(const char *, ...) __attribute__((__format__(__printf__, 1, 2))); extern void WARNING(const char *, ...) __attribute__((__format__(__printf__, 1, 2))); extern void error(void); extern void eprint(void); extern void bclass(int); extern double errcheck(double, const char *); extern int isclvar(const char *); extern bool is_valid_number(const char *s, bool trailing_stuff_ok, bool *no_trailing, double *result); #define is_number(s, val) is_valid_number(s, false, NULL, val) extern int adjbuf(char **pb, int *sz, int min, int q, char **pbp, const char *what); extern void run(Node *); extern Cell *execute(Node *); extern Cell *program(Node **, int); extern Cell *call(Node **, int); extern Cell *copycell(Cell *); extern Cell *arg(Node **, int); extern Cell *jump(Node **, int); extern Cell *awkgetline(Node **, int); extern Cell *getnf(Node **, int); extern Cell *array(Node **, int); extern Cell *awkdelete(Node **, int); extern Cell *intest(Node **, int); extern Cell *matchop(Node **, int); extern Cell *boolop(Node **, int); extern Cell *relop(Node **, int); extern void tfree(Cell *); extern Cell *gettemp(void); extern Cell *field(Node **, int); extern Cell *indirect(Node **, int); extern Cell *substr(Node **, int); extern Cell *sindex(Node **, int); extern int format(char **, int *, const char *, Node *); extern Cell *awksprintf(Node **, int); extern Cell *awkprintf(Node **, int); extern Cell *arith(Node **, int); extern double ipow(double, int); extern Cell *incrdecr(Node **, int); extern Cell *assign(Node **, int); extern Cell *cat(Node **, int); extern Cell *pastat(Node **, int); extern Cell *dopa2(Node **, int); extern Cell *split(Node **, int); extern Cell *condexpr(Node **, int); extern Cell *ifstat(Node **, int); extern Cell *whilestat(Node **, int); extern Cell *dostat(Node **, int); extern Cell *forstat(Node **, int); extern Cell *instat(Node **, int); extern Cell *bltin(Node **, int); extern Cell *printstat(Node **, int); extern Cell *nullproc(Node **, int); extern FILE *redirect(int, Node *); extern FILE *openfile(int, const char *, bool *); extern const char *filename(FILE *); extern Cell *closefile(Node **, int); extern void closeall(void); extern Cell *dosub(Node **, int); +extern Cell *gensub(Node **, int); extern FILE *popen(const char *, const char *); extern int pclose(FILE *); extern const char *flags2str(int flags); diff --git a/run.c b/run.c index 99306992df41..9c61b1a1c558 100644 --- a/run.c +++ b/run.c @@ -1,2618 +1,2854 @@ /**************************************************************** Copyright (C) Lucent Technologies 1997 All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name Lucent Technologies or any of its entities not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ****************************************************************/ #define DEBUG #include #include #include #include #include #include #include #include #include #include #include #include #include #include "awk.h" #include "awkgram.tab.h" static void stdinit(void); static void flush_all(void); static char *wide_char_to_byte_str(int rune, size_t *outlen); #if 1 #define tempfree(x) do { if (istemp(x)) tfree(x); } while (/*CONSTCOND*/0) #else void tempfree(Cell *p) { if (p->ctype == OCELL && (p->csub < CUNK || p->csub > CFREE)) { WARNING("bad csub %d in Cell %d %s", p->csub, p->ctype, p->sval); } if (istemp(p)) tfree(p); } #endif /* do we really need these? */ /* #ifdef _NFILE */ /* #ifndef FOPEN_MAX */ /* #define FOPEN_MAX _NFILE */ /* #endif */ /* #endif */ /* */ /* #ifndef FOPEN_MAX */ /* #define FOPEN_MAX 40 */ /* max number of open files */ /* #endif */ /* */ /* #ifndef RAND_MAX */ /* #define RAND_MAX 32767 */ /* all that ansi guarantees */ /* #endif */ jmp_buf env; extern int pairstack[]; extern Awkfloat srand_seed; Node *winner = NULL; /* root of parse tree */ Cell *tmps; /* free temporary cells for execution */ static Cell truecell ={ OBOOL, BTRUE, 0, 0, 1.0, NUM, NULL, NULL }; Cell *True = &truecell; static Cell falsecell ={ OBOOL, BFALSE, 0, 0, 0.0, NUM, NULL, NULL }; Cell *False = &falsecell; static Cell breakcell ={ OJUMP, JBREAK, 0, 0, 0.0, NUM, NULL, NULL }; Cell *jbreak = &breakcell; static Cell contcell ={ OJUMP, JCONT, 0, 0, 0.0, NUM, NULL, NULL }; Cell *jcont = &contcell; static Cell nextcell ={ OJUMP, JNEXT, 0, 0, 0.0, NUM, NULL, NULL }; Cell *jnext = &nextcell; static Cell nextfilecell ={ OJUMP, JNEXTFILE, 0, 0, 0.0, NUM, NULL, NULL }; Cell *jnextfile = &nextfilecell; static Cell exitcell ={ OJUMP, JEXIT, 0, 0, 0.0, NUM, NULL, NULL }; Cell *jexit = &exitcell; static Cell retcell ={ OJUMP, JRET, 0, 0, 0.0, NUM, NULL, NULL }; Cell *jret = &retcell; static Cell tempcell ={ OCELL, CTEMP, 0, EMPTY, 0.0, NUM|STR|DONTFREE, NULL, NULL }; Node *curnode = NULL; /* the node being executed, for debugging */ /* buffer memory management */ int adjbuf(char **pbuf, int *psiz, int minlen, int quantum, char **pbptr, const char *whatrtn) /* pbuf: address of pointer to buffer being managed * psiz: address of buffer size variable * minlen: minimum length of buffer needed * quantum: buffer size quantum * pbptr: address of movable pointer into buffer, or 0 if none * whatrtn: name of the calling routine if failure should cause fatal error * * return 0 for realloc failure, !=0 for success */ { if (minlen > *psiz) { char *tbuf; int rminlen = quantum ? minlen % quantum : 0; int boff = pbptr ? *pbptr - *pbuf : 0; /* round up to next multiple of quantum */ if (rminlen) minlen += quantum - rminlen; tbuf = (char *) realloc(*pbuf, minlen); DPRINTF("adjbuf %s: %d %d (pbuf=%p, tbuf=%p)\n", whatrtn, *psiz, minlen, (void*)*pbuf, (void*)tbuf); if (tbuf == NULL) { if (whatrtn) FATAL("out of memory in %s", whatrtn); return 0; } *pbuf = tbuf; *psiz = minlen; if (pbptr) *pbptr = tbuf + boff; } return 1; } void run(Node *a) /* execution of parse tree starts here */ { stdinit(); execute(a); closeall(); } Cell *execute(Node *u) /* execute a node of the parse tree */ { Cell *(*proc)(Node **, int); Cell *x; Node *a; if (u == NULL) return(True); for (a = u; ; a = a->nnext) { curnode = a; if (isvalue(a)) { x = (Cell *) (a->narg[0]); if (isfld(x) && !donefld) fldbld(); else if (isrec(x) && !donerec) recbld(); return(x); } if (notlegal(a->nobj)) /* probably a Cell* but too risky to print */ FATAL("illegal statement"); proc = proctab[a->nobj-FIRSTTOKEN]; x = (*proc)(a->narg, a->nobj); if (isfld(x) && !donefld) fldbld(); else if (isrec(x) && !donerec) recbld(); if (isexpr(a)) return(x); if (isjump(x)) return(x); if (a->nnext == NULL) return(x); tempfree(x); } } Cell *program(Node **a, int n) /* execute an awk program */ { /* a[0] = BEGIN, a[1] = body, a[2] = END */ Cell *x; if (setjmp(env) != 0) goto ex; if (a[0]) { /* BEGIN */ x = execute(a[0]); if (isexit(x)) return(True); if (isjump(x)) FATAL("illegal break, continue, next or nextfile from BEGIN"); tempfree(x); } if (a[1] || a[2]) while (getrec(&record, &recsize, true) > 0) { x = execute(a[1]); if (isexit(x)) break; tempfree(x); } ex: if (setjmp(env) != 0) /* handles exit within END */ goto ex1; if (a[2]) { /* END */ x = execute(a[2]); if (isbreak(x) || isnext(x) || iscont(x)) FATAL("illegal break, continue, next or nextfile from END"); tempfree(x); } ex1: return(True); } struct Frame { /* stack frame for awk function calls */ int nargs; /* number of arguments in this call */ Cell *fcncell; /* pointer to Cell for function */ Cell **args; /* pointer to array of arguments after execute */ Cell *retval; /* return value */ }; #define NARGS 50 /* max args in a call */ struct Frame *frame = NULL; /* base of stack frames; dynamically allocated */ int nframe = 0; /* number of frames allocated */ struct Frame *frp = NULL; /* frame pointer. bottom level unused */ Cell *call(Node **a, int n) /* function call. very kludgy and fragile */ { static const Cell newcopycell = { OCELL, CCOPY, 0, EMPTY, 0.0, NUM|STR|DONTFREE, NULL, NULL }; int i, ncall, ndef; int freed = 0; /* handles potential double freeing when fcn & param share a tempcell */ Node *x; Cell *args[NARGS], *oargs[NARGS]; /* BUG: fixed size arrays */ Cell *y, *z, *fcn; char *s; fcn = execute(a[0]); /* the function itself */ s = fcn->nval; if (!isfcn(fcn)) FATAL("calling undefined function %s", s); if (frame == NULL) { frp = frame = (struct Frame *) calloc(nframe += 100, sizeof(*frame)); if (frame == NULL) FATAL("out of space for stack frames calling %s", s); } for (ncall = 0, x = a[1]; x != NULL; x = x->nnext) /* args in call */ ncall++; ndef = (int) fcn->fval; /* args in defn */ DPRINTF("calling %s, %d args (%d in defn), frp=%d\n", s, ncall, ndef, (int) (frp-frame)); if (ncall > ndef) WARNING("function %s called with %d args, uses only %d", s, ncall, ndef); if (ncall + ndef > NARGS) FATAL("function %s has %d arguments, limit %d", s, ncall+ndef, NARGS); for (i = 0, x = a[1]; x != NULL; i++, x = x->nnext) { /* get call args */ DPRINTF("evaluate args[%d], frp=%d:\n", i, (int) (frp-frame)); y = execute(x); oargs[i] = y; DPRINTF("args[%d]: %s %f <%s>, t=%o\n", i, NN(y->nval), y->fval, isarr(y) ? "(array)" : NN(y->sval), y->tval); if (isfcn(y)) FATAL("can't use function %s as argument in %s", y->nval, s); if (isarr(y)) args[i] = y; /* arrays by ref */ else args[i] = copycell(y); tempfree(y); } for ( ; i < ndef; i++) { /* add null args for ones not provided */ args[i] = gettemp(); *args[i] = newcopycell; } frp++; /* now ok to up frame */ if (frp >= frame + nframe) { int dfp = frp - frame; /* old index */ frame = (struct Frame *) realloc(frame, (nframe += 100) * sizeof(*frame)); if (frame == NULL) FATAL("out of space for stack frames in %s", s); frp = frame + dfp; } frp->fcncell = fcn; frp->args = args; frp->nargs = ndef; /* number defined with (excess are locals) */ frp->retval = gettemp(); DPRINTF("start exec of %s, frp=%d\n", s, (int) (frp-frame)); y = execute((Node *)(fcn->sval)); /* execute body */ DPRINTF("finished exec of %s, frp=%d\n", s, (int) (frp-frame)); for (i = 0; i < ndef; i++) { Cell *t = frp->args[i]; if (isarr(t)) { if (t->csub == CCOPY) { if (i >= ncall) { freesymtab(t); t->csub = CTEMP; tempfree(t); } else { oargs[i]->tval = t->tval; oargs[i]->tval &= ~(STR|NUM|DONTFREE); oargs[i]->sval = t->sval; tempfree(t); } } } else if (t != y) { /* kludge to prevent freeing twice */ t->csub = CTEMP; tempfree(t); } else if (t == y && t->csub == CCOPY) { t->csub = CTEMP; tempfree(t); freed = 1; } } tempfree(fcn); if (isexit(y) || isnext(y)) return y; if (freed == 0) { tempfree(y); /* don't free twice! */ } z = frp->retval; /* return value */ DPRINTF("%s returns %g |%s| %o\n", s, getfval(z), getsval(z), z->tval); frp--; return(z); } Cell *copycell(Cell *x) /* make a copy of a cell in a temp */ { Cell *y; /* copy is not constant or field */ y = gettemp(); y->tval = x->tval & ~(CON|FLD|REC); y->csub = CCOPY; /* prevents freeing until call is over */ y->nval = x->nval; /* BUG? */ if (isstr(x) /* || x->ctype == OCELL */) { y->sval = tostring(x->sval); y->tval &= ~DONTFREE; } else y->tval |= DONTFREE; y->fval = x->fval; return y; } Cell *arg(Node **a, int n) /* nth argument of a function */ { n = ptoi(a[0]); /* argument number, counting from 0 */ DPRINTF("arg(%d), frp->nargs=%d\n", n, frp->nargs); if (n+1 > frp->nargs) FATAL("argument #%d of function %s was not supplied", n+1, frp->fcncell->nval); return frp->args[n]; } Cell *jump(Node **a, int n) /* break, continue, next, nextfile, return */ { Cell *y; switch (n) { case EXIT: if (a[0] != NULL) { y = execute(a[0]); errorflag = (int) getfval(y); tempfree(y); } longjmp(env, 1); case RETURN: if (a[0] != NULL) { y = execute(a[0]); if ((y->tval & (STR|NUM)) == (STR|NUM)) { setsval(frp->retval, getsval(y)); frp->retval->fval = getfval(y); frp->retval->tval |= NUM; } else if (y->tval & STR) setsval(frp->retval, getsval(y)); else if (y->tval & NUM) setfval(frp->retval, getfval(y)); else /* can't happen */ FATAL("bad type variable %d", y->tval); tempfree(y); } return(jret); case NEXT: return(jnext); case NEXTFILE: nextfile(); return(jnextfile); case BREAK: return(jbreak); case CONTINUE: return(jcont); default: /* can't happen */ FATAL("illegal jump type %d", n); } return 0; /* not reached */ } Cell *awkgetline(Node **a, int n) /* get next line from specific input */ { /* a[0] is variable, a[1] is operator, a[2] is filename */ Cell *r, *x; extern Cell **fldtab; FILE *fp; char *buf; int bufsize = recsize; int mode; bool newflag; double result; if ((buf = (char *) malloc(bufsize)) == NULL) FATAL("out of memory in getline"); fflush(stdout); /* in case someone is waiting for a prompt */ r = gettemp(); if (a[1] != NULL) { /* getline < file */ x = execute(a[2]); /* filename */ mode = ptoi(a[1]); if (mode == '|') /* input pipe */ mode = LE; /* arbitrary flag */ fp = openfile(mode, getsval(x), &newflag); tempfree(x); if (fp == NULL) n = -1; else n = readrec(&buf, &bufsize, fp, newflag); if (n <= 0) { ; } else if (a[0] != NULL) { /* getline var sval, & result)) { x->fval = result; x->tval |= NUM; } tempfree(x); } else { /* getline sval, & result)) { fldtab[0]->fval = result; fldtab[0]->tval |= NUM; } } } else { /* bare getline; use current input */ if (a[0] == NULL) /* getline */ n = getrec(&record, &recsize, true); else { /* getline var */ n = getrec(&buf, &bufsize, false); if (n > 0) { x = execute(a[0]); setsval(x, buf); if (is_number(x->sval, & result)) { x->fval = result; x->tval |= NUM; } tempfree(x); } } } setfval(r, (Awkfloat) n); free(buf); return r; } Cell *getnf(Node **a, int n) /* get NF */ { if (!donefld) fldbld(); return (Cell *) a[0]; } static char * makearraystring(Node *p, const char *func) { char *buf; int bufsz = recsize; size_t blen; if ((buf = (char *) malloc(bufsz)) == NULL) { FATAL("%s: out of memory", func); } blen = 0; buf[blen] = '\0'; for (; p; p = p->nnext) { Cell *x = execute(p); /* expr */ char *s = getsval(x); size_t seplen = strlen(getsval(subseploc)); size_t nsub = p->nnext ? seplen : 0; size_t slen = strlen(s); size_t tlen = blen + slen + nsub; if (!adjbuf(&buf, &bufsz, tlen + 1, recsize, 0, func)) { FATAL("%s: out of memory %s[%s...]", func, x->nval, buf); } memcpy(buf + blen, s, slen); if (nsub) { memcpy(buf + blen + slen, *SUBSEP, nsub); } buf[tlen] = '\0'; blen = tlen; tempfree(x); } return buf; } Cell *array(Node **a, int n) /* a[0] is symtab, a[1] is list of subscripts */ { Cell *x, *z; char *buf; x = execute(a[0]); /* Cell* for symbol table */ buf = makearraystring(a[1], __func__); if (!isarr(x)) { DPRINTF("making %s into an array\n", NN(x->nval)); if (freeable(x)) xfree(x->sval); x->tval &= ~(STR|NUM|DONTFREE); x->tval |= ARR; x->sval = (char *) makesymtab(NSYMTAB); } z = setsymtab(buf, "", 0.0, STR|NUM, (Array *) x->sval); z->ctype = OCELL; z->csub = CVAR; tempfree(x); free(buf); return(z); } Cell *awkdelete(Node **a, int n) /* a[0] is symtab, a[1] is list of subscripts */ { Cell *x; x = execute(a[0]); /* Cell* for symbol table */ if (x == symtabloc) { FATAL("cannot delete SYMTAB or its elements"); } if (!isarr(x)) return True; if (a[1] == NULL) { /* delete the elements, not the table */ freesymtab(x); x->tval &= ~STR; x->tval |= ARR; x->sval = (char *) makesymtab(NSYMTAB); } else { char *buf = makearraystring(a[1], __func__); freeelem(x, buf); free(buf); } tempfree(x); return True; } Cell *intest(Node **a, int n) /* a[0] is index (list), a[1] is symtab */ { Cell *ap, *k; char *buf; ap = execute(a[1]); /* array name */ if (!isarr(ap)) { DPRINTF("making %s into an array\n", ap->nval); if (freeable(ap)) xfree(ap->sval); ap->tval &= ~(STR|NUM|DONTFREE); ap->tval |= ARR; ap->sval = (char *) makesymtab(NSYMTAB); } buf = makearraystring(a[0], __func__); k = lookup(buf, (Array *) ap->sval); tempfree(ap); free(buf); if (k == NULL) return(False); else return(True); } /* ======== utf-8 code ========== */ /* * Awk strings can contain ascii, random 8-bit items (eg Latin-1), * or utf-8. u8_isutf tests whether a string starts with a valid * utf-8 sequence, and returns 0 if not (e.g., high bit set). * u8_nextlen returns length of next valid sequence, which is * 1 for ascii, 2..4 for utf-8, or 1 for high bit non-utf. * u8_strlen returns length of string in valid utf-8 sequences * and/or high-bit bytes. Conversion functions go between byte * number and character number. * * In theory, this behaves the same as before for non-utf8 bytes. * * Limited checking! This is a potential security hole. */ /* is s the beginning of a valid utf-8 string? */ /* return length 1..4 if yes, 0 if no */ int u8_isutf(const char *s) { int n, ret; unsigned char c; c = s[0]; if (c < 128 || awk_mb_cur_max == 1) return 1; /* what if it's 0? */ n = strlen(s); if (n >= 2 && ((c>>5) & 0x7) == 0x6 && (s[1] & 0xC0) == 0x80) { ret = 2; /* 110xxxxx 10xxxxxx */ } else if (n >= 3 && ((c>>4) & 0xF) == 0xE && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80) { ret = 3; /* 1110xxxx 10xxxxxx 10xxxxxx */ } else if (n >= 4 && ((c>>3) & 0x1F) == 0x1E && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80 && (s[3] & 0xC0) == 0x80) { ret = 4; /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ } else { ret = 0; } return ret; } /* Convert (prefix of) utf8 string to utf-32 rune. */ /* Sets *rune to the value, returns the length. */ /* No error checking: watch out. */ int u8_rune(int *rune, const char *s) { int n, ret; unsigned char c; c = s[0]; if (c < 128 || awk_mb_cur_max == 1) { *rune = c; return 1; } n = strlen(s); if (n >= 2 && ((c>>5) & 0x7) == 0x6 && (s[1] & 0xC0) == 0x80) { *rune = ((c & 0x1F) << 6) | (s[1] & 0x3F); /* 110xxxxx 10xxxxxx */ ret = 2; } else if (n >= 3 && ((c>>4) & 0xF) == 0xE && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80) { *rune = ((c & 0xF) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F); /* 1110xxxx 10xxxxxx 10xxxxxx */ ret = 3; } else if (n >= 4 && ((c>>3) & 0x1F) == 0x1E && (s[1] & 0xC0) == 0x80 && (s[2] & 0xC0) == 0x80 && (s[3] & 0xC0) == 0x80) { *rune = ((c & 0x7) << 18) | ((s[1] & 0x3F) << 12) | ((s[2] & 0x3F) << 6) | (s[3] & 0x3F); /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ ret = 4; } else { *rune = c; ret = 1; } return ret; /* returns one byte if sequence doesn't look like utf */ } /* return length of next sequence: 1 for ascii or random, 2..4 for valid utf8 */ int u8_nextlen(const char *s) { int len; len = u8_isutf(s); if (len == 0) len = 1; return len; } /* return number of utf characters or single non-utf bytes */ int u8_strlen(const char *s) { int i, len, n, totlen; unsigned char c; n = strlen(s); totlen = 0; for (i = 0; i < n; i += len) { c = s[i]; if (c < 128 || awk_mb_cur_max == 1) { len = 1; } else { len = u8_nextlen(&s[i]); } totlen++; if (i > n) FATAL("bad utf count [%s] n=%d i=%d\n", s, n, i); } return totlen; } /* convert utf-8 char number in a string to its byte offset */ int u8_char2byte(const char *s, int charnum) { int n; int bytenum = 0; while (charnum > 0) { n = u8_nextlen(s); s += n; bytenum += n; charnum--; } return bytenum; } /* convert byte offset in s to utf-8 char number that starts there */ int u8_byte2char(const char *s, int bytenum) { int i, len, b; int charnum = 0; /* BUG: what origin? */ /* should be 0 to match start==0 which means no match */ b = strlen(s); if (bytenum > b) { return -1; /* ??? */ } for (i = 0; i <= bytenum; i += len) { len = u8_nextlen(s+i); charnum++; } return charnum; } /* runetochar() adapted from rune.c in the Plan 9 distributione */ enum { Runeerror = 128, /* from somewhere else */ Runemax = 0x10FFFF, Bit1 = 7, Bitx = 6, Bit2 = 5, Bit3 = 4, Bit4 = 3, Bit5 = 2, T1 = ((1<<(Bit1+1))-1) ^ 0xFF, /* 0000 0000 */ Tx = ((1<<(Bitx+1))-1) ^ 0xFF, /* 1000 0000 */ T2 = ((1<<(Bit2+1))-1) ^ 0xFF, /* 1100 0000 */ T3 = ((1<<(Bit3+1))-1) ^ 0xFF, /* 1110 0000 */ T4 = ((1<<(Bit4+1))-1) ^ 0xFF, /* 1111 0000 */ T5 = ((1<<(Bit5+1))-1) ^ 0xFF, /* 1111 1000 */ Rune1 = (1<<(Bit1+0*Bitx))-1, /* 0000 0000 0000 0000 0111 1111 */ Rune2 = (1<<(Bit2+1*Bitx))-1, /* 0000 0000 0000 0111 1111 1111 */ Rune3 = (1<<(Bit3+2*Bitx))-1, /* 0000 0000 1111 1111 1111 1111 */ Rune4 = (1<<(Bit4+3*Bitx))-1, /* 0011 1111 1111 1111 1111 1111 */ Maskx = (1< 00-7F */ if (c <= Rune1) { str[0] = c; return 1; } /* two character sequence 00080-007FF => T2 Tx */ if (c <= Rune2) { str[0] = T2 | (c >> 1*Bitx); str[1] = Tx | (c & Maskx); return 2; } /* three character sequence 00800-0FFFF => T3 Tx Tx */ if (c > Runemax) c = Runeerror; if (c <= Rune3) { str[0] = T3 | (c >> 2*Bitx); str[1] = Tx | ((c >> 1*Bitx) & Maskx); str[2] = Tx | (c & Maskx); return 3; } /* four character sequence 010000-1FFFFF => T4 Tx Tx Tx */ str[0] = T4 | (c >> 3*Bitx); str[1] = Tx | ((c >> 2*Bitx) & Maskx); str[2] = Tx | ((c >> 1*Bitx) & Maskx); str[3] = Tx | (c & Maskx); return 4; } /* ========== end of utf8 code =========== */ Cell *matchop(Node **a, int n) /* ~ and match() */ { Cell *x, *y, *z; char *s, *t; int i; int cstart, cpatlen, len; fa *pfa; int (*mf)(fa *, const char *) = match, mode = 0; if (n == MATCHFCN) { mf = pmatch; mode = 1; } x = execute(a[1]); /* a[1] = target text */ s = getsval(x); if (a[0] == NULL) /* a[1] == 0: already-compiled reg expr */ i = (*mf)((fa *) a[2], s); else { y = execute(a[2]); /* a[2] = regular expr */ t = getsval(y); pfa = makedfa(t, mode); i = (*mf)(pfa, s); tempfree(y); } z = x; if (n == MATCHFCN) { int start = patbeg - s + 1; /* origin 1 */ if (patlen < 0) { start = 0; /* not found */ } else { cstart = u8_byte2char(s, start-1); cpatlen = 0; for (i = 0; i < patlen; i += len) { len = u8_nextlen(patbeg+i); cpatlen++; } start = cstart; patlen = cpatlen; } setfval(rstartloc, (Awkfloat) start); setfval(rlengthloc, (Awkfloat) patlen); x = gettemp(); x->tval = NUM; x->fval = start; } else if ((n == MATCH && i == 1) || (n == NOTMATCH && i == 0)) x = True; else x = False; tempfree(z); return x; } Cell *boolop(Node **a, int n) /* a[0] || a[1], a[0] && a[1], !a[0] */ { Cell *x, *y; int i; x = execute(a[0]); i = istrue(x); tempfree(x); switch (n) { case BOR: if (i) return(True); y = execute(a[1]); i = istrue(y); tempfree(y); if (i) return(True); else return(False); case AND: if ( !i ) return(False); y = execute(a[1]); i = istrue(y); tempfree(y); if (i) return(True); else return(False); case NOT: if (i) return(False); else return(True); default: /* can't happen */ FATAL("unknown boolean operator %d", n); } return 0; /*NOTREACHED*/ } Cell *relop(Node **a, int n) /* a[0 < a[1], etc. */ { int i; Cell *x, *y; Awkfloat j; bool x_is_nan, y_is_nan; x = execute(a[0]); y = execute(a[1]); x_is_nan = isnan(x->fval); y_is_nan = isnan(y->fval); if (x->tval&NUM && y->tval&NUM) { if ((x_is_nan || y_is_nan) && n != NE) return(False); j = x->fval - y->fval; i = j<0? -1: (j>0? 1: 0); } else { i = strcmp(getsval(x), getsval(y)); } tempfree(x); tempfree(y); switch (n) { case LT: if (i<0) return(True); else return(False); case LE: if (i<=0) return(True); else return(False); case NE: if (x_is_nan && y_is_nan) return(True); else if (i!=0) return(True); else return(False); case EQ: if (i == 0) return(True); else return(False); case GE: if (i>=0) return(True); else return(False); case GT: if (i>0) return(True); else return(False); default: /* can't happen */ FATAL("unknown relational operator %d", n); } return 0; /*NOTREACHED*/ } void tfree(Cell *a) /* free a tempcell */ { if (freeable(a)) { DPRINTF("freeing %s %s %o\n", NN(a->nval), NN(a->sval), a->tval); xfree(a->sval); } if (a == tmps) FATAL("tempcell list is curdled"); a->cnext = tmps; tmps = a; } Cell *gettemp(void) /* get a tempcell */ { int i; Cell *x; if (!tmps) { tmps = (Cell *) calloc(100, sizeof(*tmps)); if (!tmps) FATAL("out of space for temporaries"); for (i = 1; i < 100; i++) tmps[i-1].cnext = &tmps[i]; tmps[i-1].cnext = NULL; } x = tmps; tmps = x->cnext; *x = tempcell; return(x); } Cell *indirect(Node **a, int n) /* $( a[0] ) */ { Awkfloat val; Cell *x; int m; char *s; x = execute(a[0]); val = getfval(x); /* freebsd: defend against super large field numbers */ if ((Awkfloat)INT_MAX < val) FATAL("trying to access out of range field %s", x->nval); m = (int) val; if (m == 0 && !is_number(s = getsval(x), NULL)) /* suspicion! */ FATAL("illegal field $(%s), name \"%s\"", s, x->nval); /* BUG: can x->nval ever be null??? */ tempfree(x); x = fieldadr(m); x->ctype = OCELL; /* BUG? why are these needed? */ x->csub = CFLD; return(x); } Cell *substr(Node **a, int nnn) /* substr(a[0], a[1], a[2]) */ { int k, m, n; int mb, nb; char *s; int temp; Cell *x, *y, *z = NULL; x = execute(a[0]); y = execute(a[1]); if (a[2] != NULL) z = execute(a[2]); s = getsval(x); k = u8_strlen(s) + 1; if (k <= 1) { tempfree(x); tempfree(y); if (a[2] != NULL) { tempfree(z); } x = gettemp(); setsval(x, ""); return(x); } m = (int) getfval(y); if (m <= 0) m = 1; else if (m > k) m = k; tempfree(y); if (a[2] != NULL) { n = (int) getfval(z); tempfree(z); } else n = k - 1; if (n < 0) n = 0; else if (n > k - m) n = k - m; /* m is start, n is length from there */ DPRINTF("substr: m=%d, n=%d, s=%s\n", m, n, s); y = gettemp(); mb = u8_char2byte(s, m-1); /* byte offset of start char in s */ nb = u8_char2byte(s, m-1+n); /* byte offset of end+1 char in s */ temp = s[nb]; /* with thanks to John Linderman */ s[nb] = '\0'; setsval(y, s + mb); s[nb] = temp; tempfree(x); return(y); } Cell *sindex(Node **a, int nnn) /* index(a[0], a[1]) */ { Cell *x, *y, *z; char *s1, *s2, *p1, *p2, *q; Awkfloat v = 0.0; x = execute(a[0]); s1 = getsval(x); y = execute(a[1]); s2 = getsval(y); z = gettemp(); for (p1 = s1; *p1 != '\0'; p1++) { for (q = p1, p2 = s2; *p2 != '\0' && *q == *p2; q++, p2++) continue; if (*p2 == '\0') { /* v = (Awkfloat) (p1 - s1 + 1); origin 1 */ /* should be a function: used in match() as well */ int i, len; v = 0; for (i = 0; i < p1-s1+1; i += len) { len = u8_nextlen(s1+i); v++; } break; } } tempfree(x); tempfree(y); setfval(z, v); return(z); } int has_utf8(char *s) /* return 1 if s contains any utf-8 (2 bytes or more) character */ { int n; for (n = 0; *s != 0; s += n) { n = u8_nextlen(s); if (n > 1) return 1; } return 0; } #define MAXNUMSIZE 50 int format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conversions */ { char *fmt; char *p, *t; const char *os; Cell *x; int flag = 0, n; int fmtwd; /* format width */ int fmtsz = recsize; char *buf = *pbuf; int bufsize = *pbufsize; #define FMTSZ(a) (fmtsz - ((a) - fmt)) #define BUFSZ(a) (bufsize - ((a) - buf)) static bool first = true; static bool have_a_format = false; if (first) { char xbuf[100]; snprintf(xbuf, sizeof(xbuf), "%a", 42.0); have_a_format = (strcmp(xbuf, "0x1.5p+5") == 0); first = false; } os = s; p = buf; if ((fmt = (char *) malloc(fmtsz)) == NULL) FATAL("out of memory in format()"); while (*s) { adjbuf(&buf, &bufsize, MAXNUMSIZE+1+p-buf, recsize, &p, "format1"); if (*s != '%') { *p++ = *s++; continue; } if (*(s+1) == '%') { *p++ = '%'; s += 2; continue; } fmtwd = atoi(s+1); if (fmtwd < 0) fmtwd = -fmtwd; adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format2"); for (t = fmt; (*t++ = *s) != '\0'; s++) { if (!adjbuf(&fmt, &fmtsz, MAXNUMSIZE+1+t-fmt, recsize, &t, "format3")) FATAL("format item %.30s... ran format() out of memory", os); /* Ignore size specifiers */ if (strchr("hjLlqtz", *s) != NULL) { /* the ansi panoply */ t--; continue; } if (isalpha((uschar)*s)) break; if (*s == '$') { FATAL("'$' not permitted in awk formats"); } if (*s == '*') { if (a == NULL) { FATAL("not enough args in printf(%s)", os); } x = execute(a); a = a->nnext; snprintf(t - 1, FMTSZ(t - 1), "%d", fmtwd=(int) getfval(x)); if (fmtwd < 0) fmtwd = -fmtwd; adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format"); t = fmt + strlen(fmt); tempfree(x); } } *t = '\0'; if (fmtwd < 0) fmtwd = -fmtwd; adjbuf(&buf, &bufsize, fmtwd+1+p-buf, recsize, &p, "format4"); switch (*s) { case 'a': case 'A': if (have_a_format) flag = *s; else flag = 'f'; break; case 'f': case 'e': case 'g': case 'E': case 'G': flag = 'f'; break; case 'd': case 'i': case 'o': case 'x': case 'X': case 'u': flag = (*s == 'd' || *s == 'i') ? 'd' : 'u'; *(t-1) = 'j'; *t = *s; *++t = '\0'; break; case 's': flag = 's'; break; case 'c': flag = 'c'; break; default: WARNING("weird printf conversion %s", fmt); flag = '?'; break; } if (a == NULL) FATAL("not enough args in printf(%s)", os); x = execute(a); a = a->nnext; n = MAXNUMSIZE; if (fmtwd > n) n = fmtwd; adjbuf(&buf, &bufsize, 1+n+p-buf, recsize, &p, "format5"); switch (flag) { case '?': snprintf(p, BUFSZ(p), "%s", fmt); /* unknown, so dump it too */ t = getsval(x); n = strlen(t); if (fmtwd > n) n = fmtwd; adjbuf(&buf, &bufsize, 1+strlen(p)+n+p-buf, recsize, &p, "format6"); p += strlen(p); snprintf(p, BUFSZ(p), "%s", t); break; case 'a': case 'A': case 'f': snprintf(p, BUFSZ(p), fmt, getfval(x)); break; case 'd': snprintf(p, BUFSZ(p), fmt, (intmax_t) getfval(x)); break; case 'u': snprintf(p, BUFSZ(p), fmt, (uintmax_t) getfval(x)); break; case 's': { t = getsval(x); n = strlen(t); /* if simple format or no utf-8 in the string, sprintf works */ if (!has_utf8(t) || strcmp(fmt,"%s") == 0) { if (fmtwd > n) n = fmtwd; if (!adjbuf(&buf, &bufsize, 1+n+p-buf, recsize, &p, "format7")) FATAL("huge string/format (%d chars) in printf %.30s..." \ " ran format() out of memory", n, t); snprintf(p, BUFSZ(p), fmt, t); break; } /* get here if string has utf-8 chars and fmt is not plain %s */ /* "%-w.ps", where -, w and .p are all optional */ /* '0' before the w is a flag character */ /* fmt points at % */ int ljust = 0, wid = 0, prec = n, pad = 0; char *f = fmt+1; if (f[0] == '-') { ljust = 1; f++; } // flags '0' and '+' are recognized but skipped if (f[0] == '0') { f++; if (f[0] == '+') f++; } if (f[0] == '+') { f++; if (f[0] == '0') f++; } if (isdigit(f[0])) { /* there is a wid */ wid = strtol(f, &f, 10); } if (f[0] == '.') { /* there is a .prec */ prec = strtol(++f, &f, 10); } if (prec > u8_strlen(t)) prec = u8_strlen(t); pad = wid>prec ? wid - prec : 0; // has to be >= 0 int i, k, n; if (ljust) { // print prec chars from t, then pad blanks n = u8_char2byte(t, prec); for (k = 0; k < n; k++) { //putchar(t[k]); *p++ = t[k]; } for (i = 0; i < pad; i++) { //printf(" "); *p++ = ' '; } } else { // print pad blanks, then prec chars from t for (i = 0; i < pad; i++) { //printf(" "); *p++ = ' '; } n = u8_char2byte(t, prec); for (k = 0; k < n; k++) { //putchar(t[k]); *p++ = t[k]; } } *p = 0; break; } case 'c': { /* * If a numeric value is given, awk should just turn * it into a character and print it: * BEGIN { printf("%c\n", 65) } * prints "A". * * But what if the numeric value is > 128 and * represents a valid Unicode code point?!? We do * our best to convert it back into UTF-8. If we * can't, we output the encoding of the Unicode * "invalid character", 0xFFFD. */ if (isnum(x)) { int charval = (int) getfval(x); if (charval != 0) { if (charval < 128 || awk_mb_cur_max == 1) snprintf(p, BUFSZ(p), fmt, charval); else { // possible unicode character size_t count; char *bs = wide_char_to_byte_str(charval, &count); if (bs == NULL) { // invalid character // use unicode invalid character, 0xFFFD static char invalid_char[] = "\357\277\275"; bs = invalid_char; count = 3; } t = bs; n = count; goto format_percent_c; } } else { *p++ = '\0'; /* explicit null byte */ *p = '\0'; /* next output will start here */ } break; } t = getsval(x); n = u8_nextlen(t); format_percent_c: if (n < 2) { /* not utf8 */ snprintf(p, BUFSZ(p), fmt, getsval(x)[0]); break; } // utf8 character, almost same song and dance as for %s int ljust = 0, wid = 0, prec = n, pad = 0; char *f = fmt+1; if (f[0] == '-') { ljust = 1; f++; } // flags '0' and '+' are recognized but skipped if (f[0] == '0') { f++; if (f[0] == '+') f++; } if (f[0] == '+') { f++; if (f[0] == '0') f++; } if (isdigit(f[0])) { /* there is a wid */ wid = strtol(f, &f, 10); } if (f[0] == '.') { /* there is a .prec */ prec = strtol(++f, &f, 10); } if (prec > 1) // %c --> only one character prec = 1; pad = wid>prec ? wid - prec : 0; // has to be >= 0 int i; if (ljust) { // print one char from t, then pad blanks for (i = 0; i < n; i++) *p++ = t[i]; for (i = 0; i < pad; i++) { //printf(" "); *p++ = ' '; } } else { // print pad blanks, then prec chars from t for (i = 0; i < pad; i++) { //printf(" "); *p++ = ' '; } for (i = 0; i < n; i++) *p++ = t[i]; } *p = 0; break; } default: FATAL("can't happen: bad conversion %c in format()", flag); } tempfree(x); p += strlen(p); s++; } *p = '\0'; free(fmt); for ( ; a; a = a->nnext) { /* evaluate any remaining args */ x = execute(a); tempfree(x); } *pbuf = buf; *pbufsize = bufsize; return p - buf; } Cell *awksprintf(Node **a, int n) /* sprintf(a[0]) */ { Cell *x; Node *y; char *buf; int bufsz=3*recsize; if ((buf = (char *) malloc(bufsz)) == NULL) FATAL("out of memory in awksprintf"); y = a[0]->nnext; x = execute(a[0]); if (format(&buf, &bufsz, getsval(x), y) == -1) FATAL("sprintf string %.30s... too long. can't happen.", buf); tempfree(x); x = gettemp(); x->sval = buf; x->tval = STR; return(x); } Cell *awkprintf(Node **a, int n) /* printf */ { /* a[0] is list of args, starting with format string */ /* a[1] is redirection operator, a[2] is redirection file */ FILE *fp; Cell *x; Node *y; char *buf; int len; int bufsz=3*recsize; if ((buf = (char *) malloc(bufsz)) == NULL) FATAL("out of memory in awkprintf"); y = a[0]->nnext; x = execute(a[0]); if ((len = format(&buf, &bufsz, getsval(x), y)) == -1) FATAL("printf string %.30s... too long. can't happen.", buf); tempfree(x); if (a[1] == NULL) { /* fputs(buf, stdout); */ fwrite(buf, len, 1, stdout); if (ferror(stdout)) FATAL("write error on stdout"); } else { fp = redirect(ptoi(a[1]), a[2]); /* fputs(buf, fp); */ fwrite(buf, len, 1, fp); fflush(fp); if (ferror(fp)) FATAL("write error on %s", filename(fp)); } free(buf); return(True); } Cell *arith(Node **a, int n) /* a[0] + a[1], etc. also -a[0] */ { Awkfloat i, j = 0; double v; Cell *x, *y, *z; x = execute(a[0]); i = getfval(x); tempfree(x); if (n != UMINUS && n != UPLUS) { y = execute(a[1]); j = getfval(y); tempfree(y); } z = gettemp(); switch (n) { case ADD: i += j; break; case MINUS: i -= j; break; case MULT: i *= j; break; case DIVIDE: if (j == 0) FATAL("division by zero"); i /= j; break; case MOD: if (j == 0) FATAL("division by zero in mod"); modf(i/j, &v); i = i - j * v; break; case UMINUS: i = -i; break; case UPLUS: /* handled by getfval(), above */ break; case POWER: if (j >= 0 && modf(j, &v) == 0.0) /* pos integer exponent */ i = ipow(i, (int) j); else { errno = 0; i = errcheck(pow(i, j), "pow"); } break; default: /* can't happen */ FATAL("illegal arithmetic operator %d", n); } setfval(z, i); return(z); } double ipow(double x, int n) /* x**n. ought to be done by pow, but isn't always */ { double v; if (n <= 0) return 1; v = ipow(x, n/2); if (n % 2 == 0) return v * v; else return x * v * v; } Cell *incrdecr(Node **a, int n) /* a[0]++, etc. */ { Cell *x, *z; int k; Awkfloat xf; x = execute(a[0]); xf = getfval(x); k = (n == PREINCR || n == POSTINCR) ? 1 : -1; if (n == PREINCR || n == PREDECR) { setfval(x, xf + k); return(x); } z = gettemp(); setfval(z, xf); setfval(x, xf + k); tempfree(x); return(z); } Cell *assign(Node **a, int n) /* a[0] = a[1], a[0] += a[1], etc. */ { /* this is subtle; don't muck with it. */ Cell *x, *y; Awkfloat xf, yf; double v; y = execute(a[1]); x = execute(a[0]); if (n == ASSIGN) { /* ordinary assignment */ if (x == y && !(x->tval & (FLD|REC)) && x != nfloc) ; /* self-assignment: leave alone unless it's a field or NF */ else if ((y->tval & (STR|NUM)) == (STR|NUM)) { yf = getfval(y); setsval(x, getsval(y)); x->fval = yf; x->tval |= NUM; } else if (isstr(y)) setsval(x, getsval(y)); else if (isnum(y)) setfval(x, getfval(y)); else funnyvar(y, "read value of"); tempfree(y); return(x); } xf = getfval(x); yf = getfval(y); switch (n) { case ADDEQ: xf += yf; break; case SUBEQ: xf -= yf; break; case MULTEQ: xf *= yf; break; case DIVEQ: if (yf == 0) FATAL("division by zero in /="); xf /= yf; break; case MODEQ: if (yf == 0) FATAL("division by zero in %%="); modf(xf/yf, &v); xf = xf - yf * v; break; case POWEQ: if (yf >= 0 && modf(yf, &v) == 0.0) /* pos integer exponent */ xf = ipow(xf, (int) yf); else { errno = 0; xf = errcheck(pow(xf, yf), "pow"); } break; default: FATAL("illegal assignment operator %d", n); break; } tempfree(y); setfval(x, xf); return(x); } Cell *cat(Node **a, int q) /* a[0] cat a[1] */ { Cell *x, *y, *z; int n1, n2; char *s = NULL; int ssz = 0; x = execute(a[0]); n1 = strlen(getsval(x)); adjbuf(&s, &ssz, n1 + 1, recsize, 0, "cat1"); memcpy(s, x->sval, n1); tempfree(x); y = execute(a[1]); n2 = strlen(getsval(y)); adjbuf(&s, &ssz, n1 + n2 + 1, recsize, 0, "cat2"); memcpy(s + n1, y->sval, n2); s[n1 + n2] = '\0'; tempfree(y); z = gettemp(); z->sval = s; z->tval = STR; return(z); } Cell *pastat(Node **a, int n) /* a[0] { a[1] } */ { Cell *x; if (a[0] == NULL) x = execute(a[1]); else { x = execute(a[0]); if (istrue(x)) { tempfree(x); x = execute(a[1]); } } return x; } Cell *dopa2(Node **a, int n) /* a[0], a[1] { a[2] } */ { Cell *x; int pair; pair = ptoi(a[3]); if (pairstack[pair] == 0) { x = execute(a[0]); if (istrue(x)) pairstack[pair] = 1; tempfree(x); } if (pairstack[pair] == 1) { x = execute(a[1]); if (istrue(x)) pairstack[pair] = 0; tempfree(x); x = execute(a[2]); return(x); } return(False); } Cell *split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ { Cell *x = NULL, *y, *ap; const char *s, *origs, *t; const char *fs = NULL; char *origfs = NULL; int sep; char temp, num[50]; int n, tempstat, arg3type; int j; double result; y = execute(a[0]); /* source string */ origs = s = strdup(getsval(y)); tempfree(y); arg3type = ptoi(a[3]); if (a[2] == NULL) { /* BUG: CSV should override implicit fs but not explicit */ fs = getsval(fsloc); } else if (arg3type == STRING) { /* split(str,arr,"string") */ x = execute(a[2]); fs = origfs = strdup(getsval(x)); tempfree(x); } else if (arg3type == REGEXPR) { fs = "(regexpr)"; /* split(str,arr,/regexpr/) */ } else { FATAL("illegal type of split"); } sep = *fs; ap = execute(a[1]); /* array name */ /* BUG 7/26/22: this appears not to reset array: see C1/asplit */ freesymtab(ap); DPRINTF("split: s=|%s|, a=%s, sep=|%s|\n", s, NN(ap->nval), fs); ap->tval &= ~STR; ap->tval |= ARR; ap->sval = (char *) makesymtab(NSYMTAB); n = 0; if (arg3type == REGEXPR && strlen((char*)((fa*)a[2])->restr) == 0) { /* split(s, a, //); have to arrange that it looks like empty sep */ arg3type = 0; fs = ""; sep = 0; } if (*s != '\0' && (strlen(fs) > 1 || arg3type == REGEXPR)) { /* reg expr */ fa *pfa; if (arg3type == REGEXPR) { /* it's ready already */ pfa = (fa *) a[2]; } else { pfa = makedfa(fs, 1); } if (nematch(pfa,s)) { tempstat = pfa->initstat; pfa->initstat = 2; do { n++; snprintf(num, sizeof(num), "%d", n); temp = *patbeg; setptr(patbeg, '\0'); if (is_number(s, & result)) setsymtab(num, s, result, STR|NUM, (Array *) ap->sval); else setsymtab(num, s, 0.0, STR, (Array *) ap->sval); setptr(patbeg, temp); s = patbeg + patlen; if (*(patbeg+patlen-1) == '\0' || *s == '\0') { n++; snprintf(num, sizeof(num), "%d", n); setsymtab(num, "", 0.0, STR, (Array *) ap->sval); pfa->initstat = tempstat; goto spdone; } } while (nematch(pfa,s)); pfa->initstat = tempstat; /* bwk: has to be here to reset */ /* cf gsub and refldbld */ } n++; snprintf(num, sizeof(num), "%d", n); if (is_number(s, & result)) setsymtab(num, s, result, STR|NUM, (Array *) ap->sval); else setsymtab(num, s, 0.0, STR, (Array *) ap->sval); spdone: pfa = NULL; } else if (a[2] == NULL && CSV) { /* CSV only if no explicit separator */ char *newt = (char *) malloc(strlen(s)); /* for building new string; reuse for each field */ for (;;) { char *fr = newt; n++; if (*s == '"' ) { /* start of "..." */ for (s++ ; *s != '\0'; ) { if (*s == '"' && s[1] != '\0' && s[1] == '"') { s += 2; /* doubled quote */ *fr++ = '"'; } else if (*s == '"' && (s[1] == '\0' || s[1] == ',')) { s++; /* skip over closing quote */ break; } else { *fr++ = *s++; } } *fr++ = 0; } else { /* unquoted field */ while (*s != ',' && *s != '\0') *fr++ = *s++; *fr++ = 0; } snprintf(num, sizeof(num), "%d", n); if (is_number(newt, &result)) setsymtab(num, newt, result, STR|NUM, (Array *) ap->sval); else setsymtab(num, newt, 0.0, STR, (Array *) ap->sval); if (*s++ == '\0') break; } free(newt); } else if (!CSV && sep == ' ') { /* usual case: split on white space */ for (n = 0; ; ) { #define ISWS(c) ((c) == ' ' || (c) == '\t' || (c) == '\n') while (ISWS(*s)) s++; if (*s == '\0') break; n++; t = s; do s++; while (*s != '\0' && !ISWS(*s)); temp = *s; setptr(s, '\0'); snprintf(num, sizeof(num), "%d", n); if (is_number(t, & result)) setsymtab(num, t, result, STR|NUM, (Array *) ap->sval); else setsymtab(num, t, 0.0, STR, (Array *) ap->sval); setptr(s, temp); if (*s != '\0') s++; } } else if (sep == 0) { /* new: split(s, a, "") => 1 char/elem */ for (n = 0; *s != '\0'; s += u8_nextlen(s)) { char buf[10]; n++; snprintf(num, sizeof(num), "%d", n); for (j = 0; j < u8_nextlen(s); j++) { buf[j] = s[j]; } buf[j] = '\0'; if (isdigit((uschar)buf[0])) setsymtab(num, buf, atof(buf), STR|NUM, (Array *) ap->sval); else setsymtab(num, buf, 0.0, STR, (Array *) ap->sval); } } else if (*s != '\0') { /* some random single character */ for (;;) { n++; t = s; while (*s != sep && *s != '\0') s++; temp = *s; setptr(s, '\0'); snprintf(num, sizeof(num), "%d", n); if (is_number(t, & result)) setsymtab(num, t, result, STR|NUM, (Array *) ap->sval); else setsymtab(num, t, 0.0, STR, (Array *) ap->sval); setptr(s, temp); if (*s++ == '\0') break; } } tempfree(ap); xfree(origs); xfree(origfs); x = gettemp(); x->tval = NUM; x->fval = n; return(x); } Cell *condexpr(Node **a, int n) /* a[0] ? a[1] : a[2] */ { Cell *x; x = execute(a[0]); if (istrue(x)) { tempfree(x); x = execute(a[1]); } else { tempfree(x); x = execute(a[2]); } return(x); } Cell *ifstat(Node **a, int n) /* if (a[0]) a[1]; else a[2] */ { Cell *x; x = execute(a[0]); if (istrue(x)) { tempfree(x); x = execute(a[1]); } else if (a[2] != NULL) { tempfree(x); x = execute(a[2]); } return(x); } Cell *whilestat(Node **a, int n) /* while (a[0]) a[1] */ { Cell *x; for (;;) { x = execute(a[0]); if (!istrue(x)) return(x); tempfree(x); x = execute(a[1]); if (isbreak(x)) { x = True; return(x); } if (isnext(x) || isexit(x) || isret(x)) return(x); tempfree(x); } } Cell *dostat(Node **a, int n) /* do a[0]; while(a[1]) */ { Cell *x; for (;;) { x = execute(a[0]); if (isbreak(x)) return True; if (isnext(x) || isexit(x) || isret(x)) return(x); tempfree(x); x = execute(a[1]); if (!istrue(x)) return(x); tempfree(x); } } Cell *forstat(Node **a, int n) /* for (a[0]; a[1]; a[2]) a[3] */ { Cell *x; x = execute(a[0]); tempfree(x); for (;;) { if (a[1]!=NULL) { x = execute(a[1]); if (!istrue(x)) return(x); else tempfree(x); } x = execute(a[3]); if (isbreak(x)) /* turn off break */ return True; if (isnext(x) || isexit(x) || isret(x)) return(x); tempfree(x); x = execute(a[2]); tempfree(x); } } Cell *instat(Node **a, int n) /* for (a[0] in a[1]) a[2] */ { Cell *x, *vp, *arrayp, *cp, *ncp; Array *tp; int i; vp = execute(a[0]); arrayp = execute(a[1]); if (!isarr(arrayp)) { return True; } tp = (Array *) arrayp->sval; tempfree(arrayp); for (i = 0; i < tp->size; i++) { /* this routine knows too much */ for (cp = tp->tab[i]; cp != NULL; cp = ncp) { setsval(vp, cp->nval); ncp = cp->cnext; x = execute(a[2]); if (isbreak(x)) { tempfree(vp); return True; } if (isnext(x) || isexit(x) || isret(x)) { tempfree(vp); return(x); } tempfree(x); } } return True; } static char *nawk_convert(const char *s, int (*fun_c)(int), wint_t (*fun_wc)(wint_t)) { char *buf = NULL; char *pbuf = NULL; const char *ps = NULL; size_t n = 0; wchar_t wc; const size_t sz = awk_mb_cur_max; int unused; if (sz == 1) { buf = tostring(s); for (pbuf = buf; *pbuf; pbuf++) *pbuf = fun_c((uschar)*pbuf); return buf; } else { /* upper/lower character may be shorter/longer */ buf = tostringN(s, strlen(s) * sz + 1); (void) mbtowc(NULL, NULL, 0); /* reset internal state */ /* * Reset internal state here too. * Assign result to avoid a compiler warning. (Casting to void * doesn't work.) * Increment said variable to avoid a different warning. */ unused = wctomb(NULL, L'\0'); unused++; ps = s; pbuf = buf; while (n = mbtowc(&wc, ps, sz), n > 0 && n != (size_t)-1 && n != (size_t)-2) { ps += n; n = wctomb(pbuf, fun_wc(wc)); if (n == (size_t)-1) FATAL("illegal wide character %s", s); pbuf += n; } *pbuf = '\0'; if (n) FATAL("illegal byte sequence %s", s); return buf; } } #ifdef __DJGPP__ static wint_t towupper(wint_t wc) { if (wc >= 0 && wc < 256) return toupper(wc & 0xFF); return wc; } static wint_t towlower(wint_t wc) { if (wc >= 0 && wc < 256) return tolower(wc & 0xFF); return wc; } #endif static char *nawk_toupper(const char *s) { return nawk_convert(s, toupper, towupper); } static char *nawk_tolower(const char *s) { return nawk_convert(s, tolower, towlower); } Cell *bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */ { Cell *x, *y; Awkfloat u; - int t; + int t, sz; Awkfloat tmp; - char *buf; + char *buf, *fmt; Node *nextarg; FILE *fp; int status = 0; + time_t tv; + struct tm *tm; int estatus = 0; t = ptoi(a[0]); x = execute(a[1]); nextarg = a[1]->nnext; switch (t) { case FLENGTH: if (isarr(x)) u = ((Array *) x->sval)->nelem; /* GROT. should be function*/ else u = u8_strlen(getsval(x)); break; case FLOG: errno = 0; u = errcheck(log(getfval(x)), "log"); break; case FINT: modf(getfval(x), &u); break; case FEXP: errno = 0; u = errcheck(exp(getfval(x)), "exp"); break; case FSQRT: errno = 0; u = errcheck(sqrt(getfval(x)), "sqrt"); break; case FSIN: u = sin(getfval(x)); break; case FCOS: u = cos(getfval(x)); break; case FATAN: if (nextarg == NULL) { WARNING("atan2 requires two arguments; returning 1.0"); u = 1.0; } else { y = execute(a[1]->nnext); u = atan2(getfval(x), getfval(y)); tempfree(y); nextarg = nextarg->nnext; } break; + case FCOMPL: + u = ~((int)getfval(x)); + break; + case FAND: + if (nextarg == 0) { + WARNING("and requires two arguments; returning 0"); + u = 0; + break; + } + y = execute(a[1]->nnext); + u = ((int)getfval(x)) & ((int)getfval(y)); + tempfree(y); + nextarg = nextarg->nnext; + break; + case FFOR: + if (nextarg == 0) { + WARNING("or requires two arguments; returning 0"); + u = 0; + break; + } + y = execute(a[1]->nnext); + u = ((int)getfval(x)) | ((int)getfval(y)); + tempfree(y); + nextarg = nextarg->nnext; + break; + case FXOR: + if (nextarg == 0) { + WARNING("xor requires two arguments; returning 0"); + u = 0; + break; + } + y = execute(a[1]->nnext); + u = ((int)getfval(x)) ^ ((int)getfval(y)); + tempfree(y); + nextarg = nextarg->nnext; + break; + case FLSHIFT: + if (nextarg == 0) { + WARNING("lshift requires two arguments; returning 0"); + u = 0; + break; + } + y = execute(a[1]->nnext); + u = ((int)getfval(x)) << ((int)getfval(y)); + tempfree(y); + nextarg = nextarg->nnext; + break; + case FRSHIFT: + if (nextarg == 0) { + WARNING("rshift requires two arguments; returning 0"); + u = 0; + break; + } + y = execute(a[1]->nnext); + u = ((int)getfval(x)) >> ((int)getfval(y)); + tempfree(y); + nextarg = nextarg->nnext; + break; case FSYSTEM: fflush(stdout); /* in case something is buffered already */ estatus = status = system(getsval(x)); if (status != -1) { if (WIFEXITED(status)) { estatus = WEXITSTATUS(status); } else if (WIFSIGNALED(status)) { estatus = WTERMSIG(status) + 256; #ifdef WCOREDUMP if (WCOREDUMP(status)) estatus += 256; #endif } else /* something else?!? */ estatus = 0; } /* else estatus was set to -1 */ u = estatus; break; case FRAND: /* random() returns numbers in [0..2^31-1] * in order to get a number in [0, 1), divide it by 2^31 */ u = (Awkfloat) random() / (0x7fffffffL + 0x1UL); break; case FSRAND: if (isrec(x)) /* no argument provided */ u = time((time_t *)0); else u = getfval(x); tmp = u; srandom((unsigned long) u); u = srand_seed; srand_seed = tmp; break; case FTOUPPER: case FTOLOWER: if (t == FTOUPPER) buf = nawk_toupper(getsval(x)); else buf = nawk_tolower(getsval(x)); tempfree(x); x = gettemp(); setsval(x, buf); free(buf); return x; case FFLUSH: if (isrec(x) || strlen(getsval(x)) == 0) { flush_all(); /* fflush() or fflush("") -> all */ u = 0; } else if ((fp = openfile(FFLUSH, getsval(x), NULL)) == NULL) u = EOF; else u = fflush(fp); break; + case FSYSTIME: + u = time((time_t *) 0); + break; + case FSTRFTIME: + /* strftime([format [,timestamp]]) */ + if (nextarg) { + y = execute(nextarg); + nextarg = nextarg->nnext; + tv = (time_t) getfval(y); + tempfree(y); + } else + tv = time((time_t *) 0); + tm = localtime(&tv); + if (tm == NULL) + FATAL("bad time %ld", (long)tv); + + if (isrec(x)) { + /* format argument not provided, use default */ + fmt = tostring("%a %b %d %H:%M:%S %Z %Y"); + } else + fmt = tostring(getsval(x)); + + sz = 32; + buf = NULL; + do { + if ((buf = realloc(buf, (sz *= 2))) == NULL) + FATAL("out of memory in strftime"); + } while (strftime(buf, sz, fmt, tm) == 0 && fmt[0] != '\0'); + + y = gettemp(); + setsval(y, buf); + free(fmt); + free(buf); + + return y; default: /* can't happen */ FATAL("illegal function type %d", t); break; } tempfree(x); x = gettemp(); setfval(x, u); if (nextarg != NULL) { WARNING("warning: function has too many arguments"); for ( ; nextarg; nextarg = nextarg->nnext) { y = execute(nextarg); tempfree(y); } } return(x); } Cell *printstat(Node **a, int n) /* print a[0] */ { Node *x; Cell *y; FILE *fp; if (a[1] == NULL) /* a[1] is redirection operator, a[2] is file */ fp = stdout; else fp = redirect(ptoi(a[1]), a[2]); for (x = a[0]; x != NULL; x = x->nnext) { y = execute(x); fputs(getpssval(y), fp); tempfree(y); if (x->nnext == NULL) fputs(getsval(orsloc), fp); else fputs(getsval(ofsloc), fp); } if (a[1] != NULL) fflush(fp); if (ferror(fp)) FATAL("write error on %s", filename(fp)); return(True); } Cell *nullproc(Node **a, int n) { return 0; } FILE *redirect(int a, Node *b) /* set up all i/o redirections */ { FILE *fp; Cell *x; char *fname; x = execute(b); fname = getsval(x); fp = openfile(a, fname, NULL); if (fp == NULL) FATAL("can't open file %s", fname); tempfree(x); return fp; } struct files { FILE *fp; const char *fname; int mode; /* '|', 'a', 'w' => LE/LT, GT */ } *files; size_t nfiles; static void stdinit(void) /* in case stdin, etc., are not constants */ { nfiles = FOPEN_MAX; files = (struct files *) calloc(nfiles, sizeof(*files)); if (files == NULL) FATAL("can't allocate file memory for %zu files", nfiles); files[0].fp = stdin; files[0].fname = tostring("/dev/stdin"); files[0].mode = LT; files[1].fp = stdout; files[1].fname = tostring("/dev/stdout"); files[1].mode = GT; files[2].fp = stderr; files[2].fname = tostring("/dev/stderr"); files[2].mode = GT; } FILE *openfile(int a, const char *us, bool *pnewflag) { const char *s = us; size_t i; int m; FILE *fp = NULL; if (*s == '\0') FATAL("null file name in print or getline"); for (i = 0; i < nfiles; i++) if (files[i].fname && strcmp(s, files[i].fname) == 0 && (a == files[i].mode || (a==APPEND && files[i].mode==GT) || a == FFLUSH)) { if (pnewflag) *pnewflag = false; return files[i].fp; } if (a == FFLUSH) /* didn't find it, so don't create it! */ return NULL; for (i = 0; i < nfiles; i++) if (files[i].fp == NULL) break; if (i >= nfiles) { struct files *nf; size_t nnf = nfiles + FOPEN_MAX; nf = (struct files *) realloc(files, nnf * sizeof(*nf)); if (nf == NULL) FATAL("cannot grow files for %s and %zu files", s, nnf); memset(&nf[nfiles], 0, FOPEN_MAX * sizeof(*nf)); nfiles = nnf; files = nf; } fflush(stdout); /* force a semblance of order */ m = a; if (a == GT) { fp = fopen(s, "w"); } else if (a == APPEND) { fp = fopen(s, "a"); m = GT; /* so can mix > and >> */ } else if (a == '|') { /* output pipe */ fp = popen(s, "w"); } else if (a == LE) { /* input pipe */ fp = popen(s, "r"); } else if (a == LT) { /* getline sval, files[i].fname) != 0) continue; if (files[i].mode == GT || files[i].mode == '|') fflush(files[i].fp); if (ferror(files[i].fp)) { if ((files[i].mode == GT && files[i].fp != stderr) || files[i].mode == '|') FATAL("write error on %s", files[i].fname); else WARNING("i/o error occurred on %s", files[i].fname); } if (files[i].fp == stdin || files[i].fp == stdout || files[i].fp == stderr) stat = freopen("/dev/null", "r+", files[i].fp) == NULL; else if (files[i].mode == '|' || files[i].mode == LE) stat = pclose(files[i].fp) == -1; else stat = fclose(files[i].fp) == EOF; if (stat) WARNING("i/o error occurred closing %s", files[i].fname); xfree(files[i].fname); files[i].fname = NULL; /* watch out for ref thru this */ files[i].fp = NULL; break; } tempfree(x); x = gettemp(); setfval(x, (Awkfloat) (stat ? -1 : 0)); return(x); } void closeall(void) { size_t i; bool stat = false; for (i = 0; i < nfiles; i++) { if (! files[i].fp) continue; if (files[i].mode == GT || files[i].mode == '|') fflush(files[i].fp); if (ferror(files[i].fp)) { if ((files[i].mode == GT && files[i].fp != stderr) || files[i].mode == '|') FATAL("write error on %s", files[i].fname); else WARNING("i/o error occurred on %s", files[i].fname); } if (files[i].fp == stdin || files[i].fp == stdout || files[i].fp == stderr) continue; if (files[i].mode == '|' || files[i].mode == LE) stat = pclose(files[i].fp) == -1; else stat = fclose(files[i].fp) == EOF; if (stat) WARNING("i/o error occurred while closing %s", files[i].fname); } } static void flush_all(void) { size_t i; for (i = 0; i < nfiles; i++) if (files[i].fp) fflush(files[i].fp); } void backsub(char **pb_ptr, const char **sptr_ptr); Cell *dosub(Node **a, int subop) /* sub and gsub */ { fa *pfa; int tempstat = 0; char *repl; Cell *x; char *buf = NULL; char *pb = NULL; int bufsz = recsize; const char *r, *s; const char *start; const char *noempty = NULL; /* empty match disallowed here */ size_t m = 0; /* match count */ size_t whichm; /* which match to select, 0 = global */ int mtype; /* match type */ if (a[0] == NULL) { /* 0 => a[1] is already-compiled regexpr */ pfa = (fa *) a[1]; } else { x = execute(a[1]); pfa = makedfa(getsval(x), 1); tempfree(x); } x = execute(a[2]); /* replacement string */ repl = tostring(getsval(x)); tempfree(x); switch (subop) { case SUB: whichm = 1; x = execute(a[3]); /* source string */ break; case GSUB: whichm = 0; x = execute(a[3]); /* source string */ break; default: FATAL("dosub: unrecognized subop: %d", subop); } start = getsval(x); while (pmatch(pfa, start)) { if (buf == NULL) { if ((pb = buf = (char *) malloc(bufsz)) == NULL) FATAL("out of memory in dosub"); tempstat = pfa->initstat; pfa->initstat = 2; } /* match types */ #define MT_IGNORE 0 /* unselected or invalid */ #define MT_INSERT 1 /* selected, empty */ #define MT_REPLACE 2 /* selected, not empty */ /* an empty match just after replacement is invalid */ if (patbeg == noempty && patlen == 0) { mtype = MT_IGNORE; /* invalid, not counted */ } else if (whichm == ++m || whichm == 0) { mtype = patlen ? MT_REPLACE : MT_INSERT; } else { mtype = MT_IGNORE; /* unselected, but counted */ } /* leading text: */ if (patbeg > start) { adjbuf(&buf, &bufsz, (pb - buf) + (patbeg - start), recsize, &pb, "dosub"); s = start; while (s < patbeg) *pb++ = *s++; } if (mtype == MT_IGNORE) goto matching_text; /* skip replacement text */ r = repl; while (*r != 0) { adjbuf(&buf, &bufsz, 5+pb-buf, recsize, &pb, "dosub"); if (*r == '\\') { backsub(&pb, &r); } else if (*r == '&') { r++; adjbuf(&buf, &bufsz, 1+patlen+pb-buf, recsize, &pb, "dosub"); for (s = patbeg; s < patbeg+patlen; ) *pb++ = *s++; } else { *pb++ = *r++; } } matching_text: if (mtype == MT_REPLACE || *patbeg == '\0') goto next_search; /* skip matching text */ if (patlen == 0) patlen = u8_nextlen(patbeg); adjbuf(&buf, &bufsz, (pb-buf) + patlen, recsize, &pb, "dosub"); s = patbeg; while (s < patbeg + patlen) *pb++ = *s++; next_search: start = patbeg + patlen; if (m == whichm || *patbeg == '\0') break; if (mtype == MT_REPLACE) noempty = start; #undef MT_IGNORE #undef MT_INSERT #undef MT_REPLACE } xfree(repl); if (buf != NULL) { pfa->initstat = tempstat; /* trailing text */ adjbuf(&buf, &bufsz, 1+strlen(start)+pb-buf, 0, &pb, "dosub"); while ((*pb++ = *start++) != '\0') ; setsval(x, buf); free(buf); } tempfree(x); x = gettemp(); x->tval = NUM; x->fval = m; return x; } +Cell *gensub(Node **a, int nnn) /* global selective substitute */ + /* XXX incomplete - doesn't support backreferences \0 ... \9 */ +{ + Cell *x, *y, *res, *h; + char *rptr; + const char *sptr; + char *buf, *pb; + const char *t, *q; + fa *pfa; + int mflag, tempstat, num, whichm; + int bufsz = recsize; + + if ((buf = malloc(bufsz)) == NULL) + FATAL("out of memory in gensub"); + mflag = 0; /* if mflag == 0, can replace empty string */ + num = 0; + x = execute(a[4]); /* source string */ + t = getsval(x); + res = copycell(x); /* target string - initially copy of source */ + res->csub = CTEMP; /* result values are temporary */ + if (a[0] == 0) /* 0 => a[1] is already-compiled regexpr */ + pfa = (fa *) a[1]; /* regular expression */ + else { + y = execute(a[1]); + pfa = makedfa(getsval(y), 1); + tempfree(y); + } + y = execute(a[2]); /* replacement string */ + h = execute(a[3]); /* which matches should be replaced */ + sptr = getsval(h); + if (sptr[0] == 'g' || sptr[0] == 'G') + whichm = -1; + else { + /* + * The specified number is index of replacement, starting + * from 1. GNU awk treats index lower than 0 same as + * 1, we do same for compatibility. + */ + whichm = (int) getfval(h) - 1; + if (whichm < 0) + whichm = 0; + } + tempfree(h); + + if (pmatch(pfa, t)) { + char *sl; + + tempstat = pfa->initstat; + pfa->initstat = 2; + pb = buf; + rptr = getsval(y); + /* + * XXX if there are any backreferences in subst string, + * complain now. + */ + for (sl = rptr; (sl = strchr(sl, '\\')) && sl[1]; sl++) { + if (strchr("0123456789", sl[1])) { + FATAL("gensub doesn't support backreferences (subst \"%s\")", rptr); + } + } + + do { + if (whichm >= 0 && whichm != num) { + num++; + adjbuf(&buf, &bufsz, (pb - buf) + (patbeg - t) + patlen, recsize, &pb, "gensub"); + + /* copy the part of string up to and including + * match to output buffer */ + while (t < patbeg + patlen) + *pb++ = *t++; + continue; + } + + if (patlen == 0 && *patbeg != 0) { /* matched empty string */ + if (mflag == 0) { /* can replace empty */ + num++; + sptr = rptr; + while (*sptr != 0) { + adjbuf(&buf, &bufsz, 5+pb-buf, recsize, &pb, "gensub"); + if (*sptr == '\\') { + backsub(&pb, &sptr); + } else if (*sptr == '&') { + sptr++; + adjbuf(&buf, &bufsz, 1+patlen+pb-buf, recsize, &pb, "gensub"); + for (q = patbeg; q < patbeg+patlen; ) + *pb++ = *q++; + } else + *pb++ = *sptr++; + } + } + if (*t == 0) /* at end */ + goto done; + adjbuf(&buf, &bufsz, 2+pb-buf, recsize, &pb, "gensub"); + *pb++ = *t++; + if (pb > buf + bufsz) /* BUG: not sure of this test */ + FATAL("gensub result0 %.30s too big; can't happen", buf); + mflag = 0; + } + else { /* matched nonempty string */ + num++; + sptr = t; + adjbuf(&buf, &bufsz, 1+(patbeg-sptr)+pb-buf, recsize, &pb, "gensub"); + while (sptr < patbeg) + *pb++ = *sptr++; + sptr = rptr; + while (*sptr != 0) { + adjbuf(&buf, &bufsz, 5+pb-buf, recsize, &pb, "gensub"); + if (*sptr == '\\') { + backsub(&pb, &sptr); + } else if (*sptr == '&') { + sptr++; + adjbuf(&buf, &bufsz, 1+patlen+pb-buf, recsize, &pb, "gensub"); + for (q = patbeg; q < patbeg+patlen; ) + *pb++ = *q++; + } else + *pb++ = *sptr++; + } + t = patbeg + patlen; + if (patlen == 0 || *t == 0 || *(t-1) == 0) + goto done; + if (pb > buf + bufsz) + FATAL("gensub result1 %.30s too big; can't happen", buf); + mflag = 1; + } + } while (pmatch(pfa,t)); + sptr = t; + adjbuf(&buf, &bufsz, 1+strlen(sptr)+pb-buf, 0, &pb, "gensub"); + while ((*pb++ = *sptr++) != 0) + ; + done: if (pb > buf + bufsz) + FATAL("gensub result2 %.30s too big; can't happen", buf); + *pb = '\0'; + setsval(res, buf); + pfa->initstat = tempstat; + } + tempfree(x); + tempfree(y); + free(buf); + return(res); +} + void backsub(char **pb_ptr, const char **sptr_ptr) /* handle \\& variations */ { /* sptr[0] == '\\' */ char *pb = *pb_ptr; const char *sptr = *sptr_ptr; static bool first = true; static bool do_posix = false; if (first) { first = false; do_posix = (getenv("POSIXLY_CORRECT") != NULL); } if (sptr[1] == '\\') { if (sptr[2] == '\\' && sptr[3] == '&') { /* \\\& -> \& */ *pb++ = '\\'; *pb++ = '&'; sptr += 4; } else if (sptr[2] == '&') { /* \\& -> \ + matched */ *pb++ = '\\'; sptr += 2; } else if (do_posix) { /* \\x -> \x */ sptr++; *pb++ = *sptr++; } else { /* \\x -> \\x */ *pb++ = *sptr++; *pb++ = *sptr++; } } else if (sptr[1] == '&') { /* literal & */ sptr++; *pb++ = *sptr++; } else /* literal \ */ *pb++ = *sptr++; *pb_ptr = pb; *sptr_ptr = sptr; } static char *wide_char_to_byte_str(int rune, size_t *outlen) { static char buf[5]; int len; if (rune < 0 || rune > 0x10FFFF) return NULL; memset(buf, 0, sizeof(buf)); len = 0; if (rune <= 0x0000007F) { buf[len++] = rune; } else if (rune <= 0x000007FF) { // 110xxxxx 10xxxxxx buf[len++] = 0xC0 | (rune >> 6); buf[len++] = 0x80 | (rune & 0x3F); } else if (rune <= 0x0000FFFF) { // 1110xxxx 10xxxxxx 10xxxxxx buf[len++] = 0xE0 | (rune >> 12); buf[len++] = 0x80 | ((rune >> 6) & 0x3F); buf[len++] = 0x80 | (rune & 0x3F); } else { // 0x00010000 - 0x10FFFF // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx buf[len++] = 0xF0 | (rune >> 18); buf[len++] = 0x80 | ((rune >> 12) & 0x3F); buf[len++] = 0x80 | ((rune >> 6) & 0x3F); buf[len++] = 0x80 | (rune & 0x3F); } *outlen = len; buf[len++] = '\0'; return buf; }