unexpand: correct behavior for --first-only --tabs=4
[oweals/busybox.git] / editors / awk.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * awk implementation for busybox
4  *
5  * Copyright (C) 2002 by Dmitry Zakharov <dmit@crp.bank.gov.ua>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  */
9 //config:config AWK
10 //config:       bool "awk (23 kb)"
11 //config:       default y
12 //config:       help
13 //config:       Awk is used as a pattern scanning and processing language.
14 //config:
15 //config:config FEATURE_AWK_LIBM
16 //config:       bool "Enable math functions (requires libm)"
17 //config:       default y
18 //config:       depends on AWK
19 //config:       help
20 //config:       Enable math functions of the Awk programming language.
21 //config:       NOTE: This requires libm to be present for linking.
22 //config:
23 //config:config FEATURE_AWK_GNU_EXTENSIONS
24 //config:       bool "Enable a few GNU extensions"
25 //config:       default y
26 //config:       depends on AWK
27 //config:       help
28 //config:       Enable a few features from gawk:
29 //config:       * command line option -e AWK_PROGRAM
30 //config:       * simultaneous use of -f and -e on the command line.
31 //config:       This enables the use of awk library files.
32 //config:       Example: awk -f mylib.awk -e '{print myfunction($1);}' ...
33
34 //applet:IF_AWK(APPLET_NOEXEC(awk, awk, BB_DIR_USR_BIN, BB_SUID_DROP, awk))
35
36 //kbuild:lib-$(CONFIG_AWK) += awk.o
37
38 //usage:#define awk_trivial_usage
39 //usage:       "[OPTIONS] [AWK_PROGRAM] [FILE]..."
40 //usage:#define awk_full_usage "\n\n"
41 //usage:       "        -v VAR=VAL      Set variable"
42 //usage:     "\n        -F SEP          Use SEP as field separator"
43 //usage:     "\n        -f FILE         Read program from FILE"
44 //usage:        IF_FEATURE_AWK_GNU_EXTENSIONS(
45 //usage:     "\n        -e AWK_PROGRAM"
46 //usage:        )
47
48 #include "libbb.h"
49 #include "xregex.h"
50 #include <math.h>
51
52 /* This is a NOEXEC applet. Be very careful! */
53
54
55 /* If you comment out one of these below, it will be #defined later
56  * to perform debug printfs to stderr: */
57 #define debug_printf_walker(...)  do {} while (0)
58 #define debug_printf_eval(...)  do {} while (0)
59 #define debug_printf_parse(...)  do {} while (0)
60
61 #ifndef debug_printf_walker
62 # define debug_printf_walker(...) (fprintf(stderr, __VA_ARGS__))
63 #endif
64 #ifndef debug_printf_eval
65 # define debug_printf_eval(...) (fprintf(stderr, __VA_ARGS__))
66 #endif
67 #ifndef debug_printf_parse
68 # define debug_printf_parse(...) (fprintf(stderr, __VA_ARGS__))
69 #endif
70
71
72 /* "+": stop on first non-option:
73  * $ awk 'BEGIN { for(i=1; i<ARGC; ++i) { print i ": " ARGV[i] }}' -argz
74  * 1: -argz
75  */
76 #define OPTSTR_AWK "+" \
77         "F:v:*f:*" \
78         IF_FEATURE_AWK_GNU_EXTENSIONS("e:*") \
79         "W:"
80 enum {
81         OPTBIT_F,       /* define field separator */
82         OPTBIT_v,       /* define variable */
83         OPTBIT_f,       /* pull in awk program from file */
84         IF_FEATURE_AWK_GNU_EXTENSIONS(OPTBIT_e,) /* -e AWK_PROGRAM */
85         OPTBIT_W,       /* -W ignored */
86         OPT_F = 1 << OPTBIT_F,
87         OPT_v = 1 << OPTBIT_v,
88         OPT_f = 1 << OPTBIT_f,
89         OPT_e = IF_FEATURE_AWK_GNU_EXTENSIONS((1 << OPTBIT_e)) + 0,
90         OPT_W = 1 << OPTBIT_W
91 };
92
93 #define MAXVARFMT       240
94 #define MINNVBLOCK      64
95
96 /* variable flags */
97 #define VF_NUMBER       0x0001  /* 1 = primary type is number */
98 #define VF_ARRAY        0x0002  /* 1 = it's an array */
99
100 #define VF_CACHED       0x0100  /* 1 = num/str value has cached str/num eq */
101 #define VF_USER         0x0200  /* 1 = user input (may be numeric string) */
102 #define VF_SPECIAL      0x0400  /* 1 = requires extra handling when changed */
103 #define VF_WALK         0x0800  /* 1 = variable has alloc'd x.walker list */
104 #define VF_FSTR         0x1000  /* 1 = var::string points to fstring buffer */
105 #define VF_CHILD        0x2000  /* 1 = function arg; x.parent points to source */
106 #define VF_DIRTY        0x4000  /* 1 = variable was set explicitly */
107
108 /* these flags are static, don't change them when value is changed */
109 #define VF_DONTTOUCH    (VF_ARRAY | VF_SPECIAL | VF_WALK | VF_CHILD | VF_DIRTY)
110
111 typedef struct walker_list {
112         char *end;
113         char *cur;
114         struct walker_list *prev;
115         char wbuf[1];
116 } walker_list;
117
118 /* Variable */
119 typedef struct var_s {
120         unsigned type;            /* flags */
121         double number;
122         char *string;
123         union {
124                 int aidx;               /* func arg idx (for compilation stage) */
125                 struct xhash_s *array;  /* array ptr */
126                 struct var_s *parent;   /* for func args, ptr to actual parameter */
127                 walker_list *walker;    /* list of array elements (for..in) */
128         } x;
129 } var;
130
131 /* Node chain (pattern-action chain, BEGIN, END, function bodies) */
132 typedef struct chain_s {
133         struct node_s *first;
134         struct node_s *last;
135         const char *programname;
136 } chain;
137
138 /* Function */
139 typedef struct func_s {
140         unsigned nargs;
141         struct chain_s body;
142 } func;
143
144 /* I/O stream */
145 typedef struct rstream_s {
146         FILE *F;
147         char *buffer;
148         int adv;
149         int size;
150         int pos;
151         smallint is_pipe;
152 } rstream;
153
154 typedef struct hash_item_s {
155         union {
156                 struct var_s v;         /* variable/array hash */
157                 struct rstream_s rs;    /* redirect streams hash */
158                 struct func_s f;        /* functions hash */
159         } data;
160         struct hash_item_s *next;       /* next in chain */
161         char name[1];                   /* really it's longer */
162 } hash_item;
163
164 typedef struct xhash_s {
165         unsigned nel;           /* num of elements */
166         unsigned csize;         /* current hash size */
167         unsigned nprime;        /* next hash size in PRIMES[] */
168         unsigned glen;          /* summary length of item names */
169         struct hash_item_s **items;
170 } xhash;
171
172 /* Tree node */
173 typedef struct node_s {
174         uint32_t info;
175         unsigned lineno;
176         union {
177                 struct node_s *n;
178                 var *v;
179                 int aidx;
180                 char *new_progname;
181                 regex_t *re;
182         } l;
183         union {
184                 struct node_s *n;
185                 regex_t *ire;
186                 func *f;
187         } r;
188         union {
189                 struct node_s *n;
190         } a;
191 } node;
192
193 /* Block of temporary variables */
194 typedef struct nvblock_s {
195         int size;
196         var *pos;
197         struct nvblock_s *prev;
198         struct nvblock_s *next;
199         var nv[];
200 } nvblock;
201
202 typedef struct tsplitter_s {
203         node n;
204         regex_t re[2];
205 } tsplitter;
206
207 /* simple token classes */
208 /* Order and hex values are very important!!!  See next_token() */
209 #define TC_SEQSTART     (1 << 0)                /* ( */
210 #define TC_SEQTERM      (1 << 1)                /* ) */
211 #define TC_REGEXP       (1 << 2)                /* /.../ */
212 #define TC_OUTRDR       (1 << 3)                /* | > >> */
213 #define TC_UOPPOST      (1 << 4)                /* unary postfix operator */
214 #define TC_UOPPRE1      (1 << 5)                /* unary prefix operator */
215 #define TC_BINOPX       (1 << 6)                /* two-opnd operator */
216 #define TC_IN           (1 << 7)
217 #define TC_COMMA        (1 << 8)
218 #define TC_PIPE         (1 << 9)                /* input redirection pipe */
219 #define TC_UOPPRE2      (1 << 10)               /* unary prefix operator */
220 #define TC_ARRTERM      (1 << 11)               /* ] */
221 #define TC_GRPSTART     (1 << 12)               /* { */
222 #define TC_GRPTERM      (1 << 13)               /* } */
223 #define TC_SEMICOL      (1 << 14)
224 #define TC_NEWLINE      (1 << 15)
225 #define TC_STATX        (1 << 16)               /* ctl statement (for, next...) */
226 #define TC_WHILE        (1 << 17)
227 #define TC_ELSE         (1 << 18)
228 #define TC_BUILTIN      (1 << 19)
229 /* This costs ~50 bytes of code.
230  * A separate class to support deprecated "length" form. If we don't need that
231  * (i.e. if we demand that only "length()" with () is valid), then TC_LENGTH
232  * can be merged with TC_BUILTIN:
233  */
234 #define TC_LENGTH       (1 << 20)
235 #define TC_GETLINE      (1 << 21)
236 #define TC_FUNCDECL     (1 << 22)               /* 'function' 'func' */
237 #define TC_BEGIN        (1 << 23)
238 #define TC_END          (1 << 24)
239 #define TC_EOF          (1 << 25)
240 #define TC_VARIABLE     (1 << 26)
241 #define TC_ARRAY        (1 << 27)
242 #define TC_FUNCTION     (1 << 28)
243 #define TC_STRING       (1 << 29)
244 #define TC_NUMBER       (1 << 30)
245
246 #define TC_UOPPRE  (TC_UOPPRE1 | TC_UOPPRE2)
247
248 /* combined token classes */
249 #define TC_BINOP   (TC_BINOPX | TC_COMMA | TC_PIPE | TC_IN)
250 //#define       TC_UNARYOP (TC_UOPPRE | TC_UOPPOST)
251 #define TC_OPERAND (TC_VARIABLE | TC_ARRAY | TC_FUNCTION \
252                    | TC_BUILTIN | TC_LENGTH | TC_GETLINE \
253                    | TC_SEQSTART | TC_STRING | TC_NUMBER)
254
255 #define TC_STATEMNT (TC_STATX | TC_WHILE)
256 #define TC_OPTERM  (TC_SEMICOL | TC_NEWLINE)
257
258 /* word tokens, cannot mean something else if not expected */
259 #define TC_WORD    (TC_IN | TC_STATEMNT | TC_ELSE \
260                    | TC_BUILTIN | TC_LENGTH | TC_GETLINE \
261                    | TC_FUNCDECL | TC_BEGIN | TC_END)
262
263 /* discard newlines after these */
264 #define TC_NOTERM  (TC_COMMA | TC_GRPSTART | TC_GRPTERM \
265                    | TC_BINOP | TC_OPTERM)
266
267 /* what can expression begin with */
268 #define TC_OPSEQ   (TC_OPERAND | TC_UOPPRE | TC_REGEXP)
269 /* what can group begin with */
270 #define TC_GRPSEQ  (TC_OPSEQ | TC_OPTERM | TC_STATEMNT | TC_GRPSTART)
271
272 /* if previous token class is CONCAT1 and next is CONCAT2, concatenation */
273 /* operator is inserted between them */
274 #define TC_CONCAT1 (TC_VARIABLE | TC_ARRTERM | TC_SEQTERM \
275                    | TC_STRING | TC_NUMBER | TC_UOPPOST \
276                    | TC_LENGTH)
277 #define TC_CONCAT2 (TC_OPERAND | TC_UOPPRE)
278
279 #define OF_RES1     0x010000
280 #define OF_RES2     0x020000
281 #define OF_STR1     0x040000
282 #define OF_STR2     0x080000
283 #define OF_NUM1     0x100000
284 #define OF_CHECKED  0x200000
285 #define OF_REQUIRED 0x400000
286
287
288 /* combined operator flags */
289 #define xx      0
290 #define xV      OF_RES2
291 #define xS      (OF_RES2 | OF_STR2)
292 #define Vx      OF_RES1
293 #define Rx      (OF_RES1 | OF_NUM1 | OF_REQUIRED)
294 #define VV      (OF_RES1 | OF_RES2)
295 #define Nx      (OF_RES1 | OF_NUM1)
296 #define NV      (OF_RES1 | OF_NUM1 | OF_RES2)
297 #define Sx      (OF_RES1 | OF_STR1)
298 #define SV      (OF_RES1 | OF_STR1 | OF_RES2)
299 #define SS      (OF_RES1 | OF_STR1 | OF_RES2 | OF_STR2)
300
301 #define OPCLSMASK 0xFF00
302 #define OPNMASK   0x007F
303
304 /* operator priority is a highest byte (even: r->l, odd: l->r grouping)
305  * For builtins it has different meaning: n n s3 s2 s1 v3 v2 v1,
306  * n - min. number of args, vN - resolve Nth arg to var, sN - resolve to string
307  */
308 #undef P
309 #undef PRIMASK
310 #undef PRIMASK2
311 #define P(x)      (x << 24)
312 #define PRIMASK   0x7F000000
313 #define PRIMASK2  0x7E000000
314
315 /* Operation classes */
316
317 #define SHIFT_TIL_THIS  0x0600
318 #define RECUR_FROM_THIS 0x1000
319
320 enum {
321         OC_DELETE = 0x0100,     OC_EXEC = 0x0200,       OC_NEWSOURCE = 0x0300,
322         OC_PRINT = 0x0400,      OC_PRINTF = 0x0500,     OC_WALKINIT = 0x0600,
323
324         OC_BR = 0x0700,         OC_BREAK = 0x0800,      OC_CONTINUE = 0x0900,
325         OC_EXIT = 0x0a00,       OC_NEXT = 0x0b00,       OC_NEXTFILE = 0x0c00,
326         OC_TEST = 0x0d00,       OC_WALKNEXT = 0x0e00,
327
328         OC_BINARY = 0x1000,     OC_BUILTIN = 0x1100,    OC_COLON = 0x1200,
329         OC_COMMA = 0x1300,      OC_COMPARE = 0x1400,    OC_CONCAT = 0x1500,
330         OC_FBLTIN = 0x1600,     OC_FIELD = 0x1700,      OC_FNARG = 0x1800,
331         OC_FUNC = 0x1900,       OC_GETLINE = 0x1a00,    OC_IN = 0x1b00,
332         OC_LAND = 0x1c00,       OC_LOR = 0x1d00,        OC_MATCH = 0x1e00,
333         OC_MOVE = 0x1f00,       OC_PGETLINE = 0x2000,   OC_REGEXP = 0x2100,
334         OC_REPLACE = 0x2200,    OC_RETURN = 0x2300,     OC_SPRINTF = 0x2400,
335         OC_TERNARY = 0x2500,    OC_UNARY = 0x2600,      OC_VAR = 0x2700,
336         OC_DONE = 0x2800,
337
338         ST_IF = 0x3000,         ST_DO = 0x3100,         ST_FOR = 0x3200,
339         ST_WHILE = 0x3300
340 };
341
342 /* simple builtins */
343 enum {
344         F_in,   F_rn,   F_co,   F_ex,   F_lg,   F_si,   F_sq,   F_sr,
345         F_ti,   F_le,   F_sy,   F_ff,   F_cl
346 };
347
348 /* builtins */
349 enum {
350         B_a2,   B_ix,   B_ma,   B_sp,   B_ss,   B_ti,   B_mt,   B_lo,   B_up,
351         B_ge,   B_gs,   B_su,
352         B_an,   B_co,   B_ls,   B_or,   B_rs,   B_xo,
353 };
354
355 /* tokens and their corresponding info values */
356
357 #define NTC     "\377"  /* switch to next token class (tc<<1) */
358 #define NTCC    '\377'
359
360 static const char tokenlist[] ALIGN1 =
361         "\1("         NTC                                   /* TC_SEQSTART */
362         "\1)"         NTC                                   /* TC_SEQTERM */
363         "\1/"         NTC                                   /* TC_REGEXP */
364         "\2>>"        "\1>"         "\1|"       NTC         /* TC_OUTRDR */
365         "\2++"        "\2--"        NTC                     /* TC_UOPPOST */
366         "\2++"        "\2--"        "\1$"       NTC         /* TC_UOPPRE1 */
367         "\2=="        "\1="         "\2+="      "\2-="      /* TC_BINOPX */
368         "\2*="        "\2/="        "\2%="      "\2^="
369         "\1+"         "\1-"         "\3**="     "\2**"
370         "\1/"         "\1%"         "\1^"       "\1*"
371         "\2!="        "\2>="        "\2<="      "\1>"
372         "\1<"         "\2!~"        "\1~"       "\2&&"
373         "\2||"        "\1?"         "\1:"       NTC
374         "\2in"        NTC                                   /* TC_IN */
375         "\1,"         NTC                                   /* TC_COMMA */
376         "\1|"         NTC                                   /* TC_PIPE */
377         "\1+"         "\1-"         "\1!"       NTC         /* TC_UOPPRE2 */
378         "\1]"         NTC                                   /* TC_ARRTERM */
379         "\1{"         NTC                                   /* TC_GRPSTART */
380         "\1}"         NTC                                   /* TC_GRPTERM */
381         "\1;"         NTC                                   /* TC_SEMICOL */
382         "\1\n"        NTC                                   /* TC_NEWLINE */
383         "\2if"        "\2do"        "\3for"     "\5break"   /* TC_STATX */
384         "\10continue" "\6delete"    "\5print"
385         "\6printf"    "\4next"      "\10nextfile"
386         "\6return"    "\4exit"      NTC
387         "\5while"     NTC                                   /* TC_WHILE */
388         "\4else"      NTC                                   /* TC_ELSE */
389         "\3and"       "\5compl"     "\6lshift"  "\2or"      /* TC_BUILTIN */
390         "\6rshift"    "\3xor"
391         "\5close"     "\6system"    "\6fflush"  "\5atan2"
392         "\3cos"       "\3exp"       "\3int"     "\3log"
393         "\4rand"      "\3sin"       "\4sqrt"    "\5srand"
394         "\6gensub"    "\4gsub"      "\5index"   /* "\6length" was here */
395         "\5match"     "\5split"     "\7sprintf" "\3sub"
396         "\6substr"    "\7systime"   "\10strftime" "\6mktime"
397         "\7tolower"   "\7toupper"   NTC
398         "\6length"    NTC                                   /* TC_LENGTH */
399         "\7getline"   NTC                                   /* TC_GETLINE */
400         "\4func"      "\10function" NTC                     /* TC_FUNCDECL */
401         "\5BEGIN"     NTC                                   /* TC_BEGIN */
402         "\3END"                                             /* TC_END */
403         /* compiler adds trailing "\0" */
404         ;
405
406 #define OC_B  OC_BUILTIN
407
408 static const uint32_t tokeninfo[] = {
409         0,
410         0,
411         OC_REGEXP,
412         xS|'a',                  xS|'w',                  xS|'|',
413         OC_UNARY|xV|P(9)|'p',    OC_UNARY|xV|P(9)|'m',
414         OC_UNARY|xV|P(9)|'P',    OC_UNARY|xV|P(9)|'M',    OC_FIELD|xV|P(5),
415         OC_COMPARE|VV|P(39)|5,   OC_MOVE|VV|P(74),        OC_REPLACE|NV|P(74)|'+', OC_REPLACE|NV|P(74)|'-',
416         OC_REPLACE|NV|P(74)|'*', OC_REPLACE|NV|P(74)|'/', OC_REPLACE|NV|P(74)|'%', OC_REPLACE|NV|P(74)|'&',
417         OC_BINARY|NV|P(29)|'+',  OC_BINARY|NV|P(29)|'-',  OC_REPLACE|NV|P(74)|'&', OC_BINARY|NV|P(15)|'&',
418         OC_BINARY|NV|P(25)|'/',  OC_BINARY|NV|P(25)|'%',  OC_BINARY|NV|P(15)|'&',  OC_BINARY|NV|P(25)|'*',
419         OC_COMPARE|VV|P(39)|4,   OC_COMPARE|VV|P(39)|3,   OC_COMPARE|VV|P(39)|0,   OC_COMPARE|VV|P(39)|1,
420         OC_COMPARE|VV|P(39)|2,   OC_MATCH|Sx|P(45)|'!',   OC_MATCH|Sx|P(45)|'~',   OC_LAND|Vx|P(55),
421         OC_LOR|Vx|P(59),         OC_TERNARY|Vx|P(64)|'?', OC_COLON|xx|P(67)|':',
422         OC_IN|SV|P(49), /* TC_IN */
423         OC_COMMA|SS|P(80),
424         OC_PGETLINE|SV|P(37),
425         OC_UNARY|xV|P(19)|'+',   OC_UNARY|xV|P(19)|'-',   OC_UNARY|xV|P(19)|'!',
426         0, /* ] */
427         0,
428         0,
429         0,
430         0, /* \n */
431         ST_IF,        ST_DO,        ST_FOR,      OC_BREAK,
432         OC_CONTINUE,  OC_DELETE|Rx, OC_PRINT,
433         OC_PRINTF,    OC_NEXT,      OC_NEXTFILE,
434         OC_RETURN|Vx, OC_EXIT|Nx,
435         ST_WHILE,
436         0, /* else */
437         OC_B|B_an|P(0x83), OC_B|B_co|P(0x41), OC_B|B_ls|P(0x83), OC_B|B_or|P(0x83),
438         OC_B|B_rs|P(0x83), OC_B|B_xo|P(0x83),
439         OC_FBLTIN|Sx|F_cl, OC_FBLTIN|Sx|F_sy, OC_FBLTIN|Sx|F_ff, OC_B|B_a2|P(0x83),
440         OC_FBLTIN|Nx|F_co, OC_FBLTIN|Nx|F_ex, OC_FBLTIN|Nx|F_in, OC_FBLTIN|Nx|F_lg,
441         OC_FBLTIN|F_rn,    OC_FBLTIN|Nx|F_si, OC_FBLTIN|Nx|F_sq, OC_FBLTIN|Nx|F_sr,
442         OC_B|B_ge|P(0xd6), OC_B|B_gs|P(0xb6), OC_B|B_ix|P(0x9b), /* OC_FBLTIN|Sx|F_le, was here */
443         OC_B|B_ma|P(0x89), OC_B|B_sp|P(0x8b), OC_SPRINTF,        OC_B|B_su|P(0xb6),
444         OC_B|B_ss|P(0x8f), OC_FBLTIN|F_ti,    OC_B|B_ti|P(0x0b), OC_B|B_mt|P(0x0b),
445         OC_B|B_lo|P(0x49), OC_B|B_up|P(0x49),
446         OC_FBLTIN|Sx|F_le, /* TC_LENGTH */
447         OC_GETLINE|SV|P(0),
448         0,                 0,
449         0,
450         0 /* TC_END */
451 };
452
453 /* internal variable names and their initial values       */
454 /* asterisk marks SPECIAL vars; $ is just no-named Field0 */
455 enum {
456         CONVFMT,    OFMT,       FS,         OFS,
457         ORS,        RS,         RT,         FILENAME,
458         SUBSEP,     F0,         ARGIND,     ARGC,
459         ARGV,       ERRNO,      FNR,        NR,
460         NF,         IGNORECASE, ENVIRON,    NUM_INTERNAL_VARS
461 };
462
463 static const char vNames[] ALIGN1 =
464         "CONVFMT\0" "OFMT\0"    "FS\0*"     "OFS\0"
465         "ORS\0"     "RS\0*"     "RT\0"      "FILENAME\0"
466         "SUBSEP\0"  "$\0*"      "ARGIND\0"  "ARGC\0"
467         "ARGV\0"    "ERRNO\0"   "FNR\0"     "NR\0"
468         "NF\0*"     "IGNORECASE\0*" "ENVIRON\0" "\0";
469
470 static const char vValues[] ALIGN1 =
471         "%.6g\0"    "%.6g\0"    " \0"       " \0"
472         "\n\0"      "\n\0"      "\0"        "\0"
473         "\034\0"    "\0"        "\377";
474
475 /* hash size may grow to these values */
476 #define FIRST_PRIME 61
477 static const uint16_t PRIMES[] ALIGN2 = { 251, 1021, 4093, 16381, 65521 };
478
479
480 /* Globals. Split in two parts so that first one is addressed
481  * with (mostly short) negative offsets.
482  * NB: it's unsafe to put members of type "double"
483  * into globals2 (gcc may fail to align them).
484  */
485 struct globals {
486         double t_double;
487         chain beginseq, mainseq, endseq;
488         chain *seq;
489         node *break_ptr, *continue_ptr;
490         rstream *iF;
491         xhash *vhash, *ahash, *fdhash, *fnhash;
492         const char *g_progname;
493         int g_lineno;
494         int nfields;
495         int maxfields; /* used in fsrealloc() only */
496         var *Fields;
497         nvblock *g_cb;
498         char *g_pos;
499         char *g_buf;
500         smallint icase;
501         smallint exiting;
502         smallint nextrec;
503         smallint nextfile;
504         smallint is_f0_split;
505         smallint t_rollback;
506 };
507 struct globals2 {
508         uint32_t t_info; /* often used */
509         uint32_t t_tclass;
510         char *t_string;
511         int t_lineno;
512
513         var *intvar[NUM_INTERNAL_VARS]; /* often used */
514
515         /* former statics from various functions */
516         char *split_f0__fstrings;
517
518         uint32_t next_token__save_tclass;
519         uint32_t next_token__save_info;
520         uint32_t next_token__ltclass;
521         smallint next_token__concat_inserted;
522
523         smallint next_input_file__files_happen;
524         rstream next_input_file__rsm;
525
526         var *evaluate__fnargs;
527         unsigned evaluate__seed;
528         regex_t evaluate__sreg;
529
530         var ptest__v;
531
532         tsplitter exec_builtin__tspl;
533
534         /* biggest and least used members go last */
535         tsplitter fsplitter, rsplitter;
536 };
537 #define G1 (ptr_to_globals[-1])
538 #define G (*(struct globals2 *)ptr_to_globals)
539 /* For debug. nm --size-sort awk.o | grep -vi ' [tr] ' */
540 /*char G1size[sizeof(G1)]; - 0x74 */
541 /*char Gsize[sizeof(G)]; - 0x1c4 */
542 /* Trying to keep most of members accessible with short offsets: */
543 /*char Gofs_seed[offsetof(struct globals2, evaluate__seed)]; - 0x90 */
544 #define t_double     (G1.t_double    )
545 #define beginseq     (G1.beginseq    )
546 #define mainseq      (G1.mainseq     )
547 #define endseq       (G1.endseq      )
548 #define seq          (G1.seq         )
549 #define break_ptr    (G1.break_ptr   )
550 #define continue_ptr (G1.continue_ptr)
551 #define iF           (G1.iF          )
552 #define vhash        (G1.vhash       )
553 #define ahash        (G1.ahash       )
554 #define fdhash       (G1.fdhash      )
555 #define fnhash       (G1.fnhash      )
556 #define g_progname   (G1.g_progname  )
557 #define g_lineno     (G1.g_lineno    )
558 #define nfields      (G1.nfields     )
559 #define maxfields    (G1.maxfields   )
560 #define Fields       (G1.Fields      )
561 #define g_cb         (G1.g_cb        )
562 #define g_pos        (G1.g_pos       )
563 #define g_buf        (G1.g_buf       )
564 #define icase        (G1.icase       )
565 #define exiting      (G1.exiting     )
566 #define nextrec      (G1.nextrec     )
567 #define nextfile     (G1.nextfile    )
568 #define is_f0_split  (G1.is_f0_split )
569 #define t_rollback   (G1.t_rollback  )
570 #define t_info       (G.t_info      )
571 #define t_tclass     (G.t_tclass    )
572 #define t_string     (G.t_string    )
573 #define t_lineno     (G.t_lineno    )
574 #define intvar       (G.intvar      )
575 #define fsplitter    (G.fsplitter   )
576 #define rsplitter    (G.rsplitter   )
577 #define INIT_G() do { \
578         SET_PTR_TO_GLOBALS((char*)xzalloc(sizeof(G1)+sizeof(G)) + sizeof(G1)); \
579         G.next_token__ltclass = TC_OPTERM; \
580         G.evaluate__seed = 1; \
581 } while (0)
582
583
584 /* function prototypes */
585 static void handle_special(var *);
586 static node *parse_expr(uint32_t);
587 static void chain_group(void);
588 static var *evaluate(node *, var *);
589 static rstream *next_input_file(void);
590 static int fmt_num(char *, int, const char *, double, int);
591 static int awk_exit(int) NORETURN;
592
593 /* ---- error handling ---- */
594
595 static const char EMSG_INTERNAL_ERROR[] ALIGN1 = "Internal error";
596 static const char EMSG_UNEXP_EOS[] ALIGN1 = "Unexpected end of string";
597 static const char EMSG_UNEXP_TOKEN[] ALIGN1 = "Unexpected token";
598 static const char EMSG_DIV_BY_ZERO[] ALIGN1 = "Division by zero";
599 static const char EMSG_INV_FMT[] ALIGN1 = "Invalid format specifier";
600 static const char EMSG_TOO_FEW_ARGS[] ALIGN1 = "Too few arguments";
601 static const char EMSG_NOT_ARRAY[] ALIGN1 = "Not an array";
602 static const char EMSG_POSSIBLE_ERROR[] ALIGN1 = "Possible syntax error";
603 static const char EMSG_UNDEF_FUNC[] ALIGN1 = "Call to undefined function";
604 static const char EMSG_NO_MATH[] ALIGN1 = "Math support is not compiled in";
605 static const char EMSG_NEGATIVE_FIELD[] ALIGN1 = "Access to negative field";
606
607 static void zero_out_var(var *vp)
608 {
609         memset(vp, 0, sizeof(*vp));
610 }
611
612 static void syntax_error(const char *message) NORETURN;
613 static void syntax_error(const char *message)
614 {
615         bb_error_msg_and_die("%s:%i: %s", g_progname, g_lineno, message);
616 }
617
618 /* ---- hash stuff ---- */
619
620 static unsigned hashidx(const char *name)
621 {
622         unsigned idx = 0;
623
624         while (*name)
625                 idx = *name++ + (idx << 6) - idx;
626         return idx;
627 }
628
629 /* create new hash */
630 static xhash *hash_init(void)
631 {
632         xhash *newhash;
633
634         newhash = xzalloc(sizeof(*newhash));
635         newhash->csize = FIRST_PRIME;
636         newhash->items = xzalloc(FIRST_PRIME * sizeof(newhash->items[0]));
637
638         return newhash;
639 }
640
641 /* find item in hash, return ptr to data, NULL if not found */
642 static void *hash_search(xhash *hash, const char *name)
643 {
644         hash_item *hi;
645
646         hi = hash->items[hashidx(name) % hash->csize];
647         while (hi) {
648                 if (strcmp(hi->name, name) == 0)
649                         return &hi->data;
650                 hi = hi->next;
651         }
652         return NULL;
653 }
654
655 /* grow hash if it becomes too big */
656 static void hash_rebuild(xhash *hash)
657 {
658         unsigned newsize, i, idx;
659         hash_item **newitems, *hi, *thi;
660
661         if (hash->nprime == ARRAY_SIZE(PRIMES))
662                 return;
663
664         newsize = PRIMES[hash->nprime++];
665         newitems = xzalloc(newsize * sizeof(newitems[0]));
666
667         for (i = 0; i < hash->csize; i++) {
668                 hi = hash->items[i];
669                 while (hi) {
670                         thi = hi;
671                         hi = thi->next;
672                         idx = hashidx(thi->name) % newsize;
673                         thi->next = newitems[idx];
674                         newitems[idx] = thi;
675                 }
676         }
677
678         free(hash->items);
679         hash->csize = newsize;
680         hash->items = newitems;
681 }
682
683 /* find item in hash, add it if necessary. Return ptr to data */
684 static void *hash_find(xhash *hash, const char *name)
685 {
686         hash_item *hi;
687         unsigned idx;
688         int l;
689
690         hi = hash_search(hash, name);
691         if (!hi) {
692                 if (++hash->nel / hash->csize > 10)
693                         hash_rebuild(hash);
694
695                 l = strlen(name) + 1;
696                 hi = xzalloc(sizeof(*hi) + l);
697                 strcpy(hi->name, name);
698
699                 idx = hashidx(name) % hash->csize;
700                 hi->next = hash->items[idx];
701                 hash->items[idx] = hi;
702                 hash->glen += l;
703         }
704         return &hi->data;
705 }
706
707 #define findvar(hash, name) ((var*)    hash_find((hash), (name)))
708 #define newvar(name)        ((var*)    hash_find(vhash, (name)))
709 #define newfile(name)       ((rstream*)hash_find(fdhash, (name)))
710 #define newfunc(name)       ((func*)   hash_find(fnhash, (name)))
711
712 static void hash_remove(xhash *hash, const char *name)
713 {
714         hash_item *hi, **phi;
715
716         phi = &hash->items[hashidx(name) % hash->csize];
717         while (*phi) {
718                 hi = *phi;
719                 if (strcmp(hi->name, name) == 0) {
720                         hash->glen -= (strlen(name) + 1);
721                         hash->nel--;
722                         *phi = hi->next;
723                         free(hi);
724                         break;
725                 }
726                 phi = &hi->next;
727         }
728 }
729
730 /* ------ some useful functions ------ */
731
732 static char *skip_spaces(char *p)
733 {
734         while (1) {
735                 if (*p == '\\' && p[1] == '\n') {
736                         p++;
737                         t_lineno++;
738                 } else if (*p != ' ' && *p != '\t') {
739                         break;
740                 }
741                 p++;
742         }
743         return p;
744 }
745
746 /* returns old *s, advances *s past word and terminating NUL */
747 static char *nextword(char **s)
748 {
749         char *p = *s;
750         while (*(*s)++ != '\0')
751                 continue;
752         return p;
753 }
754
755 static char nextchar(char **s)
756 {
757         char c, *pps;
758
759         c = *(*s)++;
760         pps = *s;
761         if (c == '\\')
762                 c = bb_process_escape_sequence((const char**)s);
763         /* Example awk statement:
764          * s = "abc\"def"
765          * we must treat \" as "
766          */
767         if (c == '\\' && *s == pps) { /* unrecognized \z? */
768                 c = *(*s); /* yes, fetch z */
769                 if (c)
770                         (*s)++; /* advance unless z = NUL */
771         }
772         return c;
773 }
774
775 /* TODO: merge with strcpy_and_process_escape_sequences()?
776  */
777 static void unescape_string_in_place(char *s1)
778 {
779         char *s = s1;
780         while ((*s1 = nextchar(&s)) != '\0')
781                 s1++;
782 }
783
784 static ALWAYS_INLINE int isalnum_(int c)
785 {
786         return (isalnum(c) || c == '_');
787 }
788
789 static double my_strtod(char **pp)
790 {
791         char *cp = *pp;
792         if (ENABLE_DESKTOP && cp[0] == '0') {
793                 /* Might be hex or octal integer: 0x123abc or 07777 */
794                 char c = (cp[1] | 0x20);
795                 if (c == 'x' || isdigit(cp[1])) {
796                         unsigned long long ull = strtoull(cp, pp, 0);
797                         if (c == 'x')
798                                 return ull;
799                         c = **pp;
800                         if (!isdigit(c) && c != '.')
801                                 return ull;
802                         /* else: it may be a floating number. Examples:
803                          * 009.123 (*pp points to '9')
804                          * 000.123 (*pp points to '.')
805                          * fall through to strtod.
806                          */
807                 }
808         }
809         return strtod(cp, pp);
810 }
811
812 /* -------- working with variables (set/get/copy/etc) -------- */
813
814 static xhash *iamarray(var *v)
815 {
816         var *a = v;
817
818         while (a->type & VF_CHILD)
819                 a = a->x.parent;
820
821         if (!(a->type & VF_ARRAY)) {
822                 a->type |= VF_ARRAY;
823                 a->x.array = hash_init();
824         }
825         return a->x.array;
826 }
827
828 static void clear_array(xhash *array)
829 {
830         unsigned i;
831         hash_item *hi, *thi;
832
833         for (i = 0; i < array->csize; i++) {
834                 hi = array->items[i];
835                 while (hi) {
836                         thi = hi;
837                         hi = hi->next;
838                         free(thi->data.v.string);
839                         free(thi);
840                 }
841                 array->items[i] = NULL;
842         }
843         array->glen = array->nel = 0;
844 }
845
846 /* clear a variable */
847 static var *clrvar(var *v)
848 {
849         if (!(v->type & VF_FSTR))
850                 free(v->string);
851
852         v->type &= VF_DONTTOUCH;
853         v->type |= VF_DIRTY;
854         v->string = NULL;
855         return v;
856 }
857
858 /* assign string value to variable */
859 static var *setvar_p(var *v, char *value)
860 {
861         clrvar(v);
862         v->string = value;
863         handle_special(v);
864         return v;
865 }
866
867 /* same as setvar_p but make a copy of string */
868 static var *setvar_s(var *v, const char *value)
869 {
870         return setvar_p(v, (value && *value) ? xstrdup(value) : NULL);
871 }
872
873 /* same as setvar_s but sets USER flag */
874 static var *setvar_u(var *v, const char *value)
875 {
876         v = setvar_s(v, value);
877         v->type |= VF_USER;
878         return v;
879 }
880
881 /* set array element to user string */
882 static void setari_u(var *a, int idx, const char *s)
883 {
884         var *v;
885
886         v = findvar(iamarray(a), itoa(idx));
887         setvar_u(v, s);
888 }
889
890 /* assign numeric value to variable */
891 static var *setvar_i(var *v, double value)
892 {
893         clrvar(v);
894         v->type |= VF_NUMBER;
895         v->number = value;
896         handle_special(v);
897         return v;
898 }
899
900 static const char *getvar_s(var *v)
901 {
902         /* if v is numeric and has no cached string, convert it to string */
903         if ((v->type & (VF_NUMBER | VF_CACHED)) == VF_NUMBER) {
904                 fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[CONVFMT]), v->number, TRUE);
905                 v->string = xstrdup(g_buf);
906                 v->type |= VF_CACHED;
907         }
908         return (v->string == NULL) ? "" : v->string;
909 }
910
911 static double getvar_i(var *v)
912 {
913         char *s;
914
915         if ((v->type & (VF_NUMBER | VF_CACHED)) == 0) {
916                 v->number = 0;
917                 s = v->string;
918                 if (s && *s) {
919                         debug_printf_eval("getvar_i: '%s'->", s);
920                         v->number = my_strtod(&s);
921                         debug_printf_eval("%f (s:'%s')\n", v->number, s);
922                         if (v->type & VF_USER) {
923                                 s = skip_spaces(s);
924                                 if (*s != '\0')
925                                         v->type &= ~VF_USER;
926                         }
927                 } else {
928                         debug_printf_eval("getvar_i: '%s'->zero\n", s);
929                         v->type &= ~VF_USER;
930                 }
931                 v->type |= VF_CACHED;
932         }
933         debug_printf_eval("getvar_i: %f\n", v->number);
934         return v->number;
935 }
936
937 /* Used for operands of bitwise ops */
938 static unsigned long getvar_i_int(var *v)
939 {
940         double d = getvar_i(v);
941
942         /* Casting doubles to longs is undefined for values outside
943          * of target type range. Try to widen it as much as possible */
944         if (d >= 0)
945                 return (unsigned long)d;
946         /* Why? Think about d == -4294967295.0 (assuming 32bit longs) */
947         return - (long) (unsigned long) (-d);
948 }
949
950 static var *copyvar(var *dest, const var *src)
951 {
952         if (dest != src) {
953                 clrvar(dest);
954                 dest->type |= (src->type & ~(VF_DONTTOUCH | VF_FSTR));
955                 debug_printf_eval("copyvar: number:%f string:'%s'\n", src->number, src->string);
956                 dest->number = src->number;
957                 if (src->string)
958                         dest->string = xstrdup(src->string);
959         }
960         handle_special(dest);
961         return dest;
962 }
963
964 static var *incvar(var *v)
965 {
966         return setvar_i(v, getvar_i(v) + 1.0);
967 }
968
969 /* return true if v is number or numeric string */
970 static int is_numeric(var *v)
971 {
972         getvar_i(v);
973         return ((v->type ^ VF_DIRTY) & (VF_NUMBER | VF_USER | VF_DIRTY));
974 }
975
976 /* return 1 when value of v corresponds to true, 0 otherwise */
977 static int istrue(var *v)
978 {
979         if (is_numeric(v))
980                 return (v->number != 0);
981         return (v->string && v->string[0]);
982 }
983
984 /* temporary variables allocator. Last allocated should be first freed */
985 static var *nvalloc(int n)
986 {
987         nvblock *pb = NULL;
988         var *v, *r;
989         int size;
990
991         while (g_cb) {
992                 pb = g_cb;
993                 if ((g_cb->pos - g_cb->nv) + n <= g_cb->size)
994                         break;
995                 g_cb = g_cb->next;
996         }
997
998         if (!g_cb) {
999                 size = (n <= MINNVBLOCK) ? MINNVBLOCK : n;
1000                 g_cb = xzalloc(sizeof(nvblock) + size * sizeof(var));
1001                 g_cb->size = size;
1002                 g_cb->pos = g_cb->nv;
1003                 g_cb->prev = pb;
1004                 /*g_cb->next = NULL; - xzalloc did it */
1005                 if (pb)
1006                         pb->next = g_cb;
1007         }
1008
1009         v = r = g_cb->pos;
1010         g_cb->pos += n;
1011
1012         while (v < g_cb->pos) {
1013                 v->type = 0;
1014                 v->string = NULL;
1015                 v++;
1016         }
1017
1018         return r;
1019 }
1020
1021 static void nvfree(var *v)
1022 {
1023         var *p;
1024
1025         if (v < g_cb->nv || v >= g_cb->pos)
1026                 syntax_error(EMSG_INTERNAL_ERROR);
1027
1028         for (p = v; p < g_cb->pos; p++) {
1029                 if ((p->type & (VF_ARRAY | VF_CHILD)) == VF_ARRAY) {
1030                         clear_array(iamarray(p));
1031                         free(p->x.array->items);
1032                         free(p->x.array);
1033                 }
1034                 if (p->type & VF_WALK) {
1035                         walker_list *n;
1036                         walker_list *w = p->x.walker;
1037                         debug_printf_walker("nvfree: freeing walker @%p\n", &p->x.walker);
1038                         p->x.walker = NULL;
1039                         while (w) {
1040                                 n = w->prev;
1041                                 debug_printf_walker(" free(%p)\n", w);
1042                                 free(w);
1043                                 w = n;
1044                         }
1045                 }
1046                 clrvar(p);
1047         }
1048
1049         g_cb->pos = v;
1050         while (g_cb->prev && g_cb->pos == g_cb->nv) {
1051                 g_cb = g_cb->prev;
1052         }
1053 }
1054
1055 /* ------- awk program text parsing ------- */
1056
1057 /* Parse next token pointed by global pos, place results into global ttt.
1058  * If token isn't expected, give away. Return token class
1059  */
1060 static uint32_t next_token(uint32_t expected)
1061 {
1062 #define concat_inserted (G.next_token__concat_inserted)
1063 #define save_tclass     (G.next_token__save_tclass)
1064 #define save_info       (G.next_token__save_info)
1065 /* Initialized to TC_OPTERM: */
1066 #define ltclass         (G.next_token__ltclass)
1067
1068         char *p, *s;
1069         const char *tl;
1070         uint32_t tc;
1071         const uint32_t *ti;
1072
1073         if (t_rollback) {
1074                 debug_printf_parse("%s: using rolled-back token\n", __func__);
1075                 t_rollback = FALSE;
1076         } else if (concat_inserted) {
1077                 debug_printf_parse("%s: using concat-inserted token\n", __func__);
1078                 concat_inserted = FALSE;
1079                 t_tclass = save_tclass;
1080                 t_info = save_info;
1081         } else {
1082                 p = g_pos;
1083  readnext:
1084                 p = skip_spaces(p);
1085                 g_lineno = t_lineno;
1086                 if (*p == '#')
1087                         while (*p != '\n' && *p != '\0')
1088                                 p++;
1089
1090                 if (*p == '\n')
1091                         t_lineno++;
1092
1093                 if (*p == '\0') {
1094                         tc = TC_EOF;
1095                         debug_printf_parse("%s: token found: TC_EOF\n", __func__);
1096                 } else if (*p == '\"') {
1097                         /* it's a string */
1098                         t_string = s = ++p;
1099                         while (*p != '\"') {
1100                                 char *pp;
1101                                 if (*p == '\0' || *p == '\n')
1102                                         syntax_error(EMSG_UNEXP_EOS);
1103                                 pp = p;
1104                                 *s++ = nextchar(&pp);
1105                                 p = pp;
1106                         }
1107                         p++;
1108                         *s = '\0';
1109                         tc = TC_STRING;
1110                         debug_printf_parse("%s: token found:'%s' TC_STRING\n", __func__, t_string);
1111                 } else if ((expected & TC_REGEXP) && *p == '/') {
1112                         /* it's regexp */
1113                         t_string = s = ++p;
1114                         while (*p != '/') {
1115                                 if (*p == '\0' || *p == '\n')
1116                                         syntax_error(EMSG_UNEXP_EOS);
1117                                 *s = *p++;
1118                                 if (*s++ == '\\') {
1119                                         char *pp = p;
1120                                         s[-1] = bb_process_escape_sequence((const char **)&pp);
1121                                         if (*p == '\\')
1122                                                 *s++ = '\\';
1123                                         if (pp == p)
1124                                                 *s++ = *p++;
1125                                         else
1126                                                 p = pp;
1127                                 }
1128                         }
1129                         p++;
1130                         *s = '\0';
1131                         tc = TC_REGEXP;
1132                         debug_printf_parse("%s: token found:'%s' TC_REGEXP\n", __func__, t_string);
1133
1134                 } else if (*p == '.' || isdigit(*p)) {
1135                         /* it's a number */
1136                         char *pp = p;
1137                         t_double = my_strtod(&pp);
1138                         p = pp;
1139                         if (*p == '.')
1140                                 syntax_error(EMSG_UNEXP_TOKEN);
1141                         tc = TC_NUMBER;
1142                         debug_printf_parse("%s: token found:%f TC_NUMBER\n", __func__, t_double);
1143                 } else {
1144                         /* search for something known */
1145                         tl = tokenlist;
1146                         tc = 0x00000001;
1147                         ti = tokeninfo;
1148                         while (*tl) {
1149                                 int l = (unsigned char) *tl++;
1150                                 if (l == (unsigned char) NTCC) {
1151                                         tc <<= 1;
1152                                         continue;
1153                                 }
1154                                 /* if token class is expected,
1155                                  * token matches,
1156                                  * and it's not a longer word,
1157                                  */
1158                                 if ((tc & (expected | TC_WORD | TC_NEWLINE))
1159                                  && strncmp(p, tl, l) == 0
1160                                  && !((tc & TC_WORD) && isalnum_(p[l]))
1161                                 ) {
1162                                         /* then this is what we are looking for */
1163                                         t_info = *ti;
1164                                         debug_printf_parse("%s: token found:'%.*s' t_info:%x\n", __func__, l, p, t_info);
1165                                         p += l;
1166                                         goto token_found;
1167                                 }
1168                                 ti++;
1169                                 tl += l;
1170                         }
1171                         /* not a known token */
1172
1173                         /* is it a name? (var/array/function) */
1174                         if (!isalnum_(*p))
1175                                 syntax_error(EMSG_UNEXP_TOKEN); /* no */
1176                         /* yes */
1177                         t_string = --p;
1178                         while (isalnum_(*++p)) {
1179                                 p[-1] = *p;
1180                         }
1181                         p[-1] = '\0';
1182                         tc = TC_VARIABLE;
1183                         /* also consume whitespace between functionname and bracket */
1184                         if (!(expected & TC_VARIABLE) || (expected & TC_ARRAY))
1185                                 p = skip_spaces(p);
1186                         if (*p == '(') {
1187                                 tc = TC_FUNCTION;
1188                                 debug_printf_parse("%s: token found:'%s' TC_FUNCTION\n", __func__, t_string);
1189                         } else {
1190                                 if (*p == '[') {
1191                                         p++;
1192                                         tc = TC_ARRAY;
1193                                         debug_printf_parse("%s: token found:'%s' TC_ARRAY\n", __func__, t_string);
1194                                 } else
1195                                         debug_printf_parse("%s: token found:'%s' TC_VARIABLE\n", __func__, t_string);
1196                         }
1197                 }
1198  token_found:
1199                 g_pos = p;
1200
1201                 /* skipping newlines in some cases */
1202                 if ((ltclass & TC_NOTERM) && (tc & TC_NEWLINE))
1203                         goto readnext;
1204
1205                 /* insert concatenation operator when needed */
1206                 debug_printf_parse("%s: %x %x %x concat_inserted?\n", __func__,
1207                         (ltclass & TC_CONCAT1), (tc & TC_CONCAT2), (expected & TC_BINOP));
1208                 if ((ltclass & TC_CONCAT1) && (tc & TC_CONCAT2) && (expected & TC_BINOP)
1209                  && !(ltclass == TC_LENGTH && tc == TC_SEQSTART) /* but not for "length(..." */
1210                 ) {
1211                         concat_inserted = TRUE;
1212                         save_tclass = tc;
1213                         save_info = t_info;
1214                         tc = TC_BINOP;
1215                         t_info = OC_CONCAT | SS | P(35);
1216                 }
1217
1218                 debug_printf_parse("%s: t_tclass=tc=%x\n", __func__, t_tclass);
1219                 t_tclass = tc;
1220         }
1221         ltclass = t_tclass;
1222
1223         /* Are we ready for this? */
1224         if (!(ltclass & expected)) {
1225                 syntax_error((ltclass & (TC_NEWLINE | TC_EOF)) ?
1226                                 EMSG_UNEXP_EOS : EMSG_UNEXP_TOKEN);
1227         }
1228
1229         debug_printf_parse("%s: returning, ltclass:%x t_double:%f\n", __func__, ltclass, t_double);
1230         return ltclass;
1231 #undef concat_inserted
1232 #undef save_tclass
1233 #undef save_info
1234 #undef ltclass
1235 }
1236
1237 static void rollback_token(void)
1238 {
1239         t_rollback = TRUE;
1240 }
1241
1242 static node *new_node(uint32_t info)
1243 {
1244         node *n;
1245
1246         n = xzalloc(sizeof(node));
1247         n->info = info;
1248         n->lineno = g_lineno;
1249         return n;
1250 }
1251
1252 static void mk_re_node(const char *s, node *n, regex_t *re)
1253 {
1254         n->info = OC_REGEXP;
1255         n->l.re = re;
1256         n->r.ire = re + 1;
1257         xregcomp(re, s, REG_EXTENDED);
1258         xregcomp(re + 1, s, REG_EXTENDED | REG_ICASE);
1259 }
1260
1261 static node *condition(void)
1262 {
1263         next_token(TC_SEQSTART);
1264         return parse_expr(TC_SEQTERM);
1265 }
1266
1267 /* parse expression terminated by given argument, return ptr
1268  * to built subtree. Terminator is eaten by parse_expr */
1269 static node *parse_expr(uint32_t iexp)
1270 {
1271         node sn;
1272         node *cn = &sn;
1273         node *vn, *glptr;
1274         uint32_t tc, xtc;
1275         var *v;
1276
1277         debug_printf_parse("%s(%x)\n", __func__, iexp);
1278
1279         sn.info = PRIMASK;
1280         sn.r.n = sn.a.n = glptr = NULL;
1281         xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP | iexp;
1282
1283         while (!((tc = next_token(xtc)) & iexp)) {
1284
1285                 if (glptr && (t_info == (OC_COMPARE | VV | P(39) | 2))) {
1286                         /* input redirection (<) attached to glptr node */
1287                         debug_printf_parse("%s: input redir\n", __func__);
1288                         cn = glptr->l.n = new_node(OC_CONCAT | SS | P(37));
1289                         cn->a.n = glptr;
1290                         xtc = TC_OPERAND | TC_UOPPRE;
1291                         glptr = NULL;
1292
1293                 } else if (tc & (TC_BINOP | TC_UOPPOST)) {
1294                         debug_printf_parse("%s: TC_BINOP | TC_UOPPOST tc:%x\n", __func__, tc);
1295                         /* for binary and postfix-unary operators, jump back over
1296                          * previous operators with higher priority */
1297                         vn = cn;
1298                         while (((t_info & PRIMASK) > (vn->a.n->info & PRIMASK2))
1299                             || ((t_info == vn->info) && ((t_info & OPCLSMASK) == OC_COLON))
1300                         ) {
1301                                 vn = vn->a.n;
1302                                 if (!vn->a.n) syntax_error(EMSG_UNEXP_TOKEN);
1303                         }
1304                         if ((t_info & OPCLSMASK) == OC_TERNARY)
1305                                 t_info += P(6);
1306                         cn = vn->a.n->r.n = new_node(t_info);
1307                         cn->a.n = vn->a.n;
1308                         if (tc & TC_BINOP) {
1309                                 cn->l.n = vn;
1310                                 xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP;
1311                                 if ((t_info & OPCLSMASK) == OC_PGETLINE) {
1312                                         /* it's a pipe */
1313                                         next_token(TC_GETLINE);
1314                                         /* give maximum priority to this pipe */
1315                                         cn->info &= ~PRIMASK;
1316                                         xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1317                                 }
1318                         } else {
1319                                 cn->r.n = vn;
1320                                 xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1321                         }
1322                         vn->a.n = cn;
1323
1324                 } else {
1325                         debug_printf_parse("%s: other\n", __func__);
1326                         /* for operands and prefix-unary operators, attach them
1327                          * to last node */
1328                         vn = cn;
1329                         cn = vn->r.n = new_node(t_info);
1330                         cn->a.n = vn;
1331                         xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP;
1332                         if (tc & (TC_OPERAND | TC_REGEXP)) {
1333                                 debug_printf_parse("%s: TC_OPERAND | TC_REGEXP\n", __func__);
1334                                 xtc = TC_UOPPRE | TC_UOPPOST | TC_BINOP | TC_OPERAND | iexp;
1335                                 /* one should be very careful with switch on tclass -
1336                                  * only simple tclasses should be used! */
1337                                 switch (tc) {
1338                                 case TC_VARIABLE:
1339                                 case TC_ARRAY:
1340                                         debug_printf_parse("%s: TC_VARIABLE | TC_ARRAY\n", __func__);
1341                                         cn->info = OC_VAR;
1342                                         v = hash_search(ahash, t_string);
1343                                         if (v != NULL) {
1344                                                 cn->info = OC_FNARG;
1345                                                 cn->l.aidx = v->x.aidx;
1346                                         } else {
1347                                                 cn->l.v = newvar(t_string);
1348                                         }
1349                                         if (tc & TC_ARRAY) {
1350                                                 cn->info |= xS;
1351                                                 cn->r.n = parse_expr(TC_ARRTERM);
1352                                         }
1353                                         break;
1354
1355                                 case TC_NUMBER:
1356                                 case TC_STRING:
1357                                         debug_printf_parse("%s: TC_NUMBER | TC_STRING\n", __func__);
1358                                         cn->info = OC_VAR;
1359                                         v = cn->l.v = xzalloc(sizeof(var));
1360                                         if (tc & TC_NUMBER)
1361                                                 setvar_i(v, t_double);
1362                                         else {
1363                                                 setvar_s(v, t_string);
1364                                                 xtc &= ~TC_UOPPOST; /* "str"++ is not allowed */
1365                                         }
1366                                         break;
1367
1368                                 case TC_REGEXP:
1369                                         debug_printf_parse("%s: TC_REGEXP\n", __func__);
1370                                         mk_re_node(t_string, cn, xzalloc(sizeof(regex_t)*2));
1371                                         break;
1372
1373                                 case TC_FUNCTION:
1374                                         debug_printf_parse("%s: TC_FUNCTION\n", __func__);
1375                                         cn->info = OC_FUNC;
1376                                         cn->r.f = newfunc(t_string);
1377                                         cn->l.n = condition();
1378                                         break;
1379
1380                                 case TC_SEQSTART:
1381                                         debug_printf_parse("%s: TC_SEQSTART\n", __func__);
1382                                         cn = vn->r.n = parse_expr(TC_SEQTERM);
1383                                         if (!cn)
1384                                                 syntax_error("Empty sequence");
1385                                         cn->a.n = vn;
1386                                         break;
1387
1388                                 case TC_GETLINE:
1389                                         debug_printf_parse("%s: TC_GETLINE\n", __func__);
1390                                         glptr = cn;
1391                                         xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1392                                         break;
1393
1394                                 case TC_BUILTIN:
1395                                         debug_printf_parse("%s: TC_BUILTIN\n", __func__);
1396                                         cn->l.n = condition();
1397                                         break;
1398
1399                                 case TC_LENGTH:
1400                                         debug_printf_parse("%s: TC_LENGTH\n", __func__);
1401                                         next_token(TC_SEQSTART /* length(...) */
1402                                                 | TC_OPTERM    /* length; (or newline)*/
1403                                                 | TC_GRPTERM   /* length } */
1404                                                 | TC_BINOPX    /* length <op> NUM */
1405                                                 | TC_COMMA     /* print length, 1 */
1406                                         );
1407                                         rollback_token();
1408                                         if (t_tclass & TC_SEQSTART) {
1409                                                 /* It was a "(" token. Handle just like TC_BUILTIN */
1410                                                 cn->l.n = condition();
1411                                         }
1412                                         break;
1413                                 }
1414                         }
1415                 }
1416         }
1417
1418         debug_printf_parse("%s() returns %p\n", __func__, sn.r.n);
1419         return sn.r.n;
1420 }
1421
1422 /* add node to chain. Return ptr to alloc'd node */
1423 static node *chain_node(uint32_t info)
1424 {
1425         node *n;
1426
1427         if (!seq->first)
1428                 seq->first = seq->last = new_node(0);
1429
1430         if (seq->programname != g_progname) {
1431                 seq->programname = g_progname;
1432                 n = chain_node(OC_NEWSOURCE);
1433                 n->l.new_progname = xstrdup(g_progname);
1434         }
1435
1436         n = seq->last;
1437         n->info = info;
1438         seq->last = n->a.n = new_node(OC_DONE);
1439
1440         return n;
1441 }
1442
1443 static void chain_expr(uint32_t info)
1444 {
1445         node *n;
1446
1447         n = chain_node(info);
1448
1449         n->l.n = parse_expr(TC_OPTERM | TC_GRPTERM);
1450         if ((info & OF_REQUIRED) && !n->l.n)
1451                 syntax_error(EMSG_TOO_FEW_ARGS);
1452
1453         if (t_tclass & TC_GRPTERM)
1454                 rollback_token();
1455 }
1456
1457 static node *chain_loop(node *nn)
1458 {
1459         node *n, *n2, *save_brk, *save_cont;
1460
1461         save_brk = break_ptr;
1462         save_cont = continue_ptr;
1463
1464         n = chain_node(OC_BR | Vx);
1465         continue_ptr = new_node(OC_EXEC);
1466         break_ptr = new_node(OC_EXEC);
1467         chain_group();
1468         n2 = chain_node(OC_EXEC | Vx);
1469         n2->l.n = nn;
1470         n2->a.n = n;
1471         continue_ptr->a.n = n2;
1472         break_ptr->a.n = n->r.n = seq->last;
1473
1474         continue_ptr = save_cont;
1475         break_ptr = save_brk;
1476
1477         return n;
1478 }
1479
1480 /* parse group and attach it to chain */
1481 static void chain_group(void)
1482 {
1483         uint32_t c;
1484         node *n, *n2, *n3;
1485
1486         do {
1487                 c = next_token(TC_GRPSEQ);
1488         } while (c & TC_NEWLINE);
1489
1490         if (c & TC_GRPSTART) {
1491                 debug_printf_parse("%s: TC_GRPSTART\n", __func__);
1492                 while (next_token(TC_GRPSEQ | TC_GRPTERM) != TC_GRPTERM) {
1493                         debug_printf_parse("%s: !TC_GRPTERM\n", __func__);
1494                         if (t_tclass & TC_NEWLINE)
1495                                 continue;
1496                         rollback_token();
1497                         chain_group();
1498                 }
1499                 debug_printf_parse("%s: TC_GRPTERM\n", __func__);
1500         } else if (c & (TC_OPSEQ | TC_OPTERM)) {
1501                 debug_printf_parse("%s: TC_OPSEQ | TC_OPTERM\n", __func__);
1502                 rollback_token();
1503                 chain_expr(OC_EXEC | Vx);
1504         } else {
1505                 /* TC_STATEMNT */
1506                 debug_printf_parse("%s: TC_STATEMNT(?)\n", __func__);
1507                 switch (t_info & OPCLSMASK) {
1508                 case ST_IF:
1509                         debug_printf_parse("%s: ST_IF\n", __func__);
1510                         n = chain_node(OC_BR | Vx);
1511                         n->l.n = condition();
1512                         chain_group();
1513                         n2 = chain_node(OC_EXEC);
1514                         n->r.n = seq->last;
1515                         if (next_token(TC_GRPSEQ | TC_GRPTERM | TC_ELSE) == TC_ELSE) {
1516                                 chain_group();
1517                                 n2->a.n = seq->last;
1518                         } else {
1519                                 rollback_token();
1520                         }
1521                         break;
1522
1523                 case ST_WHILE:
1524                         debug_printf_parse("%s: ST_WHILE\n", __func__);
1525                         n2 = condition();
1526                         n = chain_loop(NULL);
1527                         n->l.n = n2;
1528                         break;
1529
1530                 case ST_DO:
1531                         debug_printf_parse("%s: ST_DO\n", __func__);
1532                         n2 = chain_node(OC_EXEC);
1533                         n = chain_loop(NULL);
1534                         n2->a.n = n->a.n;
1535                         next_token(TC_WHILE);
1536                         n->l.n = condition();
1537                         break;
1538
1539                 case ST_FOR:
1540                         debug_printf_parse("%s: ST_FOR\n", __func__);
1541                         next_token(TC_SEQSTART);
1542                         n2 = parse_expr(TC_SEMICOL | TC_SEQTERM);
1543                         if (t_tclass & TC_SEQTERM) {    /* for-in */
1544                                 if (!n2 || (n2->info & OPCLSMASK) != OC_IN)
1545                                         syntax_error(EMSG_UNEXP_TOKEN);
1546                                 n = chain_node(OC_WALKINIT | VV);
1547                                 n->l.n = n2->l.n;
1548                                 n->r.n = n2->r.n;
1549                                 n = chain_loop(NULL);
1550                                 n->info = OC_WALKNEXT | Vx;
1551                                 n->l.n = n2->l.n;
1552                         } else {                        /* for (;;) */
1553                                 n = chain_node(OC_EXEC | Vx);
1554                                 n->l.n = n2;
1555                                 n2 = parse_expr(TC_SEMICOL);
1556                                 n3 = parse_expr(TC_SEQTERM);
1557                                 n = chain_loop(n3);
1558                                 n->l.n = n2;
1559                                 if (!n2)
1560                                         n->info = OC_EXEC;
1561                         }
1562                         break;
1563
1564                 case OC_PRINT:
1565                 case OC_PRINTF:
1566                         debug_printf_parse("%s: OC_PRINT[F]\n", __func__);
1567                         n = chain_node(t_info);
1568                         n->l.n = parse_expr(TC_OPTERM | TC_OUTRDR | TC_GRPTERM);
1569                         if (t_tclass & TC_OUTRDR) {
1570                                 n->info |= t_info;
1571                                 n->r.n = parse_expr(TC_OPTERM | TC_GRPTERM);
1572                         }
1573                         if (t_tclass & TC_GRPTERM)
1574                                 rollback_token();
1575                         break;
1576
1577                 case OC_BREAK:
1578                         debug_printf_parse("%s: OC_BREAK\n", __func__);
1579                         n = chain_node(OC_EXEC);
1580                         n->a.n = break_ptr;
1581                         chain_expr(t_info);
1582                         break;
1583
1584                 case OC_CONTINUE:
1585                         debug_printf_parse("%s: OC_CONTINUE\n", __func__);
1586                         n = chain_node(OC_EXEC);
1587                         n->a.n = continue_ptr;
1588                         chain_expr(t_info);
1589                         break;
1590
1591                 /* delete, next, nextfile, return, exit */
1592                 default:
1593                         debug_printf_parse("%s: default\n", __func__);
1594                         chain_expr(t_info);
1595                 }
1596         }
1597 }
1598
1599 static void parse_program(char *p)
1600 {
1601         uint32_t tclass;
1602         node *cn;
1603         func *f;
1604         var *v;
1605
1606         g_pos = p;
1607         t_lineno = 1;
1608         while ((tclass = next_token(TC_EOF | TC_OPSEQ | TC_GRPSTART |
1609                         TC_OPTERM | TC_BEGIN | TC_END | TC_FUNCDECL)) != TC_EOF) {
1610
1611                 if (tclass & TC_OPTERM) {
1612                         debug_printf_parse("%s: TC_OPTERM\n", __func__);
1613                         continue;
1614                 }
1615
1616                 seq = &mainseq;
1617                 if (tclass & TC_BEGIN) {
1618                         debug_printf_parse("%s: TC_BEGIN\n", __func__);
1619                         seq = &beginseq;
1620                         chain_group();
1621                 } else if (tclass & TC_END) {
1622                         debug_printf_parse("%s: TC_END\n", __func__);
1623                         seq = &endseq;
1624                         chain_group();
1625                 } else if (tclass & TC_FUNCDECL) {
1626                         debug_printf_parse("%s: TC_FUNCDECL\n", __func__);
1627                         next_token(TC_FUNCTION);
1628                         g_pos++;
1629                         f = newfunc(t_string);
1630                         f->body.first = NULL;
1631                         f->nargs = 0;
1632                         /* Match func arg list: a comma sep list of >= 0 args, and a close paren */
1633                         while (next_token(TC_VARIABLE | TC_SEQTERM | TC_COMMA)) {
1634                                 /* Either an empty arg list, or trailing comma from prev iter
1635                                  * must be followed by an arg */
1636                                 if (f->nargs == 0 && t_tclass == TC_SEQTERM)
1637                                         break;
1638
1639                                 /* TC_SEQSTART/TC_COMMA must be followed by TC_VARIABLE */
1640                                 if (t_tclass != TC_VARIABLE)
1641                                         syntax_error(EMSG_UNEXP_TOKEN);
1642
1643                                 v = findvar(ahash, t_string);
1644                                 v->x.aidx = f->nargs++;
1645
1646                                 /* Arg followed either by end of arg list or 1 comma */
1647                                 if (next_token(TC_COMMA | TC_SEQTERM) & TC_SEQTERM)
1648                                         break;
1649                                 if (t_tclass != TC_COMMA)
1650                                         syntax_error(EMSG_UNEXP_TOKEN);
1651                         }
1652                         seq = &f->body;
1653                         chain_group();
1654                         clear_array(ahash);
1655                 } else if (tclass & TC_OPSEQ) {
1656                         debug_printf_parse("%s: TC_OPSEQ\n", __func__);
1657                         rollback_token();
1658                         cn = chain_node(OC_TEST);
1659                         cn->l.n = parse_expr(TC_OPTERM | TC_EOF | TC_GRPSTART);
1660                         if (t_tclass & TC_GRPSTART) {
1661                                 debug_printf_parse("%s: TC_GRPSTART\n", __func__);
1662                                 rollback_token();
1663                                 chain_group();
1664                         } else {
1665                                 debug_printf_parse("%s: !TC_GRPSTART\n", __func__);
1666                                 chain_node(OC_PRINT);
1667                         }
1668                         cn->r.n = mainseq.last;
1669                 } else /* if (tclass & TC_GRPSTART) */ {
1670                         debug_printf_parse("%s: TC_GRPSTART(?)\n", __func__);
1671                         rollback_token();
1672                         chain_group();
1673                 }
1674         }
1675         debug_printf_parse("%s: TC_EOF\n", __func__);
1676 }
1677
1678
1679 /* -------- program execution part -------- */
1680
1681 static node *mk_splitter(const char *s, tsplitter *spl)
1682 {
1683         regex_t *re, *ire;
1684         node *n;
1685
1686         re = &spl->re[0];
1687         ire = &spl->re[1];
1688         n = &spl->n;
1689         if ((n->info & OPCLSMASK) == OC_REGEXP) {
1690                 regfree(re);
1691                 regfree(ire); // TODO: nuke ire, use re+1?
1692         }
1693         if (s[0] && s[1]) { /* strlen(s) > 1 */
1694                 mk_re_node(s, n, re);
1695         } else {
1696                 n->info = (uint32_t) s[0];
1697         }
1698
1699         return n;
1700 }
1701
1702 /* use node as a regular expression. Supplied with node ptr and regex_t
1703  * storage space. Return ptr to regex (if result points to preg, it should
1704  * be later regfree'd manually
1705  */
1706 static regex_t *as_regex(node *op, regex_t *preg)
1707 {
1708         int cflags;
1709         var *v;
1710         const char *s;
1711
1712         if ((op->info & OPCLSMASK) == OC_REGEXP) {
1713                 return icase ? op->r.ire : op->l.re;
1714         }
1715         v = nvalloc(1);
1716         s = getvar_s(evaluate(op, v));
1717
1718         cflags = icase ? REG_EXTENDED | REG_ICASE : REG_EXTENDED;
1719         /* Testcase where REG_EXTENDED fails (unpaired '{'):
1720          * echo Hi | awk 'gsub("@(samp|code|file)\{","");'
1721          * gawk 3.1.5 eats this. We revert to ~REG_EXTENDED
1722          * (maybe gsub is not supposed to use REG_EXTENDED?).
1723          */
1724         if (regcomp(preg, s, cflags)) {
1725                 cflags &= ~REG_EXTENDED;
1726                 xregcomp(preg, s, cflags);
1727         }
1728         nvfree(v);
1729         return preg;
1730 }
1731
1732 /* gradually increasing buffer.
1733  * note that we reallocate even if n == old_size,
1734  * and thus there is at least one extra allocated byte.
1735  */
1736 static char* qrealloc(char *b, int n, int *size)
1737 {
1738         if (!b || n >= *size) {
1739                 *size = n + (n>>1) + 80;
1740                 b = xrealloc(b, *size);
1741         }
1742         return b;
1743 }
1744
1745 /* resize field storage space */
1746 static void fsrealloc(int size)
1747 {
1748         int i;
1749
1750         if (size >= maxfields) {
1751                 i = maxfields;
1752                 maxfields = size + 16;
1753                 Fields = xrealloc(Fields, maxfields * sizeof(Fields[0]));
1754                 for (; i < maxfields; i++) {
1755                         Fields[i].type = VF_SPECIAL;
1756                         Fields[i].string = NULL;
1757                 }
1758         }
1759         /* if size < nfields, clear extra field variables */
1760         for (i = size; i < nfields; i++) {
1761                 clrvar(Fields + i);
1762         }
1763         nfields = size;
1764 }
1765
1766 static int awk_split(const char *s, node *spl, char **slist)
1767 {
1768         int l, n;
1769         char c[4];
1770         char *s1;
1771         regmatch_t pmatch[2]; // TODO: why [2]? [1] is enough...
1772
1773         /* in worst case, each char would be a separate field */
1774         *slist = s1 = xzalloc(strlen(s) * 2 + 3);
1775         strcpy(s1, s);
1776
1777         c[0] = c[1] = (char)spl->info;
1778         c[2] = c[3] = '\0';
1779         if (*getvar_s(intvar[RS]) == '\0')
1780                 c[2] = '\n';
1781
1782         n = 0;
1783         if ((spl->info & OPCLSMASK) == OC_REGEXP) {  /* regex split */
1784                 if (!*s)
1785                         return n; /* "": zero fields */
1786                 n++; /* at least one field will be there */
1787                 do {
1788                         l = strcspn(s, c+2); /* len till next NUL or \n */
1789                         if (regexec(icase ? spl->r.ire : spl->l.re, s, 1, pmatch, 0) == 0
1790                          && pmatch[0].rm_so <= l
1791                         ) {
1792                                 l = pmatch[0].rm_so;
1793                                 if (pmatch[0].rm_eo == 0) {
1794                                         l++;
1795                                         pmatch[0].rm_eo++;
1796                                 }
1797                                 n++; /* we saw yet another delimiter */
1798                         } else {
1799                                 pmatch[0].rm_eo = l;
1800                                 if (s[l])
1801                                         pmatch[0].rm_eo++;
1802                         }
1803                         memcpy(s1, s, l);
1804                         /* make sure we remove *all* of the separator chars */
1805                         do {
1806                                 s1[l] = '\0';
1807                         } while (++l < pmatch[0].rm_eo);
1808                         nextword(&s1);
1809                         s += pmatch[0].rm_eo;
1810                 } while (*s);
1811                 return n;
1812         }
1813         if (c[0] == '\0') {  /* null split */
1814                 while (*s) {
1815                         *s1++ = *s++;
1816                         *s1++ = '\0';
1817                         n++;
1818                 }
1819                 return n;
1820         }
1821         if (c[0] != ' ') {  /* single-character split */
1822                 if (icase) {
1823                         c[0] = toupper(c[0]);
1824                         c[1] = tolower(c[1]);
1825                 }
1826                 if (*s1)
1827                         n++;
1828                 while ((s1 = strpbrk(s1, c)) != NULL) {
1829                         *s1++ = '\0';
1830                         n++;
1831                 }
1832                 return n;
1833         }
1834         /* space split */
1835         while (*s) {
1836                 s = skip_whitespace(s);
1837                 if (!*s)
1838                         break;
1839                 n++;
1840                 while (*s && !isspace(*s))
1841                         *s1++ = *s++;
1842                 *s1++ = '\0';
1843         }
1844         return n;
1845 }
1846
1847 static void split_f0(void)
1848 {
1849 /* static char *fstrings; */
1850 #define fstrings (G.split_f0__fstrings)
1851
1852         int i, n;
1853         char *s;
1854
1855         if (is_f0_split)
1856                 return;
1857
1858         is_f0_split = TRUE;
1859         free(fstrings);
1860         fsrealloc(0);
1861         n = awk_split(getvar_s(intvar[F0]), &fsplitter.n, &fstrings);
1862         fsrealloc(n);
1863         s = fstrings;
1864         for (i = 0; i < n; i++) {
1865                 Fields[i].string = nextword(&s);
1866                 Fields[i].type |= (VF_FSTR | VF_USER | VF_DIRTY);
1867         }
1868
1869         /* set NF manually to avoid side effects */
1870         clrvar(intvar[NF]);
1871         intvar[NF]->type = VF_NUMBER | VF_SPECIAL;
1872         intvar[NF]->number = nfields;
1873 #undef fstrings
1874 }
1875
1876 /* perform additional actions when some internal variables changed */
1877 static void handle_special(var *v)
1878 {
1879         int n;
1880         char *b;
1881         const char *sep, *s;
1882         int sl, l, len, i, bsize;
1883
1884         if (!(v->type & VF_SPECIAL))
1885                 return;
1886
1887         if (v == intvar[NF]) {
1888                 n = (int)getvar_i(v);
1889                 if (n < 0)
1890                         syntax_error("NF set to negative value");
1891                 fsrealloc(n);
1892
1893                 /* recalculate $0 */
1894                 sep = getvar_s(intvar[OFS]);
1895                 sl = strlen(sep);
1896                 b = NULL;
1897                 len = 0;
1898                 for (i = 0; i < n; i++) {
1899                         s = getvar_s(&Fields[i]);
1900                         l = strlen(s);
1901                         if (b) {
1902                                 memcpy(b+len, sep, sl);
1903                                 len += sl;
1904                         }
1905                         b = qrealloc(b, len+l+sl, &bsize);
1906                         memcpy(b+len, s, l);
1907                         len += l;
1908                 }
1909                 if (b)
1910                         b[len] = '\0';
1911                 setvar_p(intvar[F0], b);
1912                 is_f0_split = TRUE;
1913
1914         } else if (v == intvar[F0]) {
1915                 is_f0_split = FALSE;
1916
1917         } else if (v == intvar[FS]) {
1918                 /*
1919                  * The POSIX-2008 standard says that changing FS should have no effect on the
1920                  * current input line, but only on the next one. The language is:
1921                  *
1922                  * > Before the first reference to a field in the record is evaluated, the record
1923                  * > shall be split into fields, according to the rules in Regular Expressions,
1924                  * > using the value of FS that was current at the time the record was read.
1925                  *
1926                  * So, split up current line before assignment to FS:
1927                  */
1928                 split_f0();
1929
1930                 mk_splitter(getvar_s(v), &fsplitter);
1931         } else if (v == intvar[RS]) {
1932                 mk_splitter(getvar_s(v), &rsplitter);
1933         } else if (v == intvar[IGNORECASE]) {
1934                 icase = istrue(v);
1935         } else {                                /* $n */
1936                 n = getvar_i(intvar[NF]);
1937                 setvar_i(intvar[NF], n > v-Fields ? n : v-Fields+1);
1938                 /* right here v is invalid. Just to note... */
1939         }
1940 }
1941
1942 /* step through func/builtin/etc arguments */
1943 static node *nextarg(node **pn)
1944 {
1945         node *n;
1946
1947         n = *pn;
1948         if (n && (n->info & OPCLSMASK) == OC_COMMA) {
1949                 *pn = n->r.n;
1950                 n = n->l.n;
1951         } else {
1952                 *pn = NULL;
1953         }
1954         return n;
1955 }
1956
1957 static void hashwalk_init(var *v, xhash *array)
1958 {
1959         hash_item *hi;
1960         unsigned i;
1961         walker_list *w;
1962         walker_list *prev_walker;
1963
1964         if (v->type & VF_WALK) {
1965                 prev_walker = v->x.walker;
1966         } else {
1967                 v->type |= VF_WALK;
1968                 prev_walker = NULL;
1969         }
1970         debug_printf_walker("hashwalk_init: prev_walker:%p\n", prev_walker);
1971
1972         w = v->x.walker = xzalloc(sizeof(*w) + array->glen + 1); /* why + 1? */
1973         debug_printf_walker(" walker@%p=%p\n", &v->x.walker, w);
1974         w->cur = w->end = w->wbuf;
1975         w->prev = prev_walker;
1976         for (i = 0; i < array->csize; i++) {
1977                 hi = array->items[i];
1978                 while (hi) {
1979                         strcpy(w->end, hi->name);
1980                         nextword(&w->end);
1981                         hi = hi->next;
1982                 }
1983         }
1984 }
1985
1986 static int hashwalk_next(var *v)
1987 {
1988         walker_list *w = v->x.walker;
1989
1990         if (w->cur >= w->end) {
1991                 walker_list *prev_walker = w->prev;
1992
1993                 debug_printf_walker("end of iteration, free(walker@%p:%p), prev_walker:%p\n", &v->x.walker, w, prev_walker);
1994                 free(w);
1995                 v->x.walker = prev_walker;
1996                 return FALSE;
1997         }
1998
1999         setvar_s(v, nextword(&w->cur));
2000         return TRUE;
2001 }
2002
2003 /* evaluate node, return 1 when result is true, 0 otherwise */
2004 static int ptest(node *pattern)
2005 {
2006         /* ptest__v is "static": to save stack space? */
2007         return istrue(evaluate(pattern, &G.ptest__v));
2008 }
2009
2010 /* read next record from stream rsm into a variable v */
2011 static int awk_getline(rstream *rsm, var *v)
2012 {
2013         char *b;
2014         regmatch_t pmatch[2];
2015         int size, a, p, pp = 0;
2016         int fd, so, eo, r, rp;
2017         char c, *m, *s;
2018
2019         debug_printf_eval("entered %s()\n", __func__);
2020
2021         /* we're using our own buffer since we need access to accumulating
2022          * characters
2023          */
2024         fd = fileno(rsm->F);
2025         m = rsm->buffer;
2026         a = rsm->adv;
2027         p = rsm->pos;
2028         size = rsm->size;
2029         c = (char) rsplitter.n.info;
2030         rp = 0;
2031
2032         if (!m)
2033                 m = qrealloc(m, 256, &size);
2034
2035         do {
2036                 b = m + a;
2037                 so = eo = p;
2038                 r = 1;
2039                 if (p > 0) {
2040                         if ((rsplitter.n.info & OPCLSMASK) == OC_REGEXP) {
2041                                 if (regexec(icase ? rsplitter.n.r.ire : rsplitter.n.l.re,
2042                                                         b, 1, pmatch, 0) == 0) {
2043                                         so = pmatch[0].rm_so;
2044                                         eo = pmatch[0].rm_eo;
2045                                         if (b[eo] != '\0')
2046                                                 break;
2047                                 }
2048                         } else if (c != '\0') {
2049                                 s = strchr(b+pp, c);
2050                                 if (!s)
2051                                         s = memchr(b+pp, '\0', p - pp);
2052                                 if (s) {
2053                                         so = eo = s-b;
2054                                         eo++;
2055                                         break;
2056                                 }
2057                         } else {
2058                                 while (b[rp] == '\n')
2059                                         rp++;
2060                                 s = strstr(b+rp, "\n\n");
2061                                 if (s) {
2062                                         so = eo = s-b;
2063                                         while (b[eo] == '\n')
2064                                                 eo++;
2065                                         if (b[eo] != '\0')
2066                                                 break;
2067                                 }
2068                         }
2069                 }
2070
2071                 if (a > 0) {
2072                         memmove(m, m+a, p+1);
2073                         b = m;
2074                         a = 0;
2075                 }
2076
2077                 m = qrealloc(m, a+p+128, &size);
2078                 b = m + a;
2079                 pp = p;
2080                 p += safe_read(fd, b+p, size-p-1);
2081                 if (p < pp) {
2082                         p = 0;
2083                         r = 0;
2084                         setvar_i(intvar[ERRNO], errno);
2085                 }
2086                 b[p] = '\0';
2087
2088         } while (p > pp);
2089
2090         if (p == 0) {
2091                 r--;
2092         } else {
2093                 c = b[so]; b[so] = '\0';
2094                 setvar_s(v, b+rp);
2095                 v->type |= VF_USER;
2096                 b[so] = c;
2097                 c = b[eo]; b[eo] = '\0';
2098                 setvar_s(intvar[RT], b+so);
2099                 b[eo] = c;
2100         }
2101
2102         rsm->buffer = m;
2103         rsm->adv = a + eo;
2104         rsm->pos = p - eo;
2105         rsm->size = size;
2106
2107         debug_printf_eval("returning from %s(): %d\n", __func__, r);
2108
2109         return r;
2110 }
2111
2112 static int fmt_num(char *b, int size, const char *format, double n, int int_as_int)
2113 {
2114         int r = 0;
2115         char c;
2116         const char *s = format;
2117
2118         if (int_as_int && n == (long long)n) {
2119                 r = snprintf(b, size, "%lld", (long long)n);
2120         } else {
2121                 do { c = *s; } while (c && *++s);
2122                 if (strchr("diouxX", c)) {
2123                         r = snprintf(b, size, format, (int)n);
2124                 } else if (strchr("eEfgG", c)) {
2125                         r = snprintf(b, size, format, n);
2126                 } else {
2127                         syntax_error(EMSG_INV_FMT);
2128                 }
2129         }
2130         return r;
2131 }
2132
2133 /* formatted output into an allocated buffer, return ptr to buffer */
2134 static char *awk_printf(node *n)
2135 {
2136         char *b = NULL;
2137         char *fmt, *s, *f;
2138         const char *s1;
2139         int i, j, incr, bsize;
2140         char c, c1;
2141         var *v, *arg;
2142
2143         v = nvalloc(1);
2144         fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), v)));
2145
2146         i = 0;
2147         while (*f) {
2148                 s = f;
2149                 while (*f && (*f != '%' || *++f == '%'))
2150                         f++;
2151                 while (*f && !isalpha(*f)) {
2152                         if (*f == '*')
2153                                 syntax_error("%*x formats are not supported");
2154                         f++;
2155                 }
2156
2157                 incr = (f - s) + MAXVARFMT;
2158                 b = qrealloc(b, incr + i, &bsize);
2159                 c = *f;
2160                 if (c != '\0')
2161                         f++;
2162                 c1 = *f;
2163                 *f = '\0';
2164                 arg = evaluate(nextarg(&n), v);
2165
2166                 j = i;
2167                 if (c == 'c' || !c) {
2168                         i += sprintf(b+i, s, is_numeric(arg) ?
2169                                         (char)getvar_i(arg) : *getvar_s(arg));
2170                 } else if (c == 's') {
2171                         s1 = getvar_s(arg);
2172                         b = qrealloc(b, incr+i+strlen(s1), &bsize);
2173                         i += sprintf(b+i, s, s1);
2174                 } else {
2175                         i += fmt_num(b+i, incr, s, getvar_i(arg), FALSE);
2176                 }
2177                 *f = c1;
2178
2179                 /* if there was an error while sprintf, return value is negative */
2180                 if (i < j)
2181                         i = j;
2182         }
2183
2184         free(fmt);
2185         nvfree(v);
2186         b = xrealloc(b, i + 1);
2187         b[i] = '\0';
2188         return b;
2189 }
2190
2191 /* Common substitution routine.
2192  * Replace (nm)'th substring of (src) that matches (rn) with (repl),
2193  * store result into (dest), return number of substitutions.
2194  * If nm = 0, replace all matches.
2195  * If src or dst is NULL, use $0.
2196  * If subexp != 0, enable subexpression matching (\1-\9).
2197  */
2198 static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest, int subexp)
2199 {
2200         char *resbuf;
2201         const char *sp;
2202         int match_no, residx, replen, resbufsize;
2203         int regexec_flags;
2204         regmatch_t pmatch[10];
2205         regex_t sreg, *regex;
2206
2207         resbuf = NULL;
2208         residx = 0;
2209         match_no = 0;
2210         regexec_flags = 0;
2211         regex = as_regex(rn, &sreg);
2212         sp = getvar_s(src ? src : intvar[F0]);
2213         replen = strlen(repl);
2214         while (regexec(regex, sp, 10, pmatch, regexec_flags) == 0) {
2215                 int so = pmatch[0].rm_so;
2216                 int eo = pmatch[0].rm_eo;
2217
2218                 //bb_error_msg("match %u: [%u,%u] '%s'%p", match_no+1, so, eo, sp,sp);
2219                 resbuf = qrealloc(resbuf, residx + eo + replen, &resbufsize);
2220                 memcpy(resbuf + residx, sp, eo);
2221                 residx += eo;
2222                 if (++match_no >= nm) {
2223                         const char *s;
2224                         int nbs;
2225
2226                         /* replace */
2227                         residx -= (eo - so);
2228                         nbs = 0;
2229                         for (s = repl; *s; s++) {
2230                                 char c = resbuf[residx++] = *s;
2231                                 if (c == '\\') {
2232                                         nbs++;
2233                                         continue;
2234                                 }
2235                                 if (c == '&' || (subexp && c >= '0' && c <= '9')) {
2236                                         int j;
2237                                         residx -= ((nbs + 3) >> 1);
2238                                         j = 0;
2239                                         if (c != '&') {
2240                                                 j = c - '0';
2241                                                 nbs++;
2242                                         }
2243                                         if (nbs % 2) {
2244                                                 resbuf[residx++] = c;
2245                                         } else {
2246                                                 int n = pmatch[j].rm_eo - pmatch[j].rm_so;
2247                                                 resbuf = qrealloc(resbuf, residx + replen + n, &resbufsize);
2248                                                 memcpy(resbuf + residx, sp + pmatch[j].rm_so, n);
2249                                                 residx += n;
2250                                         }
2251                                 }
2252                                 nbs = 0;
2253                         }
2254                 }
2255
2256                 regexec_flags = REG_NOTBOL;
2257                 sp += eo;
2258                 if (match_no == nm)
2259                         break;
2260                 if (eo == so) {
2261                         /* Empty match (e.g. "b*" will match anywhere).
2262                          * Advance by one char. */
2263 //BUG (bug 1333):
2264 //gsub(/\<b*/,"") on "abc" will reach this point, advance to "bc"
2265 //... and will erroneously match "b" even though it is NOT at the word start.
2266 //we need REG_NOTBOW but it does not exist...
2267 //TODO: if EXTRA_COMPAT=y, use GNU matching and re_search,
2268 //it should be able to do it correctly.
2269                         /* Subtle: this is safe only because
2270                          * qrealloc allocated at least one extra byte */
2271                         resbuf[residx] = *sp;
2272                         if (*sp == '\0')
2273                                 goto ret;
2274                         sp++;
2275                         residx++;
2276                 }
2277         }
2278
2279         resbuf = qrealloc(resbuf, residx + strlen(sp), &resbufsize);
2280         strcpy(resbuf + residx, sp);
2281  ret:
2282         //bb_error_msg("end sp:'%s'%p", sp,sp);
2283         setvar_p(dest ? dest : intvar[F0], resbuf);
2284         if (regex == &sreg)
2285                 regfree(regex);
2286         return match_no;
2287 }
2288
2289 static NOINLINE int do_mktime(const char *ds)
2290 {
2291         struct tm then;
2292         int count;
2293
2294         /*memset(&then, 0, sizeof(then)); - not needed */
2295         then.tm_isdst = -1; /* default is unknown */
2296
2297         /* manpage of mktime says these fields are ints,
2298          * so we can sscanf stuff directly into them */
2299         count = sscanf(ds, "%u %u %u %u %u %u %d",
2300                 &then.tm_year, &then.tm_mon, &then.tm_mday,
2301                 &then.tm_hour, &then.tm_min, &then.tm_sec,
2302                 &then.tm_isdst);
2303
2304         if (count < 6
2305          || (unsigned)then.tm_mon < 1
2306          || (unsigned)then.tm_year < 1900
2307         ) {
2308                 return -1;
2309         }
2310
2311         then.tm_mon -= 1;
2312         then.tm_year -= 1900;
2313
2314         return mktime(&then);
2315 }
2316
2317 static NOINLINE var *exec_builtin(node *op, var *res)
2318 {
2319 #define tspl (G.exec_builtin__tspl)
2320
2321         var *tv;
2322         node *an[4];
2323         var *av[4];
2324         const char *as[4];
2325         regmatch_t pmatch[2];
2326         regex_t sreg, *re;
2327         node *spl;
2328         uint32_t isr, info;
2329         int nargs;
2330         time_t tt;
2331         int i, l, ll, n;
2332
2333         tv = nvalloc(4);
2334         isr = info = op->info;
2335         op = op->l.n;
2336
2337         av[2] = av[3] = NULL;
2338         for (i = 0; i < 4 && op; i++) {
2339                 an[i] = nextarg(&op);
2340                 if (isr & 0x09000000)
2341                         av[i] = evaluate(an[i], &tv[i]);
2342                 if (isr & 0x08000000)
2343                         as[i] = getvar_s(av[i]);
2344                 isr >>= 1;
2345         }
2346
2347         nargs = i;
2348         if ((uint32_t)nargs < (info >> 30))
2349                 syntax_error(EMSG_TOO_FEW_ARGS);
2350
2351         info &= OPNMASK;
2352         switch (info) {
2353
2354         case B_a2:
2355                 if (ENABLE_FEATURE_AWK_LIBM)
2356                         setvar_i(res, atan2(getvar_i(av[0]), getvar_i(av[1])));
2357                 else
2358                         syntax_error(EMSG_NO_MATH);
2359                 break;
2360
2361         case B_sp: {
2362                 char *s, *s1;
2363
2364                 if (nargs > 2) {
2365                         spl = (an[2]->info & OPCLSMASK) == OC_REGEXP ?
2366                                 an[2] : mk_splitter(getvar_s(evaluate(an[2], &tv[2])), &tspl);
2367                 } else {
2368                         spl = &fsplitter.n;
2369                 }
2370
2371                 n = awk_split(as[0], spl, &s);
2372                 s1 = s;
2373                 clear_array(iamarray(av[1]));
2374                 for (i = 1; i <= n; i++)
2375                         setari_u(av[1], i, nextword(&s));
2376                 free(s1);
2377                 setvar_i(res, n);
2378                 break;
2379         }
2380
2381         case B_ss: {
2382                 char *s;
2383
2384                 l = strlen(as[0]);
2385                 i = getvar_i(av[1]) - 1;
2386                 if (i > l)
2387                         i = l;
2388                 if (i < 0)
2389                         i = 0;
2390                 n = (nargs > 2) ? getvar_i(av[2]) : l-i;
2391                 if (n < 0)
2392                         n = 0;
2393                 s = xstrndup(as[0]+i, n);
2394                 setvar_p(res, s);
2395                 break;
2396         }
2397
2398         /* Bitwise ops must assume that operands are unsigned. GNU Awk 3.1.5:
2399          * awk '{ print or(-1,1) }' gives "4.29497e+09", not "-2.xxxe+09" */
2400         case B_an:
2401                 setvar_i(res, getvar_i_int(av[0]) & getvar_i_int(av[1]));
2402                 break;
2403
2404         case B_co:
2405                 setvar_i(res, ~getvar_i_int(av[0]));
2406                 break;
2407
2408         case B_ls:
2409                 setvar_i(res, getvar_i_int(av[0]) << getvar_i_int(av[1]));
2410                 break;
2411
2412         case B_or:
2413                 setvar_i(res, getvar_i_int(av[0]) | getvar_i_int(av[1]));
2414                 break;
2415
2416         case B_rs:
2417                 setvar_i(res, getvar_i_int(av[0]) >> getvar_i_int(av[1]));
2418                 break;
2419
2420         case B_xo:
2421                 setvar_i(res, getvar_i_int(av[0]) ^ getvar_i_int(av[1]));
2422                 break;
2423
2424         case B_lo:
2425         case B_up: {
2426                 char *s, *s1;
2427                 s1 = s = xstrdup(as[0]);
2428                 while (*s1) {
2429                         //*s1 = (info == B_up) ? toupper(*s1) : tolower(*s1);
2430                         if ((unsigned char)((*s1 | 0x20) - 'a') <= ('z' - 'a'))
2431                                 *s1 = (info == B_up) ? (*s1 & 0xdf) : (*s1 | 0x20);
2432                         s1++;
2433                 }
2434                 setvar_p(res, s);
2435                 break;
2436         }
2437
2438         case B_ix:
2439                 n = 0;
2440                 ll = strlen(as[1]);
2441                 l = strlen(as[0]) - ll;
2442                 if (ll > 0 && l >= 0) {
2443                         if (!icase) {
2444                                 char *s = strstr(as[0], as[1]);
2445                                 if (s)
2446                                         n = (s - as[0]) + 1;
2447                         } else {
2448                                 /* this piece of code is terribly slow and
2449                                  * really should be rewritten
2450                                  */
2451                                 for (i = 0; i <= l; i++) {
2452                                         if (strncasecmp(as[0]+i, as[1], ll) == 0) {
2453                                                 n = i+1;
2454                                                 break;
2455                                         }
2456                                 }
2457                         }
2458                 }
2459                 setvar_i(res, n);
2460                 break;
2461
2462         case B_ti:
2463                 if (nargs > 1)
2464                         tt = getvar_i(av[1]);
2465                 else
2466                         time(&tt);
2467                 //s = (nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y";
2468                 i = strftime(g_buf, MAXVARFMT,
2469                         ((nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y"),
2470                         localtime(&tt));
2471                 g_buf[i] = '\0';
2472                 setvar_s(res, g_buf);
2473                 break;
2474
2475         case B_mt:
2476                 setvar_i(res, do_mktime(as[0]));
2477                 break;
2478
2479         case B_ma:
2480                 re = as_regex(an[1], &sreg);
2481                 n = regexec(re, as[0], 1, pmatch, 0);
2482                 if (n == 0) {
2483                         pmatch[0].rm_so++;
2484                         pmatch[0].rm_eo++;
2485                 } else {
2486                         pmatch[0].rm_so = 0;
2487                         pmatch[0].rm_eo = -1;
2488                 }
2489                 setvar_i(newvar("RSTART"), pmatch[0].rm_so);
2490                 setvar_i(newvar("RLENGTH"), pmatch[0].rm_eo - pmatch[0].rm_so);
2491                 setvar_i(res, pmatch[0].rm_so);
2492                 if (re == &sreg)
2493                         regfree(re);
2494                 break;
2495
2496         case B_ge:
2497                 awk_sub(an[0], as[1], getvar_i(av[2]), av[3], res, TRUE);
2498                 break;
2499
2500         case B_gs:
2501                 setvar_i(res, awk_sub(an[0], as[1], 0, av[2], av[2], FALSE));
2502                 break;
2503
2504         case B_su:
2505                 setvar_i(res, awk_sub(an[0], as[1], 1, av[2], av[2], FALSE));
2506                 break;
2507         }
2508
2509         nvfree(tv);
2510         return res;
2511 #undef tspl
2512 }
2513
2514 /*
2515  * Evaluate node - the heart of the program. Supplied with subtree
2516  * and place where to store result. returns ptr to result.
2517  */
2518 #define XC(n) ((n) >> 8)
2519
2520 static var *evaluate(node *op, var *res)
2521 {
2522 /* This procedure is recursive so we should count every byte */
2523 #define fnargs (G.evaluate__fnargs)
2524 /* seed is initialized to 1 */
2525 #define seed   (G.evaluate__seed)
2526 #define sreg   (G.evaluate__sreg)
2527
2528         var *v1;
2529
2530         if (!op)
2531                 return setvar_s(res, NULL);
2532
2533         debug_printf_eval("entered %s()\n", __func__);
2534
2535         v1 = nvalloc(2);
2536
2537         while (op) {
2538                 struct {
2539                         var *v;
2540                         const char *s;
2541                 } L = L; /* for compiler */
2542                 struct {
2543                         var *v;
2544                         const char *s;
2545                 } R = R;
2546                 double L_d = L_d;
2547                 uint32_t opinfo;
2548                 int opn;
2549                 node *op1;
2550
2551                 opinfo = op->info;
2552                 opn = (opinfo & OPNMASK);
2553                 g_lineno = op->lineno;
2554                 op1 = op->l.n;
2555                 debug_printf_eval("opinfo:%08x opn:%08x\n", opinfo, opn);
2556
2557                 /* "delete" is special:
2558                  * "delete array[var--]" must evaluate index expr only once,
2559                  * must not evaluate it in "execute inevitable things" part.
2560                  */
2561                 if (XC(opinfo & OPCLSMASK) == XC(OC_DELETE)) {
2562                         uint32_t info = op1->info & OPCLSMASK;
2563                         var *v;
2564
2565                         debug_printf_eval("DELETE\n");
2566                         if (info == OC_VAR) {
2567                                 v = op1->l.v;
2568                         } else if (info == OC_FNARG) {
2569                                 v = &fnargs[op1->l.aidx];
2570                         } else {
2571                                 syntax_error(EMSG_NOT_ARRAY);
2572                         }
2573                         if (op1->r.n) { /* array ref? */
2574                                 const char *s;
2575                                 s = getvar_s(evaluate(op1->r.n, v1));
2576                                 hash_remove(iamarray(v), s);
2577                         } else {
2578                                 clear_array(iamarray(v));
2579                         }
2580                         goto next;
2581                 }
2582
2583                 /* execute inevitable things */
2584                 if (opinfo & OF_RES1)
2585                         L.v = evaluate(op1, v1);
2586                 if (opinfo & OF_RES2)
2587                         R.v = evaluate(op->r.n, v1+1);
2588                 if (opinfo & OF_STR1) {
2589                         L.s = getvar_s(L.v);
2590                         debug_printf_eval("L.s:'%s'\n", L.s);
2591                 }
2592                 if (opinfo & OF_STR2) {
2593                         R.s = getvar_s(R.v);
2594                         debug_printf_eval("R.s:'%s'\n", R.s);
2595                 }
2596                 if (opinfo & OF_NUM1) {
2597                         L_d = getvar_i(L.v);
2598                         debug_printf_eval("L_d:%f\n", L_d);
2599                 }
2600
2601                 debug_printf_eval("switch(0x%x)\n", XC(opinfo & OPCLSMASK));
2602                 switch (XC(opinfo & OPCLSMASK)) {
2603
2604                 /* -- iterative node type -- */
2605
2606                 /* test pattern */
2607                 case XC( OC_TEST ):
2608                         if ((op1->info & OPCLSMASK) == OC_COMMA) {
2609                                 /* it's range pattern */
2610                                 if ((opinfo & OF_CHECKED) || ptest(op1->l.n)) {
2611                                         op->info |= OF_CHECKED;
2612                                         if (ptest(op1->r.n))
2613                                                 op->info &= ~OF_CHECKED;
2614                                         op = op->a.n;
2615                                 } else {
2616                                         op = op->r.n;
2617                                 }
2618                         } else {
2619                                 op = ptest(op1) ? op->a.n : op->r.n;
2620                         }
2621                         break;
2622
2623                 /* just evaluate an expression, also used as unconditional jump */
2624                 case XC( OC_EXEC ):
2625                         break;
2626
2627                 /* branch, used in if-else and various loops */
2628                 case XC( OC_BR ):
2629                         op = istrue(L.v) ? op->a.n : op->r.n;
2630                         break;
2631
2632                 /* initialize for-in loop */
2633                 case XC( OC_WALKINIT ):
2634                         hashwalk_init(L.v, iamarray(R.v));
2635                         break;
2636
2637                 /* get next array item */
2638                 case XC( OC_WALKNEXT ):
2639                         op = hashwalk_next(L.v) ? op->a.n : op->r.n;
2640                         break;
2641
2642                 case XC( OC_PRINT ):
2643                 case XC( OC_PRINTF ): {
2644                         FILE *F = stdout;
2645
2646                         if (op->r.n) {
2647                                 rstream *rsm = newfile(R.s);
2648                                 if (!rsm->F) {
2649                                         if (opn == '|') {
2650                                                 rsm->F = popen(R.s, "w");
2651                                                 if (rsm->F == NULL)
2652                                                         bb_simple_perror_msg_and_die("popen");
2653                                                 rsm->is_pipe = 1;
2654                                         } else {
2655                                                 rsm->F = xfopen(R.s, opn=='w' ? "w" : "a");
2656                                         }
2657                                 }
2658                                 F = rsm->F;
2659                         }
2660
2661                         if ((opinfo & OPCLSMASK) == OC_PRINT) {
2662                                 if (!op1) {
2663                                         fputs(getvar_s(intvar[F0]), F);
2664                                 } else {
2665                                         while (op1) {
2666                                                 var *v = evaluate(nextarg(&op1), v1);
2667                                                 if (v->type & VF_NUMBER) {
2668                                                         fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[OFMT]),
2669                                                                         getvar_i(v), TRUE);
2670                                                         fputs(g_buf, F);
2671                                                 } else {
2672                                                         fputs(getvar_s(v), F);
2673                                                 }
2674
2675                                                 if (op1)
2676                                                         fputs(getvar_s(intvar[OFS]), F);
2677                                         }
2678                                 }
2679                                 fputs(getvar_s(intvar[ORS]), F);
2680
2681                         } else {        /* OC_PRINTF */
2682                                 char *s = awk_printf(op1);
2683                                 fputs(s, F);
2684                                 free(s);
2685                         }
2686                         fflush(F);
2687                         break;
2688                 }
2689
2690                 /* case XC( OC_DELETE ): - moved to happen before arg evaluation */
2691
2692                 case XC( OC_NEWSOURCE ):
2693                         g_progname = op->l.new_progname;
2694                         break;
2695
2696                 case XC( OC_RETURN ):
2697                         copyvar(res, L.v);
2698                         break;
2699
2700                 case XC( OC_NEXTFILE ):
2701                         nextfile = TRUE;
2702                 case XC( OC_NEXT ):
2703                         nextrec = TRUE;
2704                 case XC( OC_DONE ):
2705                         clrvar(res);
2706                         break;
2707
2708                 case XC( OC_EXIT ):
2709                         awk_exit(L_d);
2710
2711                 /* -- recursive node type -- */
2712
2713                 case XC( OC_VAR ):
2714                         debug_printf_eval("VAR\n");
2715                         L.v = op->l.v;
2716                         if (L.v == intvar[NF])
2717                                 split_f0();
2718                         goto v_cont;
2719
2720                 case XC( OC_FNARG ):
2721                         debug_printf_eval("FNARG[%d]\n", op->l.aidx);
2722                         L.v = &fnargs[op->l.aidx];
2723  v_cont:
2724                         res = op->r.n ? findvar(iamarray(L.v), R.s) : L.v;
2725                         break;
2726
2727                 case XC( OC_IN ):
2728                         setvar_i(res, hash_search(iamarray(R.v), L.s) ? 1 : 0);
2729                         break;
2730
2731                 case XC( OC_REGEXP ):
2732                         op1 = op;
2733                         L.s = getvar_s(intvar[F0]);
2734                         goto re_cont;
2735
2736                 case XC( OC_MATCH ):
2737                         op1 = op->r.n;
2738  re_cont:
2739                         {
2740                                 regex_t *re = as_regex(op1, &sreg);
2741                                 int i = regexec(re, L.s, 0, NULL, 0);
2742                                 if (re == &sreg)
2743                                         regfree(re);
2744                                 setvar_i(res, (i == 0) ^ (opn == '!'));
2745                         }
2746                         break;
2747
2748                 case XC( OC_MOVE ):
2749                         debug_printf_eval("MOVE\n");
2750                         /* if source is a temporary string, jusk relink it to dest */
2751 //Disabled: if R.v is numeric but happens to have cached R.v->string,
2752 //then L.v ends up being a string, which is wrong
2753 //                      if (R.v == v1+1 && R.v->string) {
2754 //                              res = setvar_p(L.v, R.v->string);
2755 //                              R.v->string = NULL;
2756 //                      } else {
2757                                 res = copyvar(L.v, R.v);
2758 //                      }
2759                         break;
2760
2761                 case XC( OC_TERNARY ):
2762                         if ((op->r.n->info & OPCLSMASK) != OC_COLON)
2763                                 syntax_error(EMSG_POSSIBLE_ERROR);
2764                         res = evaluate(istrue(L.v) ? op->r.n->l.n : op->r.n->r.n, res);
2765                         break;
2766
2767                 case XC( OC_FUNC ): {
2768                         var *vbeg, *v;
2769                         const char *sv_progname;
2770
2771                         /* The body might be empty, still has to eval the args */
2772                         if (!op->r.n->info && !op->r.f->body.first)
2773                                 syntax_error(EMSG_UNDEF_FUNC);
2774
2775                         vbeg = v = nvalloc(op->r.f->nargs + 1);
2776                         while (op1) {
2777                                 var *arg = evaluate(nextarg(&op1), v1);
2778                                 copyvar(v, arg);
2779                                 v->type |= VF_CHILD;
2780                                 v->x.parent = arg;
2781                                 if (++v - vbeg >= op->r.f->nargs)
2782                                         break;
2783                         }
2784
2785                         v = fnargs;
2786                         fnargs = vbeg;
2787                         sv_progname = g_progname;
2788
2789                         res = evaluate(op->r.f->body.first, res);
2790
2791                         g_progname = sv_progname;
2792                         nvfree(fnargs);
2793                         fnargs = v;
2794
2795                         break;
2796                 }
2797
2798                 case XC( OC_GETLINE ):
2799                 case XC( OC_PGETLINE ): {
2800                         rstream *rsm;
2801                         int i;
2802
2803                         if (op1) {
2804                                 rsm = newfile(L.s);
2805                                 if (!rsm->F) {
2806                                         if ((opinfo & OPCLSMASK) == OC_PGETLINE) {
2807                                                 rsm->F = popen(L.s, "r");
2808                                                 rsm->is_pipe = TRUE;
2809                                         } else {
2810                                                 rsm->F = fopen_for_read(L.s);  /* not xfopen! */
2811                                         }
2812                                 }
2813                         } else {
2814                                 if (!iF)
2815                                         iF = next_input_file();
2816                                 rsm = iF;
2817                         }
2818
2819                         if (!rsm || !rsm->F) {
2820                                 setvar_i(intvar[ERRNO], errno);
2821                                 setvar_i(res, -1);
2822                                 break;
2823                         }
2824
2825                         if (!op->r.n)
2826                                 R.v = intvar[F0];
2827
2828                         i = awk_getline(rsm, R.v);
2829                         if (i > 0 && !op1) {
2830                                 incvar(intvar[FNR]);
2831                                 incvar(intvar[NR]);
2832                         }
2833                         setvar_i(res, i);
2834                         break;
2835                 }
2836
2837                 /* simple builtins */
2838                 case XC( OC_FBLTIN ): {
2839                         double R_d = R_d; /* for compiler */
2840
2841                         switch (opn) {
2842                         case F_in:
2843                                 R_d = (long long)L_d;
2844                                 break;
2845
2846                         case F_rn:
2847                                 R_d = (double)rand() / (double)RAND_MAX;
2848                                 break;
2849
2850                         case F_co:
2851                                 if (ENABLE_FEATURE_AWK_LIBM) {
2852                                         R_d = cos(L_d);
2853                                         break;
2854                                 }
2855
2856                         case F_ex:
2857                                 if (ENABLE_FEATURE_AWK_LIBM) {
2858                                         R_d = exp(L_d);
2859                                         break;
2860                                 }
2861
2862                         case F_lg:
2863                                 if (ENABLE_FEATURE_AWK_LIBM) {
2864                                         R_d = log(L_d);
2865                                         break;
2866                                 }
2867
2868                         case F_si:
2869                                 if (ENABLE_FEATURE_AWK_LIBM) {
2870                                         R_d = sin(L_d);
2871                                         break;
2872                                 }
2873
2874                         case F_sq:
2875                                 if (ENABLE_FEATURE_AWK_LIBM) {
2876                                         R_d = sqrt(L_d);
2877                                         break;
2878                                 }
2879
2880                                 syntax_error(EMSG_NO_MATH);
2881                                 break;
2882
2883                         case F_sr:
2884                                 R_d = (double)seed;
2885                                 seed = op1 ? (unsigned)L_d : (unsigned)time(NULL);
2886                                 srand(seed);
2887                                 break;
2888
2889                         case F_ti:
2890                                 R_d = time(NULL);
2891                                 break;
2892
2893                         case F_le:
2894                                 debug_printf_eval("length: L.s:'%s'\n", L.s);
2895                                 if (!op1) {
2896                                         L.s = getvar_s(intvar[F0]);
2897                                         debug_printf_eval("length: L.s='%s'\n", L.s);
2898                                 }
2899                                 else if (L.v->type & VF_ARRAY) {
2900                                         R_d = L.v->x.array->nel;
2901                                         debug_printf_eval("length: array_len:%d\n", L.v->x.array->nel);
2902                                         break;
2903                                 }
2904                                 R_d = strlen(L.s);
2905                                 break;
2906
2907                         case F_sy:
2908                                 fflush_all();
2909                                 R_d = (ENABLE_FEATURE_ALLOW_EXEC && L.s && *L.s)
2910                                                 ? (system(L.s) >> 8) : 0;
2911                                 break;
2912
2913                         case F_ff:
2914                                 if (!op1) {
2915                                         fflush(stdout);
2916                                 } else if (L.s && *L.s) {
2917                                         rstream *rsm = newfile(L.s);
2918                                         fflush(rsm->F);
2919                                 } else {
2920                                         fflush_all();
2921                                 }
2922                                 break;
2923
2924                         case F_cl: {
2925                                 rstream *rsm;
2926                                 int err = 0;
2927                                 rsm = (rstream *)hash_search(fdhash, L.s);
2928                                 debug_printf_eval("OC_FBLTIN F_cl rsm:%p\n", rsm);
2929                                 if (rsm) {
2930                                         debug_printf_eval("OC_FBLTIN F_cl "
2931                                                 "rsm->is_pipe:%d, ->F:%p\n",
2932                                                 rsm->is_pipe, rsm->F);
2933                                         /* Can be NULL if open failed. Example:
2934                                          * getline line <"doesnt_exist";
2935                                          * close("doesnt_exist"); <--- here rsm->F is NULL
2936                                          */
2937                                         if (rsm->F)
2938                                                 err = rsm->is_pipe ? pclose(rsm->F) : fclose(rsm->F);
2939                                         free(rsm->buffer);
2940                                         hash_remove(fdhash, L.s);
2941                                 }
2942                                 if (err)
2943                                         setvar_i(intvar[ERRNO], errno);
2944                                 R_d = (double)err;
2945                                 break;
2946                         }
2947                         } /* switch */
2948                         setvar_i(res, R_d);
2949                         break;
2950                 }
2951
2952                 case XC( OC_BUILTIN ):
2953                         res = exec_builtin(op, res);
2954                         break;
2955
2956                 case XC( OC_SPRINTF ):
2957                         setvar_p(res, awk_printf(op1));
2958                         break;
2959
2960                 case XC( OC_UNARY ): {
2961                         double Ld, R_d;
2962
2963                         Ld = R_d = getvar_i(R.v);
2964                         switch (opn) {
2965                         case 'P':
2966                                 Ld = ++R_d;
2967                                 goto r_op_change;
2968                         case 'p':
2969                                 R_d++;
2970                                 goto r_op_change;
2971                         case 'M':
2972                                 Ld = --R_d;
2973                                 goto r_op_change;
2974                         case 'm':
2975                                 R_d--;
2976  r_op_change:
2977                                 setvar_i(R.v, R_d);
2978                                 break;
2979                         case '!':
2980                                 Ld = !istrue(R.v);
2981                                 break;
2982                         case '-':
2983                                 Ld = -R_d;
2984                                 break;
2985                         }
2986                         setvar_i(res, Ld);
2987                         break;
2988                 }
2989
2990                 case XC( OC_FIELD ): {
2991                         int i = (int)getvar_i(R.v);
2992                         if (i < 0)
2993                                 syntax_error(EMSG_NEGATIVE_FIELD);
2994                         if (i == 0) {
2995                                 res = intvar[F0];
2996                         } else {
2997                                 split_f0();
2998                                 if (i > nfields)
2999                                         fsrealloc(i);
3000                                 res = &Fields[i - 1];
3001                         }
3002                         break;
3003                 }
3004
3005                 /* concatenation (" ") and index joining (",") */
3006                 case XC( OC_CONCAT ):
3007                 case XC( OC_COMMA ): {
3008                         const char *sep = "";
3009                         if ((opinfo & OPCLSMASK) == OC_COMMA)
3010                                 sep = getvar_s(intvar[SUBSEP]);
3011                         setvar_p(res, xasprintf("%s%s%s", L.s, sep, R.s));
3012                         break;
3013                 }
3014
3015                 case XC( OC_LAND ):
3016                         setvar_i(res, istrue(L.v) ? ptest(op->r.n) : 0);
3017                         break;
3018
3019                 case XC( OC_LOR ):
3020                         setvar_i(res, istrue(L.v) ? 1 : ptest(op->r.n));
3021                         break;
3022
3023                 case XC( OC_BINARY ):
3024                 case XC( OC_REPLACE ): {
3025                         double R_d = getvar_i(R.v);
3026                         debug_printf_eval("BINARY/REPLACE: R_d:%f opn:%c\n", R_d, opn);
3027                         switch (opn) {
3028                         case '+':
3029                                 L_d += R_d;
3030                                 break;
3031                         case '-':
3032                                 L_d -= R_d;
3033                                 break;
3034                         case '*':
3035                                 L_d *= R_d;
3036                                 break;
3037                         case '/':
3038                                 if (R_d == 0)
3039                                         syntax_error(EMSG_DIV_BY_ZERO);
3040                                 L_d /= R_d;
3041                                 break;
3042                         case '&':
3043                                 if (ENABLE_FEATURE_AWK_LIBM)
3044                                         L_d = pow(L_d, R_d);
3045                                 else
3046                                         syntax_error(EMSG_NO_MATH);
3047                                 break;
3048                         case '%':
3049                                 if (R_d == 0)
3050                                         syntax_error(EMSG_DIV_BY_ZERO);
3051                                 L_d -= (long long)(L_d / R_d) * R_d;
3052                                 break;
3053                         }
3054                         debug_printf_eval("BINARY/REPLACE result:%f\n", L_d);
3055                         res = setvar_i(((opinfo & OPCLSMASK) == OC_BINARY) ? res : L.v, L_d);
3056                         break;
3057                 }
3058
3059                 case XC( OC_COMPARE ): {
3060                         int i = i; /* for compiler */
3061                         double Ld;
3062
3063                         if (is_numeric(L.v) && is_numeric(R.v)) {
3064                                 Ld = getvar_i(L.v) - getvar_i(R.v);
3065                         } else {
3066                                 const char *l = getvar_s(L.v);
3067                                 const char *r = getvar_s(R.v);
3068                                 Ld = icase ? strcasecmp(l, r) : strcmp(l, r);
3069                         }
3070                         switch (opn & 0xfe) {
3071                         case 0:
3072                                 i = (Ld > 0);
3073                                 break;
3074                         case 2:
3075                                 i = (Ld >= 0);
3076                                 break;
3077                         case 4:
3078                                 i = (Ld == 0);
3079                                 break;
3080                         }
3081                         setvar_i(res, (i == 0) ^ (opn & 1));
3082                         break;
3083                 }
3084
3085                 default:
3086                         syntax_error(EMSG_POSSIBLE_ERROR);
3087                 } /* switch */
3088  next:
3089                 if ((opinfo & OPCLSMASK) <= SHIFT_TIL_THIS)
3090                         op = op->a.n;
3091                 if ((opinfo & OPCLSMASK) >= RECUR_FROM_THIS)
3092                         break;
3093                 if (nextrec)
3094                         break;
3095         } /* while (op) */
3096
3097         nvfree(v1);
3098         debug_printf_eval("returning from %s(): %p\n", __func__, res);
3099         return res;
3100 #undef fnargs
3101 #undef seed
3102 #undef sreg
3103 }
3104
3105
3106 /* -------- main & co. -------- */
3107
3108 static int awk_exit(int r)
3109 {
3110         var tv;
3111         unsigned i;
3112         hash_item *hi;
3113
3114         zero_out_var(&tv);
3115
3116         if (!exiting) {
3117                 exiting = TRUE;
3118                 nextrec = FALSE;
3119                 evaluate(endseq.first, &tv);
3120         }
3121
3122         /* waiting for children */
3123         for (i = 0; i < fdhash->csize; i++) {
3124                 hi = fdhash->items[i];
3125                 while (hi) {
3126                         if (hi->data.rs.F && hi->data.rs.is_pipe)
3127                                 pclose(hi->data.rs.F);
3128                         hi = hi->next;
3129                 }
3130         }
3131
3132         exit(r);
3133 }
3134
3135 /* if expr looks like "var=value", perform assignment and return 1,
3136  * otherwise return 0 */
3137 static int is_assignment(const char *expr)
3138 {
3139         char *exprc, *val;
3140
3141         if (!isalnum_(*expr) || (val = strchr(expr, '=')) == NULL) {
3142                 return FALSE;
3143         }
3144
3145         exprc = xstrdup(expr);
3146         val = exprc + (val - expr);
3147         *val++ = '\0';
3148
3149         unescape_string_in_place(val);
3150         setvar_u(newvar(exprc), val);
3151         free(exprc);
3152         return TRUE;
3153 }
3154
3155 /* switch to next input file */
3156 static rstream *next_input_file(void)
3157 {
3158 #define rsm          (G.next_input_file__rsm)
3159 #define files_happen (G.next_input_file__files_happen)
3160
3161         FILE *F;
3162         const char *fname, *ind;
3163
3164         if (rsm.F)
3165                 fclose(rsm.F);
3166         rsm.F = NULL;
3167         rsm.pos = rsm.adv = 0;
3168
3169         for (;;) {
3170                 if (getvar_i(intvar[ARGIND])+1 >= getvar_i(intvar[ARGC])) {
3171                         if (files_happen)
3172                                 return NULL;
3173                         fname = "-";
3174                         F = stdin;
3175                         break;
3176                 }
3177                 ind = getvar_s(incvar(intvar[ARGIND]));
3178                 fname = getvar_s(findvar(iamarray(intvar[ARGV]), ind));
3179                 if (fname && *fname && !is_assignment(fname)) {
3180                         F = xfopen_stdin(fname);
3181                         break;
3182                 }
3183         }
3184
3185         files_happen = TRUE;
3186         setvar_s(intvar[FILENAME], fname);
3187         rsm.F = F;
3188         return &rsm;
3189 #undef rsm
3190 #undef files_happen
3191 }
3192
3193 int awk_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3194 int awk_main(int argc UNUSED_PARAM, char **argv)
3195 {
3196         unsigned opt;
3197         char *opt_F;
3198         llist_t *list_v = NULL;
3199         llist_t *list_f = NULL;
3200 #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
3201         llist_t *list_e = NULL;
3202 #endif
3203         int i, j;
3204         var *v;
3205         var tv;
3206         char **envp;
3207         char *vnames = (char *)vNames; /* cheat */
3208         char *vvalues = (char *)vValues;
3209
3210         INIT_G();
3211
3212         /* Undo busybox.c, or else strtod may eat ','! This breaks parsing:
3213          * $1,$2 == '$1,' '$2', NOT '$1' ',' '$2' */
3214         if (ENABLE_LOCALE_SUPPORT)
3215                 setlocale(LC_NUMERIC, "C");
3216
3217         zero_out_var(&tv);
3218
3219         /* allocate global buffer */
3220         g_buf = xmalloc(MAXVARFMT + 1);
3221
3222         vhash = hash_init();
3223         ahash = hash_init();
3224         fdhash = hash_init();
3225         fnhash = hash_init();
3226
3227         /* initialize variables */
3228         for (i = 0; *vnames; i++) {
3229                 intvar[i] = v = newvar(nextword(&vnames));
3230                 if (*vvalues != '\377')
3231                         setvar_s(v, nextword(&vvalues));
3232                 else
3233                         setvar_i(v, 0);
3234
3235                 if (*vnames == '*') {
3236                         v->type |= VF_SPECIAL;
3237                         vnames++;
3238                 }
3239         }
3240
3241         handle_special(intvar[FS]);
3242         handle_special(intvar[RS]);
3243
3244         newfile("/dev/stdin")->F = stdin;
3245         newfile("/dev/stdout")->F = stdout;
3246         newfile("/dev/stderr")->F = stderr;
3247
3248         /* Huh, people report that sometimes environ is NULL. Oh well. */
3249         if (environ) for (envp = environ; *envp; envp++) {
3250                 /* environ is writable, thus we don't strdup it needlessly */
3251                 char *s = *envp;
3252                 char *s1 = strchr(s, '=');
3253                 if (s1) {
3254                         *s1 = '\0';
3255                         /* Both findvar and setvar_u take const char*
3256                          * as 2nd arg -> environment is not trashed */
3257                         setvar_u(findvar(iamarray(intvar[ENVIRON]), s), s1 + 1);
3258                         *s1 = '=';
3259                 }
3260         }
3261         opt = getopt32(argv, OPTSTR_AWK, &opt_F, &list_v, &list_f, IF_FEATURE_AWK_GNU_EXTENSIONS(&list_e,) NULL);
3262         argv += optind;
3263         //argc -= optind;
3264         if (opt & OPT_W)
3265                 bb_simple_error_msg("warning: option -W is ignored");
3266         if (opt & OPT_F) {
3267                 unescape_string_in_place(opt_F);
3268                 setvar_s(intvar[FS], opt_F);
3269         }
3270         while (list_v) {
3271                 if (!is_assignment(llist_pop(&list_v)))
3272                         bb_show_usage();
3273         }
3274         while (list_f) {
3275                 char *s = NULL;
3276                 FILE *from_file;
3277
3278                 g_progname = llist_pop(&list_f);
3279                 from_file = xfopen_stdin(g_progname);
3280                 /* one byte is reserved for some trick in next_token */
3281                 for (i = j = 1; j > 0; i += j) {
3282                         s = xrealloc(s, i + 4096);
3283                         j = fread(s + i, 1, 4094, from_file);
3284                 }
3285                 s[i] = '\0';
3286                 fclose(from_file);
3287                 parse_program(s + 1);
3288                 free(s);
3289         }
3290         g_progname = "cmd. line";
3291 #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
3292         while (list_e) {
3293                 parse_program(llist_pop(&list_e));
3294         }
3295 #endif
3296         if (!(opt & (OPT_f | OPT_e))) {
3297                 if (!*argv)
3298                         bb_show_usage();
3299                 parse_program(*argv++);
3300         }
3301
3302         /* fill in ARGV array */
3303         setari_u(intvar[ARGV], 0, "awk");
3304         i = 0;
3305         while (*argv)
3306                 setari_u(intvar[ARGV], ++i, *argv++);
3307         setvar_i(intvar[ARGC], i + 1);
3308
3309         evaluate(beginseq.first, &tv);
3310         if (!mainseq.first && !endseq.first)
3311                 awk_exit(EXIT_SUCCESS);
3312
3313         /* input file could already be opened in BEGIN block */
3314         if (!iF)
3315                 iF = next_input_file();
3316
3317         /* passing through input files */
3318         while (iF) {
3319                 nextfile = FALSE;
3320                 setvar_i(intvar[FNR], 0);
3321
3322                 while ((i = awk_getline(iF, intvar[F0])) > 0) {
3323                         nextrec = FALSE;
3324                         incvar(intvar[NR]);
3325                         incvar(intvar[FNR]);
3326                         evaluate(mainseq.first, &tv);
3327
3328                         if (nextfile)
3329                                 break;
3330                 }
3331
3332                 if (i < 0)
3333                         syntax_error(strerror(errno));
3334
3335                 iF = next_input_file();
3336         }
3337
3338         awk_exit(EXIT_SUCCESS);
3339         /*return 0;*/
3340 }