1 /* vi: set sw=4 ts=4: */
3 * awk implementation for busybox
5 * Copyright (C) 2002 by Dmitry Zakharov <dmit@crp.bank.gov.ua>
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
11 //config: bool "awk (22 kb)"
14 //config: Awk is used as a pattern scanning and processing language.
16 //config:config FEATURE_AWK_LIBM
17 //config: bool "Enable math functions (requires libm)"
19 //config: depends on AWK
21 //config: Enable math functions of the Awk programming language.
22 //config: NOTE: This requires libm to be present for linking.
24 //config:config FEATURE_AWK_GNU_EXTENSIONS
25 //config: bool "Enable a few GNU extensions"
27 //config: depends on AWK
29 //config: Enable a few features from gawk:
30 //config: * command line option -e AWK_PROGRAM
31 //config: * simultaneous use of -f and -e on the command line.
32 //config: This enables the use of awk library files.
33 //config: Example: awk -f mylib.awk -e '{print myfunction($1);}' ...
35 //applet:IF_AWK(APPLET_NOEXEC(awk, awk, BB_DIR_USR_BIN, BB_SUID_DROP, awk))
37 //kbuild:lib-$(CONFIG_AWK) += awk.o
39 //usage:#define awk_trivial_usage
40 //usage: "[OPTIONS] [AWK_PROGRAM] [FILE]..."
41 //usage:#define awk_full_usage "\n\n"
42 //usage: " -v VAR=VAL Set variable"
43 //usage: "\n -F SEP Use SEP as field separator"
44 //usage: "\n -f FILE Read program from FILE"
45 //usage: IF_FEATURE_AWK_GNU_EXTENSIONS(
46 //usage: "\n -e AWK_PROGRAM"
53 /* This is a NOEXEC applet. Be very careful! */
56 /* If you comment out one of these below, it will be #defined later
57 * to perform debug printfs to stderr: */
58 #define debug_printf_walker(...) do {} while (0)
59 #define debug_printf_eval(...) do {} while (0)
60 #define debug_printf_parse(...) do {} while (0)
62 #ifndef debug_printf_walker
63 # define debug_printf_walker(...) (fprintf(stderr, __VA_ARGS__))
65 #ifndef debug_printf_eval
66 # define debug_printf_eval(...) (fprintf(stderr, __VA_ARGS__))
68 #ifndef debug_printf_parse
69 # define debug_printf_parse(...) (fprintf(stderr, __VA_ARGS__))
75 IF_FEATURE_AWK_GNU_EXTENSIONS("e:*") \
78 OPTBIT_F, /* define field separator */
79 OPTBIT_v, /* define variable */
80 OPTBIT_f, /* pull in awk program from file */
81 IF_FEATURE_AWK_GNU_EXTENSIONS(OPTBIT_e,) /* -e AWK_PROGRAM */
82 OPTBIT_W, /* -W ignored */
83 OPT_F = 1 << OPTBIT_F,
84 OPT_v = 1 << OPTBIT_v,
85 OPT_f = 1 << OPTBIT_f,
86 OPT_e = IF_FEATURE_AWK_GNU_EXTENSIONS((1 << OPTBIT_e)) + 0,
94 #define VF_NUMBER 0x0001 /* 1 = primary type is number */
95 #define VF_ARRAY 0x0002 /* 1 = it's an array */
97 #define VF_CACHED 0x0100 /* 1 = num/str value has cached str/num eq */
98 #define VF_USER 0x0200 /* 1 = user input (may be numeric string) */
99 #define VF_SPECIAL 0x0400 /* 1 = requires extra handling when changed */
100 #define VF_WALK 0x0800 /* 1 = variable has alloc'd x.walker list */
101 #define VF_FSTR 0x1000 /* 1 = var::string points to fstring buffer */
102 #define VF_CHILD 0x2000 /* 1 = function arg; x.parent points to source */
103 #define VF_DIRTY 0x4000 /* 1 = variable was set explicitly */
105 /* these flags are static, don't change them when value is changed */
106 #define VF_DONTTOUCH (VF_ARRAY | VF_SPECIAL | VF_WALK | VF_CHILD | VF_DIRTY)
108 typedef struct walker_list {
111 struct walker_list *prev;
116 typedef struct var_s {
117 unsigned type; /* flags */
121 int aidx; /* func arg idx (for compilation stage) */
122 struct xhash_s *array; /* array ptr */
123 struct var_s *parent; /* for func args, ptr to actual parameter */
124 walker_list *walker; /* list of array elements (for..in) */
128 /* Node chain (pattern-action chain, BEGIN, END, function bodies) */
129 typedef struct chain_s {
130 struct node_s *first;
132 const char *programname;
136 typedef struct func_s {
142 typedef struct rstream_s {
151 typedef struct hash_item_s {
153 struct var_s v; /* variable/array hash */
154 struct rstream_s rs; /* redirect streams hash */
155 struct func_s f; /* functions hash */
157 struct hash_item_s *next; /* next in chain */
158 char name[1]; /* really it's longer */
161 typedef struct xhash_s {
162 unsigned nel; /* num of elements */
163 unsigned csize; /* current hash size */
164 unsigned nprime; /* next hash size in PRIMES[] */
165 unsigned glen; /* summary length of item names */
166 struct hash_item_s **items;
170 typedef struct node_s {
190 /* Block of temporary variables */
191 typedef struct nvblock_s {
194 struct nvblock_s *prev;
195 struct nvblock_s *next;
199 typedef struct tsplitter_s {
204 /* simple token classes */
205 /* Order and hex values are very important!!! See next_token() */
206 #define TC_SEQSTART (1 << 0) /* ( */
207 #define TC_SEQTERM (1 << 1) /* ) */
208 #define TC_REGEXP (1 << 2) /* /.../ */
209 #define TC_OUTRDR (1 << 3) /* | > >> */
210 #define TC_UOPPOST (1 << 4) /* unary postfix operator */
211 #define TC_UOPPRE1 (1 << 5) /* unary prefix operator */
212 #define TC_BINOPX (1 << 6) /* two-opnd operator */
213 #define TC_IN (1 << 7)
214 #define TC_COMMA (1 << 8)
215 #define TC_PIPE (1 << 9) /* input redirection pipe */
216 #define TC_UOPPRE2 (1 << 10) /* unary prefix operator */
217 #define TC_ARRTERM (1 << 11) /* ] */
218 #define TC_GRPSTART (1 << 12) /* { */
219 #define TC_GRPTERM (1 << 13) /* } */
220 #define TC_SEMICOL (1 << 14)
221 #define TC_NEWLINE (1 << 15)
222 #define TC_STATX (1 << 16) /* ctl statement (for, next...) */
223 #define TC_WHILE (1 << 17)
224 #define TC_ELSE (1 << 18)
225 #define TC_BUILTIN (1 << 19)
226 /* This costs ~50 bytes of code.
227 * A separate class to support deprecated "length" form. If we don't need that
228 * (i.e. if we demand that only "length()" with () is valid), then TC_LENGTH
229 * can be merged with TC_BUILTIN:
231 #define TC_LENGTH (1 << 20)
232 #define TC_GETLINE (1 << 21)
233 #define TC_FUNCDECL (1 << 22) /* 'function' 'func' */
234 #define TC_BEGIN (1 << 23)
235 #define TC_END (1 << 24)
236 #define TC_EOF (1 << 25)
237 #define TC_VARIABLE (1 << 26)
238 #define TC_ARRAY (1 << 27)
239 #define TC_FUNCTION (1 << 28)
240 #define TC_STRING (1 << 29)
241 #define TC_NUMBER (1 << 30)
243 #define TC_UOPPRE (TC_UOPPRE1 | TC_UOPPRE2)
245 /* combined token classes */
246 #define TC_BINOP (TC_BINOPX | TC_COMMA | TC_PIPE | TC_IN)
247 //#define TC_UNARYOP (TC_UOPPRE | TC_UOPPOST)
248 #define TC_OPERAND (TC_VARIABLE | TC_ARRAY | TC_FUNCTION \
249 | TC_BUILTIN | TC_LENGTH | TC_GETLINE \
250 | TC_SEQSTART | TC_STRING | TC_NUMBER)
252 #define TC_STATEMNT (TC_STATX | TC_WHILE)
253 #define TC_OPTERM (TC_SEMICOL | TC_NEWLINE)
255 /* word tokens, cannot mean something else if not expected */
256 #define TC_WORD (TC_IN | TC_STATEMNT | TC_ELSE \
257 | TC_BUILTIN | TC_LENGTH | TC_GETLINE \
258 | TC_FUNCDECL | TC_BEGIN | TC_END)
260 /* discard newlines after these */
261 #define TC_NOTERM (TC_COMMA | TC_GRPSTART | TC_GRPTERM \
262 | TC_BINOP | TC_OPTERM)
264 /* what can expression begin with */
265 #define TC_OPSEQ (TC_OPERAND | TC_UOPPRE | TC_REGEXP)
266 /* what can group begin with */
267 #define TC_GRPSEQ (TC_OPSEQ | TC_OPTERM | TC_STATEMNT | TC_GRPSTART)
269 /* if previous token class is CONCAT1 and next is CONCAT2, concatenation */
270 /* operator is inserted between them */
271 #define TC_CONCAT1 (TC_VARIABLE | TC_ARRTERM | TC_SEQTERM \
272 | TC_STRING | TC_NUMBER | TC_UOPPOST)
273 #define TC_CONCAT2 (TC_OPERAND | TC_UOPPRE)
275 #define OF_RES1 0x010000
276 #define OF_RES2 0x020000
277 #define OF_STR1 0x040000
278 #define OF_STR2 0x080000
279 #define OF_NUM1 0x100000
280 #define OF_CHECKED 0x200000
282 /* combined operator flags */
285 #define xS (OF_RES2 | OF_STR2)
287 #define VV (OF_RES1 | OF_RES2)
288 #define Nx (OF_RES1 | OF_NUM1)
289 #define NV (OF_RES1 | OF_NUM1 | OF_RES2)
290 #define Sx (OF_RES1 | OF_STR1)
291 #define SV (OF_RES1 | OF_STR1 | OF_RES2)
292 #define SS (OF_RES1 | OF_STR1 | OF_RES2 | OF_STR2)
294 #define OPCLSMASK 0xFF00
295 #define OPNMASK 0x007F
297 /* operator priority is a highest byte (even: r->l, odd: l->r grouping)
298 * For builtins it has different meaning: n n s3 s2 s1 v3 v2 v1,
299 * n - min. number of args, vN - resolve Nth arg to var, sN - resolve to string
304 #define P(x) (x << 24)
305 #define PRIMASK 0x7F000000
306 #define PRIMASK2 0x7E000000
308 /* Operation classes */
310 #define SHIFT_TIL_THIS 0x0600
311 #define RECUR_FROM_THIS 0x1000
314 OC_DELETE = 0x0100, OC_EXEC = 0x0200, OC_NEWSOURCE = 0x0300,
315 OC_PRINT = 0x0400, OC_PRINTF = 0x0500, OC_WALKINIT = 0x0600,
317 OC_BR = 0x0700, OC_BREAK = 0x0800, OC_CONTINUE = 0x0900,
318 OC_EXIT = 0x0a00, OC_NEXT = 0x0b00, OC_NEXTFILE = 0x0c00,
319 OC_TEST = 0x0d00, OC_WALKNEXT = 0x0e00,
321 OC_BINARY = 0x1000, OC_BUILTIN = 0x1100, OC_COLON = 0x1200,
322 OC_COMMA = 0x1300, OC_COMPARE = 0x1400, OC_CONCAT = 0x1500,
323 OC_FBLTIN = 0x1600, OC_FIELD = 0x1700, OC_FNARG = 0x1800,
324 OC_FUNC = 0x1900, OC_GETLINE = 0x1a00, OC_IN = 0x1b00,
325 OC_LAND = 0x1c00, OC_LOR = 0x1d00, OC_MATCH = 0x1e00,
326 OC_MOVE = 0x1f00, OC_PGETLINE = 0x2000, OC_REGEXP = 0x2100,
327 OC_REPLACE = 0x2200, OC_RETURN = 0x2300, OC_SPRINTF = 0x2400,
328 OC_TERNARY = 0x2500, OC_UNARY = 0x2600, OC_VAR = 0x2700,
331 ST_IF = 0x3000, ST_DO = 0x3100, ST_FOR = 0x3200,
335 /* simple builtins */
337 F_in, F_rn, F_co, F_ex, F_lg, F_si, F_sq, F_sr,
338 F_ti, F_le, F_sy, F_ff, F_cl
343 B_a2, B_ix, B_ma, B_sp, B_ss, B_ti, B_mt, B_lo, B_up,
345 B_an, B_co, B_ls, B_or, B_rs, B_xo,
348 /* tokens and their corresponding info values */
350 #define NTC "\377" /* switch to next token class (tc<<1) */
353 static const char tokenlist[] ALIGN1 =
354 "\1(" NTC /* TC_SEQSTART */
355 "\1)" NTC /* TC_SEQTERM */
356 "\1/" NTC /* TC_REGEXP */
357 "\2>>" "\1>" "\1|" NTC /* TC_OUTRDR */
358 "\2++" "\2--" NTC /* TC_UOPPOST */
359 "\2++" "\2--" "\1$" NTC /* TC_UOPPRE1 */
360 "\2==" "\1=" "\2+=" "\2-=" /* TC_BINOPX */
361 "\2*=" "\2/=" "\2%=" "\2^="
362 "\1+" "\1-" "\3**=" "\2**"
363 "\1/" "\1%" "\1^" "\1*"
364 "\2!=" "\2>=" "\2<=" "\1>"
365 "\1<" "\2!~" "\1~" "\2&&"
366 "\2||" "\1?" "\1:" NTC
367 "\2in" NTC /* TC_IN */
368 "\1," NTC /* TC_COMMA */
369 "\1|" NTC /* TC_PIPE */
370 "\1+" "\1-" "\1!" NTC /* TC_UOPPRE2 */
371 "\1]" NTC /* TC_ARRTERM */
372 "\1{" NTC /* TC_GRPSTART */
373 "\1}" NTC /* TC_GRPTERM */
374 "\1;" NTC /* TC_SEMICOL */
375 "\1\n" NTC /* TC_NEWLINE */
376 "\2if" "\2do" "\3for" "\5break" /* TC_STATX */
377 "\10continue" "\6delete" "\5print"
378 "\6printf" "\4next" "\10nextfile"
379 "\6return" "\4exit" NTC
380 "\5while" NTC /* TC_WHILE */
381 "\4else" NTC /* TC_ELSE */
382 "\3and" "\5compl" "\6lshift" "\2or" /* TC_BUILTIN */
384 "\5close" "\6system" "\6fflush" "\5atan2"
385 "\3cos" "\3exp" "\3int" "\3log"
386 "\4rand" "\3sin" "\4sqrt" "\5srand"
387 "\6gensub" "\4gsub" "\5index" /* "\6length" was here */
388 "\5match" "\5split" "\7sprintf" "\3sub"
389 "\6substr" "\7systime" "\10strftime" "\6mktime"
390 "\7tolower" "\7toupper" NTC
391 "\6length" NTC /* TC_LENGTH */
392 "\7getline" NTC /* TC_GETLINE */
393 "\4func" "\10function" NTC /* TC_FUNCDECL */
394 "\5BEGIN" NTC /* TC_BEGIN */
396 /* compiler adds trailing "\0" */
399 #define OC_B OC_BUILTIN
401 static const uint32_t tokeninfo[] = {
405 xS|'a', xS|'w', xS|'|',
406 OC_UNARY|xV|P(9)|'p', OC_UNARY|xV|P(9)|'m',
407 OC_UNARY|xV|P(9)|'P', OC_UNARY|xV|P(9)|'M', OC_FIELD|xV|P(5),
408 OC_COMPARE|VV|P(39)|5, OC_MOVE|VV|P(74), OC_REPLACE|NV|P(74)|'+', OC_REPLACE|NV|P(74)|'-',
409 OC_REPLACE|NV|P(74)|'*', OC_REPLACE|NV|P(74)|'/', OC_REPLACE|NV|P(74)|'%', OC_REPLACE|NV|P(74)|'&',
410 OC_BINARY|NV|P(29)|'+', OC_BINARY|NV|P(29)|'-', OC_REPLACE|NV|P(74)|'&', OC_BINARY|NV|P(15)|'&',
411 OC_BINARY|NV|P(25)|'/', OC_BINARY|NV|P(25)|'%', OC_BINARY|NV|P(15)|'&', OC_BINARY|NV|P(25)|'*',
412 OC_COMPARE|VV|P(39)|4, OC_COMPARE|VV|P(39)|3, OC_COMPARE|VV|P(39)|0, OC_COMPARE|VV|P(39)|1,
413 OC_COMPARE|VV|P(39)|2, OC_MATCH|Sx|P(45)|'!', OC_MATCH|Sx|P(45)|'~', OC_LAND|Vx|P(55),
414 OC_LOR|Vx|P(59), OC_TERNARY|Vx|P(64)|'?', OC_COLON|xx|P(67)|':',
415 OC_IN|SV|P(49), /* TC_IN */
417 OC_PGETLINE|SV|P(37),
418 OC_UNARY|xV|P(19)|'+', OC_UNARY|xV|P(19)|'-', OC_UNARY|xV|P(19)|'!',
424 ST_IF, ST_DO, ST_FOR, OC_BREAK,
425 OC_CONTINUE, OC_DELETE|Vx, OC_PRINT,
426 OC_PRINTF, OC_NEXT, OC_NEXTFILE,
427 OC_RETURN|Vx, OC_EXIT|Nx,
430 OC_B|B_an|P(0x83), OC_B|B_co|P(0x41), OC_B|B_ls|P(0x83), OC_B|B_or|P(0x83),
431 OC_B|B_rs|P(0x83), OC_B|B_xo|P(0x83),
432 OC_FBLTIN|Sx|F_cl, OC_FBLTIN|Sx|F_sy, OC_FBLTIN|Sx|F_ff, OC_B|B_a2|P(0x83),
433 OC_FBLTIN|Nx|F_co, OC_FBLTIN|Nx|F_ex, OC_FBLTIN|Nx|F_in, OC_FBLTIN|Nx|F_lg,
434 OC_FBLTIN|F_rn, OC_FBLTIN|Nx|F_si, OC_FBLTIN|Nx|F_sq, OC_FBLTIN|Nx|F_sr,
435 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 */
436 OC_B|B_ma|P(0x89), OC_B|B_sp|P(0x8b), OC_SPRINTF, OC_B|B_su|P(0xb6),
437 OC_B|B_ss|P(0x8f), OC_FBLTIN|F_ti, OC_B|B_ti|P(0x0b), OC_B|B_mt|P(0x0b),
438 OC_B|B_lo|P(0x49), OC_B|B_up|P(0x49),
439 OC_FBLTIN|Sx|F_le, /* TC_LENGTH */
446 /* internal variable names and their initial values */
447 /* asterisk marks SPECIAL vars; $ is just no-named Field0 */
449 CONVFMT, OFMT, FS, OFS,
450 ORS, RS, RT, FILENAME,
451 SUBSEP, F0, ARGIND, ARGC,
452 ARGV, ERRNO, FNR, NR,
453 NF, IGNORECASE, ENVIRON, NUM_INTERNAL_VARS
456 static const char vNames[] ALIGN1 =
457 "CONVFMT\0" "OFMT\0" "FS\0*" "OFS\0"
458 "ORS\0" "RS\0*" "RT\0" "FILENAME\0"
459 "SUBSEP\0" "$\0*" "ARGIND\0" "ARGC\0"
460 "ARGV\0" "ERRNO\0" "FNR\0" "NR\0"
461 "NF\0*" "IGNORECASE\0*" "ENVIRON\0" "\0";
463 static const char vValues[] ALIGN1 =
464 "%.6g\0" "%.6g\0" " \0" " \0"
465 "\n\0" "\n\0" "\0" "\0"
466 "\034\0" "\0" "\377";
468 /* hash size may grow to these values */
469 #define FIRST_PRIME 61
470 static const uint16_t PRIMES[] ALIGN2 = { 251, 1021, 4093, 16381, 65521 };
473 /* Globals. Split in two parts so that first one is addressed
474 * with (mostly short) negative offsets.
475 * NB: it's unsafe to put members of type "double"
476 * into globals2 (gcc may fail to align them).
480 chain beginseq, mainseq, endseq;
482 node *break_ptr, *continue_ptr;
484 xhash *vhash, *ahash, *fdhash, *fnhash;
485 const char *g_progname;
488 int maxfields; /* used in fsrealloc() only */
497 smallint is_f0_split;
501 uint32_t t_info; /* often used */
506 var *intvar[NUM_INTERNAL_VARS]; /* often used */
508 /* former statics from various functions */
509 char *split_f0__fstrings;
511 uint32_t next_token__save_tclass;
512 uint32_t next_token__save_info;
513 uint32_t next_token__ltclass;
514 smallint next_token__concat_inserted;
516 smallint next_input_file__files_happen;
517 rstream next_input_file__rsm;
519 var *evaluate__fnargs;
520 unsigned evaluate__seed;
521 regex_t evaluate__sreg;
525 tsplitter exec_builtin__tspl;
527 /* biggest and least used members go last */
528 tsplitter fsplitter, rsplitter;
530 #define G1 (ptr_to_globals[-1])
531 #define G (*(struct globals2 *)ptr_to_globals)
532 /* For debug. nm --size-sort awk.o | grep -vi ' [tr] ' */
533 /*char G1size[sizeof(G1)]; - 0x74 */
534 /*char Gsize[sizeof(G)]; - 0x1c4 */
535 /* Trying to keep most of members accessible with short offsets: */
536 /*char Gofs_seed[offsetof(struct globals2, evaluate__seed)]; - 0x90 */
537 #define t_double (G1.t_double )
538 #define beginseq (G1.beginseq )
539 #define mainseq (G1.mainseq )
540 #define endseq (G1.endseq )
541 #define seq (G1.seq )
542 #define break_ptr (G1.break_ptr )
543 #define continue_ptr (G1.continue_ptr)
545 #define vhash (G1.vhash )
546 #define ahash (G1.ahash )
547 #define fdhash (G1.fdhash )
548 #define fnhash (G1.fnhash )
549 #define g_progname (G1.g_progname )
550 #define g_lineno (G1.g_lineno )
551 #define nfields (G1.nfields )
552 #define maxfields (G1.maxfields )
553 #define Fields (G1.Fields )
554 #define g_cb (G1.g_cb )
555 #define g_pos (G1.g_pos )
556 #define g_buf (G1.g_buf )
557 #define icase (G1.icase )
558 #define exiting (G1.exiting )
559 #define nextrec (G1.nextrec )
560 #define nextfile (G1.nextfile )
561 #define is_f0_split (G1.is_f0_split )
562 #define t_rollback (G1.t_rollback )
563 #define t_info (G.t_info )
564 #define t_tclass (G.t_tclass )
565 #define t_string (G.t_string )
566 #define t_lineno (G.t_lineno )
567 #define intvar (G.intvar )
568 #define fsplitter (G.fsplitter )
569 #define rsplitter (G.rsplitter )
570 #define INIT_G() do { \
571 SET_PTR_TO_GLOBALS((char*)xzalloc(sizeof(G1)+sizeof(G)) + sizeof(G1)); \
572 G.next_token__ltclass = TC_OPTERM; \
573 G.evaluate__seed = 1; \
577 /* function prototypes */
578 static void handle_special(var *);
579 static node *parse_expr(uint32_t);
580 static void chain_group(void);
581 static var *evaluate(node *, var *);
582 static rstream *next_input_file(void);
583 static int fmt_num(char *, int, const char *, double, int);
584 static int awk_exit(int) NORETURN;
586 /* ---- error handling ---- */
588 static const char EMSG_INTERNAL_ERROR[] ALIGN1 = "Internal error";
589 static const char EMSG_UNEXP_EOS[] ALIGN1 = "Unexpected end of string";
590 static const char EMSG_UNEXP_TOKEN[] ALIGN1 = "Unexpected token";
591 static const char EMSG_DIV_BY_ZERO[] ALIGN1 = "Division by zero";
592 static const char EMSG_INV_FMT[] ALIGN1 = "Invalid format specifier";
593 static const char EMSG_TOO_FEW_ARGS[] ALIGN1 = "Too few arguments for builtin";
594 static const char EMSG_NOT_ARRAY[] ALIGN1 = "Not an array";
595 static const char EMSG_POSSIBLE_ERROR[] ALIGN1 = "Possible syntax error";
596 static const char EMSG_UNDEF_FUNC[] ALIGN1 = "Call to undefined function";
597 static const char EMSG_NO_MATH[] ALIGN1 = "Math support is not compiled in";
599 static void zero_out_var(var *vp)
601 memset(vp, 0, sizeof(*vp));
604 static void syntax_error(const char *message) NORETURN;
605 static void syntax_error(const char *message)
607 bb_error_msg_and_die("%s:%i: %s", g_progname, g_lineno, message);
610 /* ---- hash stuff ---- */
612 static unsigned hashidx(const char *name)
617 idx = *name++ + (idx << 6) - idx;
621 /* create new hash */
622 static xhash *hash_init(void)
626 newhash = xzalloc(sizeof(*newhash));
627 newhash->csize = FIRST_PRIME;
628 newhash->items = xzalloc(FIRST_PRIME * sizeof(newhash->items[0]));
633 /* find item in hash, return ptr to data, NULL if not found */
634 static void *hash_search(xhash *hash, const char *name)
638 hi = hash->items[hashidx(name) % hash->csize];
640 if (strcmp(hi->name, name) == 0)
647 /* grow hash if it becomes too big */
648 static void hash_rebuild(xhash *hash)
650 unsigned newsize, i, idx;
651 hash_item **newitems, *hi, *thi;
653 if (hash->nprime == ARRAY_SIZE(PRIMES))
656 newsize = PRIMES[hash->nprime++];
657 newitems = xzalloc(newsize * sizeof(newitems[0]));
659 for (i = 0; i < hash->csize; i++) {
664 idx = hashidx(thi->name) % newsize;
665 thi->next = newitems[idx];
671 hash->csize = newsize;
672 hash->items = newitems;
675 /* find item in hash, add it if necessary. Return ptr to data */
676 static void *hash_find(xhash *hash, const char *name)
682 hi = hash_search(hash, name);
684 if (++hash->nel / hash->csize > 10)
687 l = strlen(name) + 1;
688 hi = xzalloc(sizeof(*hi) + l);
689 strcpy(hi->name, name);
691 idx = hashidx(name) % hash->csize;
692 hi->next = hash->items[idx];
693 hash->items[idx] = hi;
699 #define findvar(hash, name) ((var*) hash_find((hash), (name)))
700 #define newvar(name) ((var*) hash_find(vhash, (name)))
701 #define newfile(name) ((rstream*)hash_find(fdhash, (name)))
702 #define newfunc(name) ((func*) hash_find(fnhash, (name)))
704 static void hash_remove(xhash *hash, const char *name)
706 hash_item *hi, **phi;
708 phi = &hash->items[hashidx(name) % hash->csize];
711 if (strcmp(hi->name, name) == 0) {
712 hash->glen -= (strlen(name) + 1);
722 /* ------ some useful functions ------ */
724 static char *skip_spaces(char *p)
727 if (*p == '\\' && p[1] == '\n') {
730 } else if (*p != ' ' && *p != '\t') {
738 /* returns old *s, advances *s past word and terminating NUL */
739 static char *nextword(char **s)
742 while (*(*s)++ != '\0')
747 static char nextchar(char **s)
754 c = bb_process_escape_sequence((const char**)s);
755 /* Example awk statement:
757 * we must treat \" as "
759 if (c == '\\' && *s == pps) { /* unrecognized \z? */
760 c = *(*s); /* yes, fetch z */
762 (*s)++; /* advance unless z = NUL */
767 /* TODO: merge with strcpy_and_process_escape_sequences()?
769 static void unescape_string_in_place(char *s1)
772 while ((*s1 = nextchar(&s)) != '\0')
776 static ALWAYS_INLINE int isalnum_(int c)
778 return (isalnum(c) || c == '_');
781 static double my_strtod(char **pp)
784 if (ENABLE_DESKTOP && cp[0] == '0') {
785 /* Might be hex or octal integer: 0x123abc or 07777 */
786 char c = (cp[1] | 0x20);
787 if (c == 'x' || isdigit(cp[1])) {
788 unsigned long long ull = strtoull(cp, pp, 0);
792 if (!isdigit(c) && c != '.')
794 /* else: it may be a floating number. Examples:
795 * 009.123 (*pp points to '9')
796 * 000.123 (*pp points to '.')
797 * fall through to strtod.
801 return strtod(cp, pp);
804 /* -------- working with variables (set/get/copy/etc) -------- */
806 static xhash *iamarray(var *v)
810 while (a->type & VF_CHILD)
813 if (!(a->type & VF_ARRAY)) {
815 a->x.array = hash_init();
820 static void clear_array(xhash *array)
825 for (i = 0; i < array->csize; i++) {
826 hi = array->items[i];
830 free(thi->data.v.string);
833 array->items[i] = NULL;
835 array->glen = array->nel = 0;
838 /* clear a variable */
839 static var *clrvar(var *v)
841 if (!(v->type & VF_FSTR))
844 v->type &= VF_DONTTOUCH;
850 /* assign string value to variable */
851 static var *setvar_p(var *v, char *value)
859 /* same as setvar_p but make a copy of string */
860 static var *setvar_s(var *v, const char *value)
862 return setvar_p(v, (value && *value) ? xstrdup(value) : NULL);
865 /* same as setvar_s but sets USER flag */
866 static var *setvar_u(var *v, const char *value)
868 v = setvar_s(v, value);
873 /* set array element to user string */
874 static void setari_u(var *a, int idx, const char *s)
878 v = findvar(iamarray(a), itoa(idx));
882 /* assign numeric value to variable */
883 static var *setvar_i(var *v, double value)
886 v->type |= VF_NUMBER;
892 static const char *getvar_s(var *v)
894 /* if v is numeric and has no cached string, convert it to string */
895 if ((v->type & (VF_NUMBER | VF_CACHED)) == VF_NUMBER) {
896 fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[CONVFMT]), v->number, TRUE);
897 v->string = xstrdup(g_buf);
898 v->type |= VF_CACHED;
900 return (v->string == NULL) ? "" : v->string;
903 static double getvar_i(var *v)
907 if ((v->type & (VF_NUMBER | VF_CACHED)) == 0) {
911 debug_printf_eval("getvar_i: '%s'->", s);
912 v->number = my_strtod(&s);
913 debug_printf_eval("%f (s:'%s')\n", v->number, s);
914 if (v->type & VF_USER) {
920 debug_printf_eval("getvar_i: '%s'->zero\n", s);
923 v->type |= VF_CACHED;
925 debug_printf_eval("getvar_i: %f\n", v->number);
929 /* Used for operands of bitwise ops */
930 static unsigned long getvar_i_int(var *v)
932 double d = getvar_i(v);
934 /* Casting doubles to longs is undefined for values outside
935 * of target type range. Try to widen it as much as possible */
937 return (unsigned long)d;
938 /* Why? Think about d == -4294967295.0 (assuming 32bit longs) */
939 return - (long) (unsigned long) (-d);
942 static var *copyvar(var *dest, const var *src)
946 dest->type |= (src->type & ~(VF_DONTTOUCH | VF_FSTR));
947 debug_printf_eval("copyvar: number:%f string:'%s'\n", src->number, src->string);
948 dest->number = src->number;
950 dest->string = xstrdup(src->string);
952 handle_special(dest);
956 static var *incvar(var *v)
958 return setvar_i(v, getvar_i(v) + 1.0);
961 /* return true if v is number or numeric string */
962 static int is_numeric(var *v)
965 return ((v->type ^ VF_DIRTY) & (VF_NUMBER | VF_USER | VF_DIRTY));
968 /* return 1 when value of v corresponds to true, 0 otherwise */
969 static int istrue(var *v)
972 return (v->number != 0);
973 return (v->string && v->string[0]);
976 /* temporary variables allocator. Last allocated should be first freed */
977 static var *nvalloc(int n)
985 if ((g_cb->pos - g_cb->nv) + n <= g_cb->size)
991 size = (n <= MINNVBLOCK) ? MINNVBLOCK : n;
992 g_cb = xzalloc(sizeof(nvblock) + size * sizeof(var));
994 g_cb->pos = g_cb->nv;
996 /*g_cb->next = NULL; - xzalloc did it */
1004 while (v < g_cb->pos) {
1013 static void nvfree(var *v)
1017 if (v < g_cb->nv || v >= g_cb->pos)
1018 syntax_error(EMSG_INTERNAL_ERROR);
1020 for (p = v; p < g_cb->pos; p++) {
1021 if ((p->type & (VF_ARRAY | VF_CHILD)) == VF_ARRAY) {
1022 clear_array(iamarray(p));
1023 free(p->x.array->items);
1026 if (p->type & VF_WALK) {
1028 walker_list *w = p->x.walker;
1029 debug_printf_walker("nvfree: freeing walker @%p\n", &p->x.walker);
1033 debug_printf_walker(" free(%p)\n", w);
1042 while (g_cb->prev && g_cb->pos == g_cb->nv) {
1047 /* ------- awk program text parsing ------- */
1049 /* Parse next token pointed by global pos, place results into global ttt.
1050 * If token isn't expected, give away. Return token class
1052 static uint32_t next_token(uint32_t expected)
1054 #define concat_inserted (G.next_token__concat_inserted)
1055 #define save_tclass (G.next_token__save_tclass)
1056 #define save_info (G.next_token__save_info)
1057 /* Initialized to TC_OPTERM: */
1058 #define ltclass (G.next_token__ltclass)
1067 } else if (concat_inserted) {
1068 concat_inserted = FALSE;
1069 t_tclass = save_tclass;
1075 g_lineno = t_lineno;
1077 while (*p != '\n' && *p != '\0')
1085 debug_printf_parse("%s: token found: TC_EOF\n", __func__);
1086 } else if (*p == '\"') {
1089 while (*p != '\"') {
1091 if (*p == '\0' || *p == '\n')
1092 syntax_error(EMSG_UNEXP_EOS);
1094 *s++ = nextchar(&pp);
1100 debug_printf_parse("%s: token found:'%s' TC_STRING\n", __func__, t_string);
1101 } else if ((expected & TC_REGEXP) && *p == '/') {
1105 if (*p == '\0' || *p == '\n')
1106 syntax_error(EMSG_UNEXP_EOS);
1110 s[-1] = bb_process_escape_sequence((const char **)&pp);
1122 debug_printf_parse("%s: token found:'%s' TC_REGEXP\n", __func__, t_string);
1124 } else if (*p == '.' || isdigit(*p)) {
1127 t_double = my_strtod(&pp);
1130 syntax_error(EMSG_UNEXP_TOKEN);
1132 debug_printf_parse("%s: token found:%f TC_NUMBER\n", __func__, t_double);
1134 /* search for something known */
1139 int l = (unsigned char) *tl++;
1140 if (l == (unsigned char) NTCC) {
1144 /* if token class is expected,
1146 * and it's not a longer word,
1148 if ((tc & (expected | TC_WORD | TC_NEWLINE))
1149 && strncmp(p, tl, l) == 0
1150 && !((tc & TC_WORD) && isalnum_(p[l]))
1152 /* then this is what we are looking for */
1154 debug_printf_parse("%s: token found:'%.*s' t_info:%x\n", __func__, l, p, t_info);
1161 /* not a known token */
1163 /* is it a name? (var/array/function) */
1165 syntax_error(EMSG_UNEXP_TOKEN); /* no */
1168 while (isalnum_(*++p)) {
1173 /* also consume whitespace between functionname and bracket */
1174 if (!(expected & TC_VARIABLE) || (expected & TC_ARRAY))
1178 debug_printf_parse("%s: token found:'%s' TC_FUNCTION\n", __func__, t_string);
1183 debug_printf_parse("%s: token found:'%s' TC_ARRAY\n", __func__, t_string);
1185 debug_printf_parse("%s: token found:'%s' TC_VARIABLE\n", __func__, t_string);
1191 /* skipping newlines in some cases */
1192 if ((ltclass & TC_NOTERM) && (tc & TC_NEWLINE))
1195 /* insert concatenation operator when needed */
1196 if ((ltclass & TC_CONCAT1) && (tc & TC_CONCAT2) && (expected & TC_BINOP)) {
1197 concat_inserted = TRUE;
1201 t_info = OC_CONCAT | SS | P(35);
1208 /* Are we ready for this? */
1209 if (!(ltclass & expected)) {
1210 syntax_error((ltclass & (TC_NEWLINE | TC_EOF)) ?
1211 EMSG_UNEXP_EOS : EMSG_UNEXP_TOKEN);
1215 #undef concat_inserted
1221 static void rollback_token(void)
1226 static node *new_node(uint32_t info)
1230 n = xzalloc(sizeof(node));
1232 n->lineno = g_lineno;
1236 static void mk_re_node(const char *s, node *n, regex_t *re)
1238 n->info = OC_REGEXP;
1241 xregcomp(re, s, REG_EXTENDED);
1242 xregcomp(re + 1, s, REG_EXTENDED | REG_ICASE);
1245 static node *condition(void)
1247 next_token(TC_SEQSTART);
1248 return parse_expr(TC_SEQTERM);
1251 /* parse expression terminated by given argument, return ptr
1252 * to built subtree. Terminator is eaten by parse_expr */
1253 static node *parse_expr(uint32_t iexp)
1261 debug_printf_parse("%s(%x)\n", __func__, iexp);
1264 sn.r.n = glptr = NULL;
1265 xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP | iexp;
1267 while (!((tc = next_token(xtc)) & iexp)) {
1269 if (glptr && (t_info == (OC_COMPARE | VV | P(39) | 2))) {
1270 /* input redirection (<) attached to glptr node */
1271 debug_printf_parse("%s: input redir\n", __func__);
1272 cn = glptr->l.n = new_node(OC_CONCAT | SS | P(37));
1274 xtc = TC_OPERAND | TC_UOPPRE;
1277 } else if (tc & (TC_BINOP | TC_UOPPOST)) {
1278 debug_printf_parse("%s: TC_BINOP | TC_UOPPOST\n", __func__);
1279 /* for binary and postfix-unary operators, jump back over
1280 * previous operators with higher priority */
1282 while (((t_info & PRIMASK) > (vn->a.n->info & PRIMASK2))
1283 || ((t_info == vn->info) && ((t_info & OPCLSMASK) == OC_COLON))
1287 if ((t_info & OPCLSMASK) == OC_TERNARY)
1289 cn = vn->a.n->r.n = new_node(t_info);
1291 if (tc & TC_BINOP) {
1293 xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP;
1294 if ((t_info & OPCLSMASK) == OC_PGETLINE) {
1296 next_token(TC_GETLINE);
1297 /* give maximum priority to this pipe */
1298 cn->info &= ~PRIMASK;
1299 xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1303 xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1308 debug_printf_parse("%s: other\n", __func__);
1309 /* for operands and prefix-unary operators, attach them
1312 cn = vn->r.n = new_node(t_info);
1314 xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP;
1315 if (tc & (TC_OPERAND | TC_REGEXP)) {
1316 debug_printf_parse("%s: TC_OPERAND | TC_REGEXP\n", __func__);
1317 xtc = TC_UOPPRE | TC_UOPPOST | TC_BINOP | TC_OPERAND | iexp;
1318 /* one should be very careful with switch on tclass -
1319 * only simple tclasses should be used! */
1323 debug_printf_parse("%s: TC_VARIABLE | TC_ARRAY\n", __func__);
1325 v = hash_search(ahash, t_string);
1327 cn->info = OC_FNARG;
1328 cn->l.aidx = v->x.aidx;
1330 cn->l.v = newvar(t_string);
1332 if (tc & TC_ARRAY) {
1334 cn->r.n = parse_expr(TC_ARRTERM);
1340 debug_printf_parse("%s: TC_NUMBER | TC_STRING\n", __func__);
1342 v = cn->l.v = xzalloc(sizeof(var));
1344 setvar_i(v, t_double);
1346 setvar_s(v, t_string);
1350 debug_printf_parse("%s: TC_REGEXP\n", __func__);
1351 mk_re_node(t_string, cn, xzalloc(sizeof(regex_t)*2));
1355 debug_printf_parse("%s: TC_FUNCTION\n", __func__);
1357 cn->r.f = newfunc(t_string);
1358 cn->l.n = condition();
1362 debug_printf_parse("%s: TC_SEQSTART\n", __func__);
1363 cn = vn->r.n = parse_expr(TC_SEQTERM);
1365 syntax_error("Empty sequence");
1370 debug_printf_parse("%s: TC_GETLINE\n", __func__);
1372 xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1376 debug_printf_parse("%s: TC_BUILTIN\n", __func__);
1377 cn->l.n = condition();
1381 debug_printf_parse("%s: TC_LENGTH\n", __func__);
1382 next_token(TC_SEQSTART | TC_OPTERM | TC_GRPTERM);
1384 if (t_tclass & TC_SEQSTART) {
1385 /* It was a "(" token. Handle just like TC_BUILTIN */
1386 cn->l.n = condition();
1394 debug_printf_parse("%s() returns %p\n", __func__, sn.r.n);
1398 /* add node to chain. Return ptr to alloc'd node */
1399 static node *chain_node(uint32_t info)
1404 seq->first = seq->last = new_node(0);
1406 if (seq->programname != g_progname) {
1407 seq->programname = g_progname;
1408 n = chain_node(OC_NEWSOURCE);
1409 n->l.new_progname = xstrdup(g_progname);
1414 seq->last = n->a.n = new_node(OC_DONE);
1419 static void chain_expr(uint32_t info)
1423 n = chain_node(info);
1424 n->l.n = parse_expr(TC_OPTERM | TC_GRPTERM);
1425 if (t_tclass & TC_GRPTERM)
1429 static node *chain_loop(node *nn)
1431 node *n, *n2, *save_brk, *save_cont;
1433 save_brk = break_ptr;
1434 save_cont = continue_ptr;
1436 n = chain_node(OC_BR | Vx);
1437 continue_ptr = new_node(OC_EXEC);
1438 break_ptr = new_node(OC_EXEC);
1440 n2 = chain_node(OC_EXEC | Vx);
1443 continue_ptr->a.n = n2;
1444 break_ptr->a.n = n->r.n = seq->last;
1446 continue_ptr = save_cont;
1447 break_ptr = save_brk;
1452 /* parse group and attach it to chain */
1453 static void chain_group(void)
1459 c = next_token(TC_GRPSEQ);
1460 } while (c & TC_NEWLINE);
1462 if (c & TC_GRPSTART) {
1463 debug_printf_parse("%s: TC_GRPSTART\n", __func__);
1464 while (next_token(TC_GRPSEQ | TC_GRPTERM) != TC_GRPTERM) {
1465 debug_printf_parse("%s: !TC_GRPTERM\n", __func__);
1466 if (t_tclass & TC_NEWLINE)
1471 debug_printf_parse("%s: TC_GRPTERM\n", __func__);
1472 } else if (c & (TC_OPSEQ | TC_OPTERM)) {
1473 debug_printf_parse("%s: TC_OPSEQ | TC_OPTERM\n", __func__);
1475 chain_expr(OC_EXEC | Vx);
1478 debug_printf_parse("%s: TC_STATEMNT(?)\n", __func__);
1479 switch (t_info & OPCLSMASK) {
1481 debug_printf_parse("%s: ST_IF\n", __func__);
1482 n = chain_node(OC_BR | Vx);
1483 n->l.n = condition();
1485 n2 = chain_node(OC_EXEC);
1487 if (next_token(TC_GRPSEQ | TC_GRPTERM | TC_ELSE) == TC_ELSE) {
1489 n2->a.n = seq->last;
1496 debug_printf_parse("%s: ST_WHILE\n", __func__);
1498 n = chain_loop(NULL);
1503 debug_printf_parse("%s: ST_DO\n", __func__);
1504 n2 = chain_node(OC_EXEC);
1505 n = chain_loop(NULL);
1507 next_token(TC_WHILE);
1508 n->l.n = condition();
1512 debug_printf_parse("%s: ST_FOR\n", __func__);
1513 next_token(TC_SEQSTART);
1514 n2 = parse_expr(TC_SEMICOL | TC_SEQTERM);
1515 if (t_tclass & TC_SEQTERM) { /* for-in */
1516 if (!n2 || (n2->info & OPCLSMASK) != OC_IN)
1517 syntax_error(EMSG_UNEXP_TOKEN);
1518 n = chain_node(OC_WALKINIT | VV);
1521 n = chain_loop(NULL);
1522 n->info = OC_WALKNEXT | Vx;
1524 } else { /* for (;;) */
1525 n = chain_node(OC_EXEC | Vx);
1527 n2 = parse_expr(TC_SEMICOL);
1528 n3 = parse_expr(TC_SEQTERM);
1538 debug_printf_parse("%s: OC_PRINT[F]\n", __func__);
1539 n = chain_node(t_info);
1540 n->l.n = parse_expr(TC_OPTERM | TC_OUTRDR | TC_GRPTERM);
1541 if (t_tclass & TC_OUTRDR) {
1543 n->r.n = parse_expr(TC_OPTERM | TC_GRPTERM);
1545 if (t_tclass & TC_GRPTERM)
1550 debug_printf_parse("%s: OC_BREAK\n", __func__);
1551 n = chain_node(OC_EXEC);
1557 debug_printf_parse("%s: OC_CONTINUE\n", __func__);
1558 n = chain_node(OC_EXEC);
1559 n->a.n = continue_ptr;
1563 /* delete, next, nextfile, return, exit */
1565 debug_printf_parse("%s: default\n", __func__);
1571 static void parse_program(char *p)
1580 while ((tclass = next_token(TC_EOF | TC_OPSEQ | TC_GRPSTART |
1581 TC_OPTERM | TC_BEGIN | TC_END | TC_FUNCDECL)) != TC_EOF) {
1583 if (tclass & TC_OPTERM) {
1584 debug_printf_parse("%s: TC_OPTERM\n", __func__);
1589 if (tclass & TC_BEGIN) {
1590 debug_printf_parse("%s: TC_BEGIN\n", __func__);
1593 } else if (tclass & TC_END) {
1594 debug_printf_parse("%s: TC_END\n", __func__);
1597 } else if (tclass & TC_FUNCDECL) {
1598 debug_printf_parse("%s: TC_FUNCDECL\n", __func__);
1599 next_token(TC_FUNCTION);
1601 f = newfunc(t_string);
1602 f->body.first = NULL;
1604 while (next_token(TC_VARIABLE | TC_SEQTERM) & TC_VARIABLE) {
1605 v = findvar(ahash, t_string);
1606 v->x.aidx = f->nargs++;
1608 if (next_token(TC_COMMA | TC_SEQTERM) & TC_SEQTERM)
1614 } else if (tclass & TC_OPSEQ) {
1615 debug_printf_parse("%s: TC_OPSEQ\n", __func__);
1617 cn = chain_node(OC_TEST);
1618 cn->l.n = parse_expr(TC_OPTERM | TC_EOF | TC_GRPSTART);
1619 if (t_tclass & TC_GRPSTART) {
1620 debug_printf_parse("%s: TC_GRPSTART\n", __func__);
1624 debug_printf_parse("%s: !TC_GRPSTART\n", __func__);
1625 chain_node(OC_PRINT);
1627 cn->r.n = mainseq.last;
1628 } else /* if (tclass & TC_GRPSTART) */ {
1629 debug_printf_parse("%s: TC_GRPSTART(?)\n", __func__);
1634 debug_printf_parse("%s: TC_EOF\n", __func__);
1638 /* -------- program execution part -------- */
1640 static node *mk_splitter(const char *s, tsplitter *spl)
1648 if ((n->info & OPCLSMASK) == OC_REGEXP) {
1650 regfree(ire); // TODO: nuke ire, use re+1?
1652 if (s[0] && s[1]) { /* strlen(s) > 1 */
1653 mk_re_node(s, n, re);
1655 n->info = (uint32_t) s[0];
1661 /* use node as a regular expression. Supplied with node ptr and regex_t
1662 * storage space. Return ptr to regex (if result points to preg, it should
1663 * be later regfree'd manually
1665 static regex_t *as_regex(node *op, regex_t *preg)
1671 if ((op->info & OPCLSMASK) == OC_REGEXP) {
1672 return icase ? op->r.ire : op->l.re;
1675 s = getvar_s(evaluate(op, v));
1677 cflags = icase ? REG_EXTENDED | REG_ICASE : REG_EXTENDED;
1678 /* Testcase where REG_EXTENDED fails (unpaired '{'):
1679 * echo Hi | awk 'gsub("@(samp|code|file)\{","");'
1680 * gawk 3.1.5 eats this. We revert to ~REG_EXTENDED
1681 * (maybe gsub is not supposed to use REG_EXTENDED?).
1683 if (regcomp(preg, s, cflags)) {
1684 cflags &= ~REG_EXTENDED;
1685 xregcomp(preg, s, cflags);
1691 /* gradually increasing buffer.
1692 * note that we reallocate even if n == old_size,
1693 * and thus there is at least one extra allocated byte.
1695 static char* qrealloc(char *b, int n, int *size)
1697 if (!b || n >= *size) {
1698 *size = n + (n>>1) + 80;
1699 b = xrealloc(b, *size);
1704 /* resize field storage space */
1705 static void fsrealloc(int size)
1709 if (size >= maxfields) {
1711 maxfields = size + 16;
1712 Fields = xrealloc(Fields, maxfields * sizeof(Fields[0]));
1713 for (; i < maxfields; i++) {
1714 Fields[i].type = VF_SPECIAL;
1715 Fields[i].string = NULL;
1718 /* if size < nfields, clear extra field variables */
1719 for (i = size; i < nfields; i++) {
1725 static int awk_split(const char *s, node *spl, char **slist)
1730 regmatch_t pmatch[2]; // TODO: why [2]? [1] is enough...
1732 /* in worst case, each char would be a separate field */
1733 *slist = s1 = xzalloc(strlen(s) * 2 + 3);
1736 c[0] = c[1] = (char)spl->info;
1738 if (*getvar_s(intvar[RS]) == '\0')
1742 if ((spl->info & OPCLSMASK) == OC_REGEXP) { /* regex split */
1744 return n; /* "": zero fields */
1745 n++; /* at least one field will be there */
1747 l = strcspn(s, c+2); /* len till next NUL or \n */
1748 if (regexec(icase ? spl->r.ire : spl->l.re, s, 1, pmatch, 0) == 0
1749 && pmatch[0].rm_so <= l
1751 l = pmatch[0].rm_so;
1752 if (pmatch[0].rm_eo == 0) {
1756 n++; /* we saw yet another delimiter */
1758 pmatch[0].rm_eo = l;
1763 /* make sure we remove *all* of the separator chars */
1766 } while (++l < pmatch[0].rm_eo);
1768 s += pmatch[0].rm_eo;
1772 if (c[0] == '\0') { /* null split */
1780 if (c[0] != ' ') { /* single-character split */
1782 c[0] = toupper(c[0]);
1783 c[1] = tolower(c[1]);
1787 while ((s1 = strpbrk(s1, c)) != NULL) {
1795 s = skip_whitespace(s);
1799 while (*s && !isspace(*s))
1806 static void split_f0(void)
1808 /* static char *fstrings; */
1809 #define fstrings (G.split_f0__fstrings)
1820 n = awk_split(getvar_s(intvar[F0]), &fsplitter.n, &fstrings);
1823 for (i = 0; i < n; i++) {
1824 Fields[i].string = nextword(&s);
1825 Fields[i].type |= (VF_FSTR | VF_USER | VF_DIRTY);
1828 /* set NF manually to avoid side effects */
1830 intvar[NF]->type = VF_NUMBER | VF_SPECIAL;
1831 intvar[NF]->number = nfields;
1835 /* perform additional actions when some internal variables changed */
1836 static void handle_special(var *v)
1840 const char *sep, *s;
1841 int sl, l, len, i, bsize;
1843 if (!(v->type & VF_SPECIAL))
1846 if (v == intvar[NF]) {
1847 n = (int)getvar_i(v);
1850 /* recalculate $0 */
1851 sep = getvar_s(intvar[OFS]);
1855 for (i = 0; i < n; i++) {
1856 s = getvar_s(&Fields[i]);
1859 memcpy(b+len, sep, sl);
1862 b = qrealloc(b, len+l+sl, &bsize);
1863 memcpy(b+len, s, l);
1868 setvar_p(intvar[F0], b);
1871 } else if (v == intvar[F0]) {
1872 is_f0_split = FALSE;
1874 } else if (v == intvar[FS]) {
1876 * The POSIX-2008 standard says that changing FS should have no effect on the
1877 * current input line, but only on the next one. The language is:
1879 * > Before the first reference to a field in the record is evaluated, the record
1880 * > shall be split into fields, according to the rules in Regular Expressions,
1881 * > using the value of FS that was current at the time the record was read.
1883 * So, split up current line before assignment to FS:
1887 mk_splitter(getvar_s(v), &fsplitter);
1888 } else if (v == intvar[RS]) {
1889 mk_splitter(getvar_s(v), &rsplitter);
1890 } else if (v == intvar[IGNORECASE]) {
1893 n = getvar_i(intvar[NF]);
1894 setvar_i(intvar[NF], n > v-Fields ? n : v-Fields+1);
1895 /* right here v is invalid. Just to note... */
1899 /* step through func/builtin/etc arguments */
1900 static node *nextarg(node **pn)
1905 if (n && (n->info & OPCLSMASK) == OC_COMMA) {
1914 static void hashwalk_init(var *v, xhash *array)
1919 walker_list *prev_walker;
1921 if (v->type & VF_WALK) {
1922 prev_walker = v->x.walker;
1927 debug_printf_walker("hashwalk_init: prev_walker:%p\n", prev_walker);
1929 w = v->x.walker = xzalloc(sizeof(*w) + array->glen + 1); /* why + 1? */
1930 debug_printf_walker(" walker@%p=%p\n", &v->x.walker, w);
1931 w->cur = w->end = w->wbuf;
1932 w->prev = prev_walker;
1933 for (i = 0; i < array->csize; i++) {
1934 hi = array->items[i];
1936 strcpy(w->end, hi->name);
1943 static int hashwalk_next(var *v)
1945 walker_list *w = v->x.walker;
1947 if (w->cur >= w->end) {
1948 walker_list *prev_walker = w->prev;
1950 debug_printf_walker("end of iteration, free(walker@%p:%p), prev_walker:%p\n", &v->x.walker, w, prev_walker);
1952 v->x.walker = prev_walker;
1956 setvar_s(v, nextword(&w->cur));
1960 /* evaluate node, return 1 when result is true, 0 otherwise */
1961 static int ptest(node *pattern)
1963 /* ptest__v is "static": to save stack space? */
1964 return istrue(evaluate(pattern, &G.ptest__v));
1967 /* read next record from stream rsm into a variable v */
1968 static int awk_getline(rstream *rsm, var *v)
1971 regmatch_t pmatch[2];
1972 int size, a, p, pp = 0;
1973 int fd, so, eo, r, rp;
1976 debug_printf_eval("entered %s()\n", __func__);
1978 /* we're using our own buffer since we need access to accumulating
1981 fd = fileno(rsm->F);
1986 c = (char) rsplitter.n.info;
1990 m = qrealloc(m, 256, &size);
1997 if ((rsplitter.n.info & OPCLSMASK) == OC_REGEXP) {
1998 if (regexec(icase ? rsplitter.n.r.ire : rsplitter.n.l.re,
1999 b, 1, pmatch, 0) == 0) {
2000 so = pmatch[0].rm_so;
2001 eo = pmatch[0].rm_eo;
2005 } else if (c != '\0') {
2006 s = strchr(b+pp, c);
2008 s = memchr(b+pp, '\0', p - pp);
2015 while (b[rp] == '\n')
2017 s = strstr(b+rp, "\n\n");
2020 while (b[eo] == '\n')
2029 memmove(m, m+a, p+1);
2034 m = qrealloc(m, a+p+128, &size);
2037 p += safe_read(fd, b+p, size-p-1);
2041 setvar_i(intvar[ERRNO], errno);
2050 c = b[so]; b[so] = '\0';
2054 c = b[eo]; b[eo] = '\0';
2055 setvar_s(intvar[RT], b+so);
2064 debug_printf_eval("returning from %s(): %d\n", __func__, r);
2069 static int fmt_num(char *b, int size, const char *format, double n, int int_as_int)
2073 const char *s = format;
2075 if (int_as_int && n == (long long)n) {
2076 r = snprintf(b, size, "%lld", (long long)n);
2078 do { c = *s; } while (c && *++s);
2079 if (strchr("diouxX", c)) {
2080 r = snprintf(b, size, format, (int)n);
2081 } else if (strchr("eEfgG", c)) {
2082 r = snprintf(b, size, format, n);
2084 syntax_error(EMSG_INV_FMT);
2090 /* formatted output into an allocated buffer, return ptr to buffer */
2091 static char *awk_printf(node *n)
2096 int i, j, incr, bsize;
2101 fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), v)));
2106 while (*f && (*f != '%' || *++f == '%'))
2108 while (*f && !isalpha(*f)) {
2110 syntax_error("%*x formats are not supported");
2114 incr = (f - s) + MAXVARFMT;
2115 b = qrealloc(b, incr + i, &bsize);
2121 arg = evaluate(nextarg(&n), v);
2124 if (c == 'c' || !c) {
2125 i += sprintf(b+i, s, is_numeric(arg) ?
2126 (char)getvar_i(arg) : *getvar_s(arg));
2127 } else if (c == 's') {
2129 b = qrealloc(b, incr+i+strlen(s1), &bsize);
2130 i += sprintf(b+i, s, s1);
2132 i += fmt_num(b+i, incr, s, getvar_i(arg), FALSE);
2136 /* if there was an error while sprintf, return value is negative */
2143 b = xrealloc(b, i + 1);
2148 /* Common substitution routine.
2149 * Replace (nm)'th substring of (src) that matches (rn) with (repl),
2150 * store result into (dest), return number of substitutions.
2151 * If nm = 0, replace all matches.
2152 * If src or dst is NULL, use $0.
2153 * If subexp != 0, enable subexpression matching (\1-\9).
2155 static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest, int subexp)
2159 int match_no, residx, replen, resbufsize;
2161 regmatch_t pmatch[10];
2162 regex_t sreg, *regex;
2168 regex = as_regex(rn, &sreg);
2169 sp = getvar_s(src ? src : intvar[F0]);
2170 replen = strlen(repl);
2171 while (regexec(regex, sp, 10, pmatch, regexec_flags) == 0) {
2172 int so = pmatch[0].rm_so;
2173 int eo = pmatch[0].rm_eo;
2175 //bb_error_msg("match %u: [%u,%u] '%s'%p", match_no+1, so, eo, sp,sp);
2176 resbuf = qrealloc(resbuf, residx + eo + replen, &resbufsize);
2177 memcpy(resbuf + residx, sp, eo);
2179 if (++match_no >= nm) {
2184 residx -= (eo - so);
2186 for (s = repl; *s; s++) {
2187 char c = resbuf[residx++] = *s;
2192 if (c == '&' || (subexp && c >= '0' && c <= '9')) {
2194 residx -= ((nbs + 3) >> 1);
2201 resbuf[residx++] = c;
2203 int n = pmatch[j].rm_eo - pmatch[j].rm_so;
2204 resbuf = qrealloc(resbuf, residx + replen + n, &resbufsize);
2205 memcpy(resbuf + residx, sp + pmatch[j].rm_so, n);
2213 regexec_flags = REG_NOTBOL;
2218 /* Empty match (e.g. "b*" will match anywhere).
2219 * Advance by one char. */
2221 //gsub(/\<b*/,"") on "abc" will reach this point, advance to "bc"
2222 //... and will erroneously match "b" even though it is NOT at the word start.
2223 //we need REG_NOTBOW but it does not exist...
2224 //TODO: if EXTRA_COMPAT=y, use GNU matching and re_search,
2225 //it should be able to do it correctly.
2226 /* Subtle: this is safe only because
2227 * qrealloc allocated at least one extra byte */
2228 resbuf[residx] = *sp;
2236 resbuf = qrealloc(resbuf, residx + strlen(sp), &resbufsize);
2237 strcpy(resbuf + residx, sp);
2239 //bb_error_msg("end sp:'%s'%p", sp,sp);
2240 setvar_p(dest ? dest : intvar[F0], resbuf);
2246 static NOINLINE int do_mktime(const char *ds)
2251 /*memset(&then, 0, sizeof(then)); - not needed */
2252 then.tm_isdst = -1; /* default is unknown */
2254 /* manpage of mktime says these fields are ints,
2255 * so we can sscanf stuff directly into them */
2256 count = sscanf(ds, "%u %u %u %u %u %u %d",
2257 &then.tm_year, &then.tm_mon, &then.tm_mday,
2258 &then.tm_hour, &then.tm_min, &then.tm_sec,
2262 || (unsigned)then.tm_mon < 1
2263 || (unsigned)then.tm_year < 1900
2269 then.tm_year -= 1900;
2271 return mktime(&then);
2274 static NOINLINE var *exec_builtin(node *op, var *res)
2276 #define tspl (G.exec_builtin__tspl)
2282 regmatch_t pmatch[2];
2291 isr = info = op->info;
2294 av[2] = av[3] = NULL;
2295 for (i = 0; i < 4 && op; i++) {
2296 an[i] = nextarg(&op);
2297 if (isr & 0x09000000)
2298 av[i] = evaluate(an[i], &tv[i]);
2299 if (isr & 0x08000000)
2300 as[i] = getvar_s(av[i]);
2305 if ((uint32_t)nargs < (info >> 30))
2306 syntax_error(EMSG_TOO_FEW_ARGS);
2312 if (ENABLE_FEATURE_AWK_LIBM)
2313 setvar_i(res, atan2(getvar_i(av[0]), getvar_i(av[1])));
2315 syntax_error(EMSG_NO_MATH);
2322 spl = (an[2]->info & OPCLSMASK) == OC_REGEXP ?
2323 an[2] : mk_splitter(getvar_s(evaluate(an[2], &tv[2])), &tspl);
2328 n = awk_split(as[0], spl, &s);
2330 clear_array(iamarray(av[1]));
2331 for (i = 1; i <= n; i++)
2332 setari_u(av[1], i, nextword(&s));
2342 i = getvar_i(av[1]) - 1;
2347 n = (nargs > 2) ? getvar_i(av[2]) : l-i;
2350 s = xstrndup(as[0]+i, n);
2355 /* Bitwise ops must assume that operands are unsigned. GNU Awk 3.1.5:
2356 * awk '{ print or(-1,1) }' gives "4.29497e+09", not "-2.xxxe+09" */
2358 setvar_i(res, getvar_i_int(av[0]) & getvar_i_int(av[1]));
2362 setvar_i(res, ~getvar_i_int(av[0]));
2366 setvar_i(res, getvar_i_int(av[0]) << getvar_i_int(av[1]));
2370 setvar_i(res, getvar_i_int(av[0]) | getvar_i_int(av[1]));
2374 setvar_i(res, getvar_i_int(av[0]) >> getvar_i_int(av[1]));
2378 setvar_i(res, getvar_i_int(av[0]) ^ getvar_i_int(av[1]));
2384 s1 = s = xstrdup(as[0]);
2386 //*s1 = (info == B_up) ? toupper(*s1) : tolower(*s1);
2387 if ((unsigned char)((*s1 | 0x20) - 'a') <= ('z' - 'a'))
2388 *s1 = (info == B_up) ? (*s1 & 0xdf) : (*s1 | 0x20);
2398 l = strlen(as[0]) - ll;
2399 if (ll > 0 && l >= 0) {
2401 char *s = strstr(as[0], as[1]);
2403 n = (s - as[0]) + 1;
2405 /* this piece of code is terribly slow and
2406 * really should be rewritten
2408 for (i = 0; i <= l; i++) {
2409 if (strncasecmp(as[0]+i, as[1], ll) == 0) {
2421 tt = getvar_i(av[1]);
2424 //s = (nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y";
2425 i = strftime(g_buf, MAXVARFMT,
2426 ((nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y"),
2429 setvar_s(res, g_buf);
2433 setvar_i(res, do_mktime(as[0]));
2437 re = as_regex(an[1], &sreg);
2438 n = regexec(re, as[0], 1, pmatch, 0);
2443 pmatch[0].rm_so = 0;
2444 pmatch[0].rm_eo = -1;
2446 setvar_i(newvar("RSTART"), pmatch[0].rm_so);
2447 setvar_i(newvar("RLENGTH"), pmatch[0].rm_eo - pmatch[0].rm_so);
2448 setvar_i(res, pmatch[0].rm_so);
2454 awk_sub(an[0], as[1], getvar_i(av[2]), av[3], res, TRUE);
2458 setvar_i(res, awk_sub(an[0], as[1], 0, av[2], av[2], FALSE));
2462 setvar_i(res, awk_sub(an[0], as[1], 1, av[2], av[2], FALSE));
2472 * Evaluate node - the heart of the program. Supplied with subtree
2473 * and place where to store result. returns ptr to result.
2475 #define XC(n) ((n) >> 8)
2477 static var *evaluate(node *op, var *res)
2479 /* This procedure is recursive so we should count every byte */
2480 #define fnargs (G.evaluate__fnargs)
2481 /* seed is initialized to 1 */
2482 #define seed (G.evaluate__seed)
2483 #define sreg (G.evaluate__sreg)
2488 return setvar_s(res, NULL);
2490 debug_printf_eval("entered %s()\n", __func__);
2498 } L = L; /* for compiler */
2509 opn = (opinfo & OPNMASK);
2510 g_lineno = op->lineno;
2512 debug_printf_eval("opinfo:%08x opn:%08x\n", opinfo, opn);
2514 /* execute inevitable things */
2515 if (opinfo & OF_RES1)
2516 L.v = evaluate(op1, v1);
2517 if (opinfo & OF_RES2)
2518 R.v = evaluate(op->r.n, v1+1);
2519 if (opinfo & OF_STR1) {
2520 L.s = getvar_s(L.v);
2521 debug_printf_eval("L.s:'%s'\n", L.s);
2523 if (opinfo & OF_STR2) {
2524 R.s = getvar_s(R.v);
2525 debug_printf_eval("R.s:'%s'\n", R.s);
2527 if (opinfo & OF_NUM1) {
2528 L_d = getvar_i(L.v);
2529 debug_printf_eval("L_d:%f\n", L_d);
2532 debug_printf_eval("switch(0x%x)\n", XC(opinfo & OPCLSMASK));
2533 switch (XC(opinfo & OPCLSMASK)) {
2535 /* -- iterative node type -- */
2539 if ((op1->info & OPCLSMASK) == OC_COMMA) {
2540 /* it's range pattern */
2541 if ((opinfo & OF_CHECKED) || ptest(op1->l.n)) {
2542 op->info |= OF_CHECKED;
2543 if (ptest(op1->r.n))
2544 op->info &= ~OF_CHECKED;
2550 op = ptest(op1) ? op->a.n : op->r.n;
2554 /* just evaluate an expression, also used as unconditional jump */
2558 /* branch, used in if-else and various loops */
2560 op = istrue(L.v) ? op->a.n : op->r.n;
2563 /* initialize for-in loop */
2564 case XC( OC_WALKINIT ):
2565 hashwalk_init(L.v, iamarray(R.v));
2568 /* get next array item */
2569 case XC( OC_WALKNEXT ):
2570 op = hashwalk_next(L.v) ? op->a.n : op->r.n;
2573 case XC( OC_PRINT ):
2574 case XC( OC_PRINTF ): {
2578 rstream *rsm = newfile(R.s);
2581 rsm->F = popen(R.s, "w");
2583 bb_perror_msg_and_die("popen");
2586 rsm->F = xfopen(R.s, opn=='w' ? "w" : "a");
2592 if ((opinfo & OPCLSMASK) == OC_PRINT) {
2594 fputs(getvar_s(intvar[F0]), F);
2597 var *v = evaluate(nextarg(&op1), v1);
2598 if (v->type & VF_NUMBER) {
2599 fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[OFMT]),
2603 fputs(getvar_s(v), F);
2607 fputs(getvar_s(intvar[OFS]), F);
2610 fputs(getvar_s(intvar[ORS]), F);
2612 } else { /* OC_PRINTF */
2613 char *s = awk_printf(op1);
2621 case XC( OC_DELETE ): {
2622 uint32_t info = op1->info & OPCLSMASK;
2625 if (info == OC_VAR) {
2627 } else if (info == OC_FNARG) {
2628 v = &fnargs[op1->l.aidx];
2630 syntax_error(EMSG_NOT_ARRAY);
2636 s = getvar_s(evaluate(op1->r.n, v1));
2637 hash_remove(iamarray(v), s);
2639 clear_array(iamarray(v));
2644 case XC( OC_NEWSOURCE ):
2645 g_progname = op->l.new_progname;
2648 case XC( OC_RETURN ):
2652 case XC( OC_NEXTFILE ):
2663 /* -- recursive node type -- */
2667 if (L.v == intvar[NF])
2671 case XC( OC_FNARG ):
2672 L.v = &fnargs[op->l.aidx];
2674 res = op->r.n ? findvar(iamarray(L.v), R.s) : L.v;
2678 setvar_i(res, hash_search(iamarray(R.v), L.s) ? 1 : 0);
2681 case XC( OC_REGEXP ):
2683 L.s = getvar_s(intvar[F0]);
2686 case XC( OC_MATCH ):
2690 regex_t *re = as_regex(op1, &sreg);
2691 int i = regexec(re, L.s, 0, NULL, 0);
2694 setvar_i(res, (i == 0) ^ (opn == '!'));
2699 debug_printf_eval("MOVE\n");
2700 /* if source is a temporary string, jusk relink it to dest */
2701 //Disabled: if R.v is numeric but happens to have cached R.v->string,
2702 //then L.v ends up being a string, which is wrong
2703 // if (R.v == v1+1 && R.v->string) {
2704 // res = setvar_p(L.v, R.v->string);
2705 // R.v->string = NULL;
2707 res = copyvar(L.v, R.v);
2711 case XC( OC_TERNARY ):
2712 if ((op->r.n->info & OPCLSMASK) != OC_COLON)
2713 syntax_error(EMSG_POSSIBLE_ERROR);
2714 res = evaluate(istrue(L.v) ? op->r.n->l.n : op->r.n->r.n, res);
2717 case XC( OC_FUNC ): {
2719 const char *sv_progname;
2721 /* The body might be empty, still has to eval the args */
2722 if (!op->r.n->info && !op->r.f->body.first)
2723 syntax_error(EMSG_UNDEF_FUNC);
2725 vbeg = v = nvalloc(op->r.f->nargs + 1);
2727 var *arg = evaluate(nextarg(&op1), v1);
2729 v->type |= VF_CHILD;
2731 if (++v - vbeg >= op->r.f->nargs)
2737 sv_progname = g_progname;
2739 res = evaluate(op->r.f->body.first, res);
2741 g_progname = sv_progname;
2748 case XC( OC_GETLINE ):
2749 case XC( OC_PGETLINE ): {
2756 if ((opinfo & OPCLSMASK) == OC_PGETLINE) {
2757 rsm->F = popen(L.s, "r");
2758 rsm->is_pipe = TRUE;
2760 rsm->F = fopen_for_read(L.s); /* not xfopen! */
2765 iF = next_input_file();
2769 if (!rsm || !rsm->F) {
2770 setvar_i(intvar[ERRNO], errno);
2778 i = awk_getline(rsm, R.v);
2779 if (i > 0 && !op1) {
2780 incvar(intvar[FNR]);
2787 /* simple builtins */
2788 case XC( OC_FBLTIN ): {
2789 double R_d = R_d; /* for compiler */
2793 R_d = (long long)L_d;
2797 R_d = (double)rand() / (double)RAND_MAX;
2801 if (ENABLE_FEATURE_AWK_LIBM) {
2807 if (ENABLE_FEATURE_AWK_LIBM) {
2813 if (ENABLE_FEATURE_AWK_LIBM) {
2819 if (ENABLE_FEATURE_AWK_LIBM) {
2825 if (ENABLE_FEATURE_AWK_LIBM) {
2830 syntax_error(EMSG_NO_MATH);
2835 seed = op1 ? (unsigned)L_d : (unsigned)time(NULL);
2844 debug_printf_eval("length: L.s:'%s'\n", L.s);
2846 L.s = getvar_s(intvar[F0]);
2847 debug_printf_eval("length: L.s='%s'\n", L.s);
2849 else if (L.v->type & VF_ARRAY) {
2850 R_d = L.v->x.array->nel;
2851 debug_printf_eval("length: array_len:%d\n", L.v->x.array->nel);
2859 R_d = (ENABLE_FEATURE_ALLOW_EXEC && L.s && *L.s)
2860 ? (system(L.s) >> 8) : 0;
2866 } else if (L.s && *L.s) {
2867 rstream *rsm = newfile(L.s);
2877 rsm = (rstream *)hash_search(fdhash, L.s);
2878 debug_printf_eval("OC_FBLTIN F_cl rsm:%p\n", rsm);
2880 debug_printf_eval("OC_FBLTIN F_cl "
2881 "rsm->is_pipe:%d, ->F:%p\n",
2882 rsm->is_pipe, rsm->F);
2883 /* Can be NULL if open failed. Example:
2884 * getline line <"doesnt_exist";
2885 * close("doesnt_exist"); <--- here rsm->F is NULL
2888 err = rsm->is_pipe ? pclose(rsm->F) : fclose(rsm->F);
2890 hash_remove(fdhash, L.s);
2893 setvar_i(intvar[ERRNO], errno);
2902 case XC( OC_BUILTIN ):
2903 res = exec_builtin(op, res);
2906 case XC( OC_SPRINTF ):
2907 setvar_p(res, awk_printf(op1));
2910 case XC( OC_UNARY ): {
2913 Ld = R_d = getvar_i(R.v);
2940 case XC( OC_FIELD ): {
2941 int i = (int)getvar_i(R.v);
2948 res = &Fields[i - 1];
2953 /* concatenation (" ") and index joining (",") */
2954 case XC( OC_CONCAT ):
2955 case XC( OC_COMMA ): {
2956 const char *sep = "";
2957 if ((opinfo & OPCLSMASK) == OC_COMMA)
2958 sep = getvar_s(intvar[SUBSEP]);
2959 setvar_p(res, xasprintf("%s%s%s", L.s, sep, R.s));
2964 setvar_i(res, istrue(L.v) ? ptest(op->r.n) : 0);
2968 setvar_i(res, istrue(L.v) ? 1 : ptest(op->r.n));
2971 case XC( OC_BINARY ):
2972 case XC( OC_REPLACE ): {
2973 double R_d = getvar_i(R.v);
2974 debug_printf_eval("BINARY/REPLACE: R_d:%f opn:%c\n", R_d, opn);
2987 syntax_error(EMSG_DIV_BY_ZERO);
2991 if (ENABLE_FEATURE_AWK_LIBM)
2992 L_d = pow(L_d, R_d);
2994 syntax_error(EMSG_NO_MATH);
2998 syntax_error(EMSG_DIV_BY_ZERO);
2999 L_d -= (long long)(L_d / R_d) * R_d;
3002 debug_printf_eval("BINARY/REPLACE result:%f\n", L_d);
3003 res = setvar_i(((opinfo & OPCLSMASK) == OC_BINARY) ? res : L.v, L_d);
3007 case XC( OC_COMPARE ): {
3008 int i = i; /* for compiler */
3011 if (is_numeric(L.v) && is_numeric(R.v)) {
3012 Ld = getvar_i(L.v) - getvar_i(R.v);
3014 const char *l = getvar_s(L.v);
3015 const char *r = getvar_s(R.v);
3016 Ld = icase ? strcasecmp(l, r) : strcmp(l, r);
3018 switch (opn & 0xfe) {
3029 setvar_i(res, (i == 0) ^ (opn & 1));
3034 syntax_error(EMSG_POSSIBLE_ERROR);
3036 if ((opinfo & OPCLSMASK) <= SHIFT_TIL_THIS)
3038 if ((opinfo & OPCLSMASK) >= RECUR_FROM_THIS)
3045 debug_printf_eval("returning from %s(): %p\n", __func__, res);
3053 /* -------- main & co. -------- */
3055 static int awk_exit(int r)
3066 evaluate(endseq.first, &tv);
3069 /* waiting for children */
3070 for (i = 0; i < fdhash->csize; i++) {
3071 hi = fdhash->items[i];
3073 if (hi->data.rs.F && hi->data.rs.is_pipe)
3074 pclose(hi->data.rs.F);
3082 /* if expr looks like "var=value", perform assignment and return 1,
3083 * otherwise return 0 */
3084 static int is_assignment(const char *expr)
3088 if (!isalnum_(*expr) || (val = strchr(expr, '=')) == NULL) {
3092 exprc = xstrdup(expr);
3093 val = exprc + (val - expr);
3096 unescape_string_in_place(val);
3097 setvar_u(newvar(exprc), val);
3102 /* switch to next input file */
3103 static rstream *next_input_file(void)
3105 #define rsm (G.next_input_file__rsm)
3106 #define files_happen (G.next_input_file__files_happen)
3109 const char *fname, *ind;
3114 rsm.pos = rsm.adv = 0;
3117 if (getvar_i(intvar[ARGIND])+1 >= getvar_i(intvar[ARGC])) {
3124 ind = getvar_s(incvar(intvar[ARGIND]));
3125 fname = getvar_s(findvar(iamarray(intvar[ARGV]), ind));
3126 if (fname && *fname && !is_assignment(fname)) {
3127 F = xfopen_stdin(fname);
3132 files_happen = TRUE;
3133 setvar_s(intvar[FILENAME], fname);
3140 int awk_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3141 int awk_main(int argc, char **argv)
3145 llist_t *list_v = NULL;
3146 llist_t *list_f = NULL;
3147 #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
3148 llist_t *list_e = NULL;
3154 char *vnames = (char *)vNames; /* cheat */
3155 char *vvalues = (char *)vValues;
3159 /* Undo busybox.c, or else strtod may eat ','! This breaks parsing:
3160 * $1,$2 == '$1,' '$2', NOT '$1' ',' '$2' */
3161 if (ENABLE_LOCALE_SUPPORT)
3162 setlocale(LC_NUMERIC, "C");
3166 /* allocate global buffer */
3167 g_buf = xmalloc(MAXVARFMT + 1);
3169 vhash = hash_init();
3170 ahash = hash_init();
3171 fdhash = hash_init();
3172 fnhash = hash_init();
3174 /* initialize variables */
3175 for (i = 0; *vnames; i++) {
3176 intvar[i] = v = newvar(nextword(&vnames));
3177 if (*vvalues != '\377')
3178 setvar_s(v, nextword(&vvalues));
3182 if (*vnames == '*') {
3183 v->type |= VF_SPECIAL;
3188 handle_special(intvar[FS]);
3189 handle_special(intvar[RS]);
3191 newfile("/dev/stdin")->F = stdin;
3192 newfile("/dev/stdout")->F = stdout;
3193 newfile("/dev/stderr")->F = stderr;
3195 /* Huh, people report that sometimes environ is NULL. Oh well. */
3196 if (environ) for (envp = environ; *envp; envp++) {
3197 /* environ is writable, thus we don't strdup it needlessly */
3199 char *s1 = strchr(s, '=');
3202 /* Both findvar and setvar_u take const char*
3203 * as 2nd arg -> environment is not trashed */
3204 setvar_u(findvar(iamarray(intvar[ENVIRON]), s), s1 + 1);
3208 opt = getopt32(argv, OPTSTR_AWK, &opt_F, &list_v, &list_f, IF_FEATURE_AWK_GNU_EXTENSIONS(&list_e,) NULL);
3212 bb_error_msg("warning: option -W is ignored");
3214 unescape_string_in_place(opt_F);
3215 setvar_s(intvar[FS], opt_F);
3218 if (!is_assignment(llist_pop(&list_v)))
3225 g_progname = llist_pop(&list_f);
3226 from_file = xfopen_stdin(g_progname);
3227 /* one byte is reserved for some trick in next_token */
3228 for (i = j = 1; j > 0; i += j) {
3229 s = xrealloc(s, i + 4096);
3230 j = fread(s + i, 1, 4094, from_file);
3234 parse_program(s + 1);
3237 g_progname = "cmd. line";
3238 #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
3240 parse_program(llist_pop(&list_e));
3243 if (!(opt & (OPT_f | OPT_e))) {
3246 parse_program(*argv++);
3250 /* fill in ARGV array */
3251 setvar_i(intvar[ARGC], argc + 1);
3252 setari_u(intvar[ARGV], 0, "awk");
3255 setari_u(intvar[ARGV], ++i, *argv++);
3257 evaluate(beginseq.first, &tv);
3258 if (!mainseq.first && !endseq.first)
3259 awk_exit(EXIT_SUCCESS);
3261 /* input file could already be opened in BEGIN block */
3263 iF = next_input_file();
3265 /* passing through input files */
3268 setvar_i(intvar[FNR], 0);
3270 while ((i = awk_getline(iF, intvar[F0])) > 0) {
3273 incvar(intvar[FNR]);
3274 evaluate(mainseq.first, &tv);
3281 syntax_error(strerror(errno));
3283 iF = next_input_file();
3286 awk_exit(EXIT_SUCCESS);