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.
14 //config: Awk is used as a pattern scanning and processing language. This is
15 //config: the BusyBox implementation of that programming language.
17 //config:config FEATURE_AWK_LIBM
18 //config: bool "Enable math functions (requires libm)"
20 //config: depends on AWK
22 //config: Enable math functions of the Awk programming language.
23 //config: NOTE: This will require libm to be present for linking.
25 //config:config FEATURE_AWK_GNU_EXTENSIONS
26 //config: bool "Enable a few GNU extensions"
28 //config: depends on AWK
30 //config: Enable a few features from gawk:
31 //config: * command line option -e AWK_PROGRAM
32 //config: * simultaneous use of -f and -e on the command line.
33 //config: This enables the use of awk library files.
34 //config: Ex: awk -f mylib.awk -e '{print myfunction($1);}' ...
36 //applet:IF_AWK(APPLET_NOEXEC(awk, awk, BB_DIR_USR_BIN, BB_SUID_DROP, awk))
38 //kbuild:lib-$(CONFIG_AWK) += awk.o
40 //usage:#define awk_trivial_usage
41 //usage: "[OPTIONS] [AWK_PROGRAM] [FILE]..."
42 //usage:#define awk_full_usage "\n\n"
43 //usage: " -v VAR=VAL Set variable"
44 //usage: "\n -F SEP Use SEP as field separator"
45 //usage: "\n -f FILE Read program from FILE"
46 //usage: IF_FEATURE_AWK_GNU_EXTENSIONS(
47 //usage: "\n -e AWK_PROGRAM"
54 /* This is a NOEXEC applet. Be very careful! */
57 /* If you comment out one of these below, it will be #defined later
58 * to perform debug printfs to stderr: */
59 #define debug_printf_walker(...) do {} while (0)
60 #define debug_printf_eval(...) do {} while (0)
61 #define debug_printf_parse(...) do {} while (0)
63 #ifndef debug_printf_walker
64 # define debug_printf_walker(...) (fprintf(stderr, __VA_ARGS__))
66 #ifndef debug_printf_eval
67 # define debug_printf_eval(...) (fprintf(stderr, __VA_ARGS__))
69 #ifndef debug_printf_parse
70 # define debug_printf_parse(...) (fprintf(stderr, __VA_ARGS__))
76 IF_FEATURE_AWK_GNU_EXTENSIONS("e:*") \
79 OPTBIT_F, /* define field separator */
80 OPTBIT_v, /* define variable */
81 OPTBIT_f, /* pull in awk program from file */
82 IF_FEATURE_AWK_GNU_EXTENSIONS(OPTBIT_e,) /* -e AWK_PROGRAM */
83 OPTBIT_W, /* -W ignored */
84 OPT_F = 1 << OPTBIT_F,
85 OPT_v = 1 << OPTBIT_v,
86 OPT_f = 1 << OPTBIT_f,
87 OPT_e = IF_FEATURE_AWK_GNU_EXTENSIONS((1 << OPTBIT_e)) + 0,
95 #define VF_NUMBER 0x0001 /* 1 = primary type is number */
96 #define VF_ARRAY 0x0002 /* 1 = it's an array */
98 #define VF_CACHED 0x0100 /* 1 = num/str value has cached str/num eq */
99 #define VF_USER 0x0200 /* 1 = user input (may be numeric string) */
100 #define VF_SPECIAL 0x0400 /* 1 = requires extra handling when changed */
101 #define VF_WALK 0x0800 /* 1 = variable has alloc'd x.walker list */
102 #define VF_FSTR 0x1000 /* 1 = var::string points to fstring buffer */
103 #define VF_CHILD 0x2000 /* 1 = function arg; x.parent points to source */
104 #define VF_DIRTY 0x4000 /* 1 = variable was set explicitly */
106 /* these flags are static, don't change them when value is changed */
107 #define VF_DONTTOUCH (VF_ARRAY | VF_SPECIAL | VF_WALK | VF_CHILD | VF_DIRTY)
109 typedef struct walker_list {
112 struct walker_list *prev;
117 typedef struct var_s {
118 unsigned type; /* flags */
122 int aidx; /* func arg idx (for compilation stage) */
123 struct xhash_s *array; /* array ptr */
124 struct var_s *parent; /* for func args, ptr to actual parameter */
125 walker_list *walker; /* list of array elements (for..in) */
129 /* Node chain (pattern-action chain, BEGIN, END, function bodies) */
130 typedef struct chain_s {
131 struct node_s *first;
133 const char *programname;
137 typedef struct func_s {
143 typedef struct rstream_s {
152 typedef struct hash_item_s {
154 struct var_s v; /* variable/array hash */
155 struct rstream_s rs; /* redirect streams hash */
156 struct func_s f; /* functions hash */
158 struct hash_item_s *next; /* next in chain */
159 char name[1]; /* really it's longer */
162 typedef struct xhash_s {
163 unsigned nel; /* num of elements */
164 unsigned csize; /* current hash size */
165 unsigned nprime; /* next hash size in PRIMES[] */
166 unsigned glen; /* summary length of item names */
167 struct hash_item_s **items;
171 typedef struct node_s {
191 /* Block of temporary variables */
192 typedef struct nvblock_s {
195 struct nvblock_s *prev;
196 struct nvblock_s *next;
200 typedef struct tsplitter_s {
205 /* simple token classes */
206 /* Order and hex values are very important!!! See next_token() */
207 #define TC_SEQSTART (1 << 0) /* ( */
208 #define TC_SEQTERM (1 << 1) /* ) */
209 #define TC_REGEXP (1 << 2) /* /.../ */
210 #define TC_OUTRDR (1 << 3) /* | > >> */
211 #define TC_UOPPOST (1 << 4) /* unary postfix operator */
212 #define TC_UOPPRE1 (1 << 5) /* unary prefix operator */
213 #define TC_BINOPX (1 << 6) /* two-opnd operator */
214 #define TC_IN (1 << 7)
215 #define TC_COMMA (1 << 8)
216 #define TC_PIPE (1 << 9) /* input redirection pipe */
217 #define TC_UOPPRE2 (1 << 10) /* unary prefix operator */
218 #define TC_ARRTERM (1 << 11) /* ] */
219 #define TC_GRPSTART (1 << 12) /* { */
220 #define TC_GRPTERM (1 << 13) /* } */
221 #define TC_SEMICOL (1 << 14)
222 #define TC_NEWLINE (1 << 15)
223 #define TC_STATX (1 << 16) /* ctl statement (for, next...) */
224 #define TC_WHILE (1 << 17)
225 #define TC_ELSE (1 << 18)
226 #define TC_BUILTIN (1 << 19)
227 /* This costs ~50 bytes of code.
228 * A separate class to support deprecated "length" form. If we don't need that
229 * (i.e. if we demand that only "length()" with () is valid), then TC_LENGTH
230 * can be merged with TC_BUILTIN:
232 #define TC_LENGTH (1 << 20)
233 #define TC_GETLINE (1 << 21)
234 #define TC_FUNCDECL (1 << 22) /* `function' `func' */
235 #define TC_BEGIN (1 << 23)
236 #define TC_END (1 << 24)
237 #define TC_EOF (1 << 25)
238 #define TC_VARIABLE (1 << 26)
239 #define TC_ARRAY (1 << 27)
240 #define TC_FUNCTION (1 << 28)
241 #define TC_STRING (1 << 29)
242 #define TC_NUMBER (1 << 30)
244 #define TC_UOPPRE (TC_UOPPRE1 | TC_UOPPRE2)
246 /* combined token classes */
247 #define TC_BINOP (TC_BINOPX | TC_COMMA | TC_PIPE | TC_IN)
248 //#define TC_UNARYOP (TC_UOPPRE | TC_UOPPOST)
249 #define TC_OPERAND (TC_VARIABLE | TC_ARRAY | TC_FUNCTION \
250 | TC_BUILTIN | TC_LENGTH | TC_GETLINE \
251 | TC_SEQSTART | TC_STRING | TC_NUMBER)
253 #define TC_STATEMNT (TC_STATX | TC_WHILE)
254 #define TC_OPTERM (TC_SEMICOL | TC_NEWLINE)
256 /* word tokens, cannot mean something else if not expected */
257 #define TC_WORD (TC_IN | TC_STATEMNT | TC_ELSE \
258 | TC_BUILTIN | TC_LENGTH | TC_GETLINE \
259 | TC_FUNCDECL | TC_BEGIN | TC_END)
261 /* discard newlines after these */
262 #define TC_NOTERM (TC_COMMA | TC_GRPSTART | TC_GRPTERM \
263 | TC_BINOP | TC_OPTERM)
265 /* what can expression begin with */
266 #define TC_OPSEQ (TC_OPERAND | TC_UOPPRE | TC_REGEXP)
267 /* what can group begin with */
268 #define TC_GRPSEQ (TC_OPSEQ | TC_OPTERM | TC_STATEMNT | TC_GRPSTART)
270 /* if previous token class is CONCAT1 and next is CONCAT2, concatenation */
271 /* operator is inserted between them */
272 #define TC_CONCAT1 (TC_VARIABLE | TC_ARRTERM | TC_SEQTERM \
273 | TC_STRING | TC_NUMBER | TC_UOPPOST)
274 #define TC_CONCAT2 (TC_OPERAND | TC_UOPPRE)
276 #define OF_RES1 0x010000
277 #define OF_RES2 0x020000
278 #define OF_STR1 0x040000
279 #define OF_STR2 0x080000
280 #define OF_NUM1 0x100000
281 #define OF_CHECKED 0x200000
283 /* combined operator flags */
286 #define xS (OF_RES2 | OF_STR2)
288 #define VV (OF_RES1 | OF_RES2)
289 #define Nx (OF_RES1 | OF_NUM1)
290 #define NV (OF_RES1 | OF_NUM1 | OF_RES2)
291 #define Sx (OF_RES1 | OF_STR1)
292 #define SV (OF_RES1 | OF_STR1 | OF_RES2)
293 #define SS (OF_RES1 | OF_STR1 | OF_RES2 | OF_STR2)
295 #define OPCLSMASK 0xFF00
296 #define OPNMASK 0x007F
298 /* operator priority is a highest byte (even: r->l, odd: l->r grouping)
299 * For builtins it has different meaning: n n s3 s2 s1 v3 v2 v1,
300 * n - min. number of args, vN - resolve Nth arg to var, sN - resolve to string
305 #define P(x) (x << 24)
306 #define PRIMASK 0x7F000000
307 #define PRIMASK2 0x7E000000
309 /* Operation classes */
311 #define SHIFT_TIL_THIS 0x0600
312 #define RECUR_FROM_THIS 0x1000
315 OC_DELETE = 0x0100, OC_EXEC = 0x0200, OC_NEWSOURCE = 0x0300,
316 OC_PRINT = 0x0400, OC_PRINTF = 0x0500, OC_WALKINIT = 0x0600,
318 OC_BR = 0x0700, OC_BREAK = 0x0800, OC_CONTINUE = 0x0900,
319 OC_EXIT = 0x0a00, OC_NEXT = 0x0b00, OC_NEXTFILE = 0x0c00,
320 OC_TEST = 0x0d00, OC_WALKNEXT = 0x0e00,
322 OC_BINARY = 0x1000, OC_BUILTIN = 0x1100, OC_COLON = 0x1200,
323 OC_COMMA = 0x1300, OC_COMPARE = 0x1400, OC_CONCAT = 0x1500,
324 OC_FBLTIN = 0x1600, OC_FIELD = 0x1700, OC_FNARG = 0x1800,
325 OC_FUNC = 0x1900, OC_GETLINE = 0x1a00, OC_IN = 0x1b00,
326 OC_LAND = 0x1c00, OC_LOR = 0x1d00, OC_MATCH = 0x1e00,
327 OC_MOVE = 0x1f00, OC_PGETLINE = 0x2000, OC_REGEXP = 0x2100,
328 OC_REPLACE = 0x2200, OC_RETURN = 0x2300, OC_SPRINTF = 0x2400,
329 OC_TERNARY = 0x2500, OC_UNARY = 0x2600, OC_VAR = 0x2700,
332 ST_IF = 0x3000, ST_DO = 0x3100, ST_FOR = 0x3200,
336 /* simple builtins */
338 F_in, F_rn, F_co, F_ex, F_lg, F_si, F_sq, F_sr,
339 F_ti, F_le, F_sy, F_ff, F_cl
344 B_a2, B_ix, B_ma, B_sp, B_ss, B_ti, B_mt, B_lo, B_up,
346 B_an, B_co, B_ls, B_or, B_rs, B_xo,
349 /* tokens and their corresponding info values */
351 #define NTC "\377" /* switch to next token class (tc<<1) */
354 static const char tokenlist[] ALIGN1 =
355 "\1(" NTC /* TC_SEQSTART */
356 "\1)" NTC /* TC_SEQTERM */
357 "\1/" NTC /* TC_REGEXP */
358 "\2>>" "\1>" "\1|" NTC /* TC_OUTRDR */
359 "\2++" "\2--" NTC /* TC_UOPPOST */
360 "\2++" "\2--" "\1$" NTC /* TC_UOPPRE1 */
361 "\2==" "\1=" "\2+=" "\2-=" /* TC_BINOPX */
362 "\2*=" "\2/=" "\2%=" "\2^="
363 "\1+" "\1-" "\3**=" "\2**"
364 "\1/" "\1%" "\1^" "\1*"
365 "\2!=" "\2>=" "\2<=" "\1>"
366 "\1<" "\2!~" "\1~" "\2&&"
367 "\2||" "\1?" "\1:" NTC
368 "\2in" NTC /* TC_IN */
369 "\1," NTC /* TC_COMMA */
370 "\1|" NTC /* TC_PIPE */
371 "\1+" "\1-" "\1!" NTC /* TC_UOPPRE2 */
372 "\1]" NTC /* TC_ARRTERM */
373 "\1{" NTC /* TC_GRPSTART */
374 "\1}" NTC /* TC_GRPTERM */
375 "\1;" NTC /* TC_SEMICOL */
376 "\1\n" NTC /* TC_NEWLINE */
377 "\2if" "\2do" "\3for" "\5break" /* TC_STATX */
378 "\10continue" "\6delete" "\5print"
379 "\6printf" "\4next" "\10nextfile"
380 "\6return" "\4exit" NTC
381 "\5while" NTC /* TC_WHILE */
382 "\4else" NTC /* TC_ELSE */
383 "\3and" "\5compl" "\6lshift" "\2or" /* TC_BUILTIN */
385 "\5close" "\6system" "\6fflush" "\5atan2"
386 "\3cos" "\3exp" "\3int" "\3log"
387 "\4rand" "\3sin" "\4sqrt" "\5srand"
388 "\6gensub" "\4gsub" "\5index" /* "\6length" was here */
389 "\5match" "\5split" "\7sprintf" "\3sub"
390 "\6substr" "\7systime" "\10strftime" "\6mktime"
391 "\7tolower" "\7toupper" NTC
392 "\6length" NTC /* TC_LENGTH */
393 "\7getline" NTC /* TC_GETLINE */
394 "\4func" "\10function" NTC /* TC_FUNCDECL */
395 "\5BEGIN" NTC /* TC_BEGIN */
397 /* compiler adds trailing "\0" */
400 #define OC_B OC_BUILTIN
402 static const uint32_t tokeninfo[] = {
406 xS|'a', xS|'w', xS|'|',
407 OC_UNARY|xV|P(9)|'p', OC_UNARY|xV|P(9)|'m',
408 OC_UNARY|xV|P(9)|'P', OC_UNARY|xV|P(9)|'M', OC_FIELD|xV|P(5),
409 OC_COMPARE|VV|P(39)|5, OC_MOVE|VV|P(74), OC_REPLACE|NV|P(74)|'+', OC_REPLACE|NV|P(74)|'-',
410 OC_REPLACE|NV|P(74)|'*', OC_REPLACE|NV|P(74)|'/', OC_REPLACE|NV|P(74)|'%', OC_REPLACE|NV|P(74)|'&',
411 OC_BINARY|NV|P(29)|'+', OC_BINARY|NV|P(29)|'-', OC_REPLACE|NV|P(74)|'&', OC_BINARY|NV|P(15)|'&',
412 OC_BINARY|NV|P(25)|'/', OC_BINARY|NV|P(25)|'%', OC_BINARY|NV|P(15)|'&', OC_BINARY|NV|P(25)|'*',
413 OC_COMPARE|VV|P(39)|4, OC_COMPARE|VV|P(39)|3, OC_COMPARE|VV|P(39)|0, OC_COMPARE|VV|P(39)|1,
414 OC_COMPARE|VV|P(39)|2, OC_MATCH|Sx|P(45)|'!', OC_MATCH|Sx|P(45)|'~', OC_LAND|Vx|P(55),
415 OC_LOR|Vx|P(59), OC_TERNARY|Vx|P(64)|'?', OC_COLON|xx|P(67)|':',
416 OC_IN|SV|P(49), /* TC_IN */
418 OC_PGETLINE|SV|P(37),
419 OC_UNARY|xV|P(19)|'+', OC_UNARY|xV|P(19)|'-', OC_UNARY|xV|P(19)|'!',
425 ST_IF, ST_DO, ST_FOR, OC_BREAK,
426 OC_CONTINUE, OC_DELETE|Vx, OC_PRINT,
427 OC_PRINTF, OC_NEXT, OC_NEXTFILE,
428 OC_RETURN|Vx, OC_EXIT|Nx,
431 OC_B|B_an|P(0x83), OC_B|B_co|P(0x41), OC_B|B_ls|P(0x83), OC_B|B_or|P(0x83),
432 OC_B|B_rs|P(0x83), OC_B|B_xo|P(0x83),
433 OC_FBLTIN|Sx|F_cl, OC_FBLTIN|Sx|F_sy, OC_FBLTIN|Sx|F_ff, OC_B|B_a2|P(0x83),
434 OC_FBLTIN|Nx|F_co, OC_FBLTIN|Nx|F_ex, OC_FBLTIN|Nx|F_in, OC_FBLTIN|Nx|F_lg,
435 OC_FBLTIN|F_rn, OC_FBLTIN|Nx|F_si, OC_FBLTIN|Nx|F_sq, OC_FBLTIN|Nx|F_sr,
436 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 */
437 OC_B|B_ma|P(0x89), OC_B|B_sp|P(0x8b), OC_SPRINTF, OC_B|B_su|P(0xb6),
438 OC_B|B_ss|P(0x8f), OC_FBLTIN|F_ti, OC_B|B_ti|P(0x0b), OC_B|B_mt|P(0x0b),
439 OC_B|B_lo|P(0x49), OC_B|B_up|P(0x49),
440 OC_FBLTIN|Sx|F_le, /* TC_LENGTH */
447 /* internal variable names and their initial values */
448 /* asterisk marks SPECIAL vars; $ is just no-named Field0 */
450 CONVFMT, OFMT, FS, OFS,
451 ORS, RS, RT, FILENAME,
452 SUBSEP, F0, ARGIND, ARGC,
453 ARGV, ERRNO, FNR, NR,
454 NF, IGNORECASE, ENVIRON, NUM_INTERNAL_VARS
457 static const char vNames[] ALIGN1 =
458 "CONVFMT\0" "OFMT\0" "FS\0*" "OFS\0"
459 "ORS\0" "RS\0*" "RT\0" "FILENAME\0"
460 "SUBSEP\0" "$\0*" "ARGIND\0" "ARGC\0"
461 "ARGV\0" "ERRNO\0" "FNR\0" "NR\0"
462 "NF\0*" "IGNORECASE\0*" "ENVIRON\0" "\0";
464 static const char vValues[] ALIGN1 =
465 "%.6g\0" "%.6g\0" " \0" " \0"
466 "\n\0" "\n\0" "\0" "\0"
467 "\034\0" "\0" "\377";
469 /* hash size may grow to these values */
470 #define FIRST_PRIME 61
471 static const uint16_t PRIMES[] ALIGN2 = { 251, 1021, 4093, 16381, 65521 };
474 /* Globals. Split in two parts so that first one is addressed
475 * with (mostly short) negative offsets.
476 * NB: it's unsafe to put members of type "double"
477 * into globals2 (gcc may fail to align them).
481 chain beginseq, mainseq, endseq;
483 node *break_ptr, *continue_ptr;
485 xhash *vhash, *ahash, *fdhash, *fnhash;
486 const char *g_progname;
489 int maxfields; /* used in fsrealloc() only */
498 smallint is_f0_split;
502 uint32_t t_info; /* often used */
507 var *intvar[NUM_INTERNAL_VARS]; /* often used */
509 /* former statics from various functions */
510 char *split_f0__fstrings;
512 uint32_t next_token__save_tclass;
513 uint32_t next_token__save_info;
514 uint32_t next_token__ltclass;
515 smallint next_token__concat_inserted;
517 smallint next_input_file__files_happen;
518 rstream next_input_file__rsm;
520 var *evaluate__fnargs;
521 unsigned evaluate__seed;
522 regex_t evaluate__sreg;
526 tsplitter exec_builtin__tspl;
528 /* biggest and least used members go last */
529 tsplitter fsplitter, rsplitter;
531 #define G1 (ptr_to_globals[-1])
532 #define G (*(struct globals2 *)ptr_to_globals)
533 /* For debug. nm --size-sort awk.o | grep -vi ' [tr] ' */
534 /*char G1size[sizeof(G1)]; - 0x74 */
535 /*char Gsize[sizeof(G)]; - 0x1c4 */
536 /* Trying to keep most of members accessible with short offsets: */
537 /*char Gofs_seed[offsetof(struct globals2, evaluate__seed)]; - 0x90 */
538 #define t_double (G1.t_double )
539 #define beginseq (G1.beginseq )
540 #define mainseq (G1.mainseq )
541 #define endseq (G1.endseq )
542 #define seq (G1.seq )
543 #define break_ptr (G1.break_ptr )
544 #define continue_ptr (G1.continue_ptr)
546 #define vhash (G1.vhash )
547 #define ahash (G1.ahash )
548 #define fdhash (G1.fdhash )
549 #define fnhash (G1.fnhash )
550 #define g_progname (G1.g_progname )
551 #define g_lineno (G1.g_lineno )
552 #define nfields (G1.nfields )
553 #define maxfields (G1.maxfields )
554 #define Fields (G1.Fields )
555 #define g_cb (G1.g_cb )
556 #define g_pos (G1.g_pos )
557 #define g_buf (G1.g_buf )
558 #define icase (G1.icase )
559 #define exiting (G1.exiting )
560 #define nextrec (G1.nextrec )
561 #define nextfile (G1.nextfile )
562 #define is_f0_split (G1.is_f0_split )
563 #define t_rollback (G1.t_rollback )
564 #define t_info (G.t_info )
565 #define t_tclass (G.t_tclass )
566 #define t_string (G.t_string )
567 #define t_lineno (G.t_lineno )
568 #define intvar (G.intvar )
569 #define fsplitter (G.fsplitter )
570 #define rsplitter (G.rsplitter )
571 #define INIT_G() do { \
572 SET_PTR_TO_GLOBALS((char*)xzalloc(sizeof(G1)+sizeof(G)) + sizeof(G1)); \
573 G.next_token__ltclass = TC_OPTERM; \
574 G.evaluate__seed = 1; \
578 /* function prototypes */
579 static void handle_special(var *);
580 static node *parse_expr(uint32_t);
581 static void chain_group(void);
582 static var *evaluate(node *, var *);
583 static rstream *next_input_file(void);
584 static int fmt_num(char *, int, const char *, double, int);
585 static int awk_exit(int) NORETURN;
587 /* ---- error handling ---- */
589 static const char EMSG_INTERNAL_ERROR[] ALIGN1 = "Internal error";
590 static const char EMSG_UNEXP_EOS[] ALIGN1 = "Unexpected end of string";
591 static const char EMSG_UNEXP_TOKEN[] ALIGN1 = "Unexpected token";
592 static const char EMSG_DIV_BY_ZERO[] ALIGN1 = "Division by zero";
593 static const char EMSG_INV_FMT[] ALIGN1 = "Invalid format specifier";
594 static const char EMSG_TOO_FEW_ARGS[] ALIGN1 = "Too few arguments for builtin";
595 static const char EMSG_NOT_ARRAY[] ALIGN1 = "Not an array";
596 static const char EMSG_POSSIBLE_ERROR[] ALIGN1 = "Possible syntax error";
597 static const char EMSG_UNDEF_FUNC[] ALIGN1 = "Call to undefined function";
598 static const char EMSG_NO_MATH[] ALIGN1 = "Math support is not compiled in";
600 static void zero_out_var(var *vp)
602 memset(vp, 0, sizeof(*vp));
605 static void syntax_error(const char *message) NORETURN;
606 static void syntax_error(const char *message)
608 bb_error_msg_and_die("%s:%i: %s", g_progname, g_lineno, message);
611 /* ---- hash stuff ---- */
613 static unsigned hashidx(const char *name)
618 idx = *name++ + (idx << 6) - idx;
622 /* create new hash */
623 static xhash *hash_init(void)
627 newhash = xzalloc(sizeof(*newhash));
628 newhash->csize = FIRST_PRIME;
629 newhash->items = xzalloc(FIRST_PRIME * sizeof(newhash->items[0]));
634 /* find item in hash, return ptr to data, NULL if not found */
635 static void *hash_search(xhash *hash, const char *name)
639 hi = hash->items[hashidx(name) % hash->csize];
641 if (strcmp(hi->name, name) == 0)
648 /* grow hash if it becomes too big */
649 static void hash_rebuild(xhash *hash)
651 unsigned newsize, i, idx;
652 hash_item **newitems, *hi, *thi;
654 if (hash->nprime == ARRAY_SIZE(PRIMES))
657 newsize = PRIMES[hash->nprime++];
658 newitems = xzalloc(newsize * sizeof(newitems[0]));
660 for (i = 0; i < hash->csize; i++) {
665 idx = hashidx(thi->name) % newsize;
666 thi->next = newitems[idx];
672 hash->csize = newsize;
673 hash->items = newitems;
676 /* find item in hash, add it if necessary. Return ptr to data */
677 static void *hash_find(xhash *hash, const char *name)
683 hi = hash_search(hash, name);
685 if (++hash->nel / hash->csize > 10)
688 l = strlen(name) + 1;
689 hi = xzalloc(sizeof(*hi) + l);
690 strcpy(hi->name, name);
692 idx = hashidx(name) % hash->csize;
693 hi->next = hash->items[idx];
694 hash->items[idx] = hi;
700 #define findvar(hash, name) ((var*) hash_find((hash), (name)))
701 #define newvar(name) ((var*) hash_find(vhash, (name)))
702 #define newfile(name) ((rstream*)hash_find(fdhash, (name)))
703 #define newfunc(name) ((func*) hash_find(fnhash, (name)))
705 static void hash_remove(xhash *hash, const char *name)
707 hash_item *hi, **phi;
709 phi = &hash->items[hashidx(name) % hash->csize];
712 if (strcmp(hi->name, name) == 0) {
713 hash->glen -= (strlen(name) + 1);
723 /* ------ some useful functions ------ */
725 static char *skip_spaces(char *p)
728 if (*p == '\\' && p[1] == '\n') {
731 } else if (*p != ' ' && *p != '\t') {
739 /* returns old *s, advances *s past word and terminating NUL */
740 static char *nextword(char **s)
743 while (*(*s)++ != '\0')
748 static char nextchar(char **s)
755 c = bb_process_escape_sequence((const char**)s);
756 /* Example awk statement:
758 * we must treat \" as "
760 if (c == '\\' && *s == pps) { /* unrecognized \z? */
761 c = *(*s); /* yes, fetch z */
763 (*s)++; /* advance unless z = NUL */
768 /* TODO: merge with strcpy_and_process_escape_sequences()?
770 static void unescape_string_in_place(char *s1)
773 while ((*s1 = nextchar(&s)) != '\0')
777 static ALWAYS_INLINE int isalnum_(int c)
779 return (isalnum(c) || c == '_');
782 static double my_strtod(char **pp)
785 if (ENABLE_DESKTOP && cp[0] == '0') {
786 /* Might be hex or octal integer: 0x123abc or 07777 */
787 char c = (cp[1] | 0x20);
788 if (c == 'x' || isdigit(cp[1])) {
789 unsigned long long ull = strtoull(cp, pp, 0);
793 if (!isdigit(c) && c != '.')
795 /* else: it may be a floating number. Examples:
796 * 009.123 (*pp points to '9')
797 * 000.123 (*pp points to '.')
798 * fall through to strtod.
802 return strtod(cp, pp);
805 /* -------- working with variables (set/get/copy/etc) -------- */
807 static xhash *iamarray(var *v)
811 while (a->type & VF_CHILD)
814 if (!(a->type & VF_ARRAY)) {
816 a->x.array = hash_init();
821 static void clear_array(xhash *array)
826 for (i = 0; i < array->csize; i++) {
827 hi = array->items[i];
831 free(thi->data.v.string);
834 array->items[i] = NULL;
836 array->glen = array->nel = 0;
839 /* clear a variable */
840 static var *clrvar(var *v)
842 if (!(v->type & VF_FSTR))
845 v->type &= VF_DONTTOUCH;
851 /* assign string value to variable */
852 static var *setvar_p(var *v, char *value)
860 /* same as setvar_p but make a copy of string */
861 static var *setvar_s(var *v, const char *value)
863 return setvar_p(v, (value && *value) ? xstrdup(value) : NULL);
866 /* same as setvar_s but sets USER flag */
867 static var *setvar_u(var *v, const char *value)
869 v = setvar_s(v, value);
874 /* set array element to user string */
875 static void setari_u(var *a, int idx, const char *s)
879 v = findvar(iamarray(a), itoa(idx));
883 /* assign numeric value to variable */
884 static var *setvar_i(var *v, double value)
887 v->type |= VF_NUMBER;
893 static const char *getvar_s(var *v)
895 /* if v is numeric and has no cached string, convert it to string */
896 if ((v->type & (VF_NUMBER | VF_CACHED)) == VF_NUMBER) {
897 fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[CONVFMT]), v->number, TRUE);
898 v->string = xstrdup(g_buf);
899 v->type |= VF_CACHED;
901 return (v->string == NULL) ? "" : v->string;
904 static double getvar_i(var *v)
908 if ((v->type & (VF_NUMBER | VF_CACHED)) == 0) {
912 debug_printf_eval("getvar_i: '%s'->", s);
913 v->number = my_strtod(&s);
914 debug_printf_eval("%f (s:'%s')\n", v->number, s);
915 if (v->type & VF_USER) {
921 debug_printf_eval("getvar_i: '%s'->zero\n", s);
924 v->type |= VF_CACHED;
926 debug_printf_eval("getvar_i: %f\n", v->number);
930 /* Used for operands of bitwise ops */
931 static unsigned long getvar_i_int(var *v)
933 double d = getvar_i(v);
935 /* Casting doubles to longs is undefined for values outside
936 * of target type range. Try to widen it as much as possible */
938 return (unsigned long)d;
939 /* Why? Think about d == -4294967295.0 (assuming 32bit longs) */
940 return - (long) (unsigned long) (-d);
943 static var *copyvar(var *dest, const var *src)
947 dest->type |= (src->type & ~(VF_DONTTOUCH | VF_FSTR));
948 debug_printf_eval("copyvar: number:%f string:'%s'\n", src->number, src->string);
949 dest->number = src->number;
951 dest->string = xstrdup(src->string);
953 handle_special(dest);
957 static var *incvar(var *v)
959 return setvar_i(v, getvar_i(v) + 1.0);
962 /* return true if v is number or numeric string */
963 static int is_numeric(var *v)
966 return ((v->type ^ VF_DIRTY) & (VF_NUMBER | VF_USER | VF_DIRTY));
969 /* return 1 when value of v corresponds to true, 0 otherwise */
970 static int istrue(var *v)
973 return (v->number != 0);
974 return (v->string && v->string[0]);
977 /* temporary variables allocator. Last allocated should be first freed */
978 static var *nvalloc(int n)
986 if ((g_cb->pos - g_cb->nv) + n <= g_cb->size)
992 size = (n <= MINNVBLOCK) ? MINNVBLOCK : n;
993 g_cb = xzalloc(sizeof(nvblock) + size * sizeof(var));
995 g_cb->pos = g_cb->nv;
997 /*g_cb->next = NULL; - xzalloc did it */
1005 while (v < g_cb->pos) {
1014 static void nvfree(var *v)
1018 if (v < g_cb->nv || v >= g_cb->pos)
1019 syntax_error(EMSG_INTERNAL_ERROR);
1021 for (p = v; p < g_cb->pos; p++) {
1022 if ((p->type & (VF_ARRAY | VF_CHILD)) == VF_ARRAY) {
1023 clear_array(iamarray(p));
1024 free(p->x.array->items);
1027 if (p->type & VF_WALK) {
1029 walker_list *w = p->x.walker;
1030 debug_printf_walker("nvfree: freeing walker @%p\n", &p->x.walker);
1034 debug_printf_walker(" free(%p)\n", w);
1043 while (g_cb->prev && g_cb->pos == g_cb->nv) {
1048 /* ------- awk program text parsing ------- */
1050 /* Parse next token pointed by global pos, place results into global ttt.
1051 * If token isn't expected, give away. Return token class
1053 static uint32_t next_token(uint32_t expected)
1055 #define concat_inserted (G.next_token__concat_inserted)
1056 #define save_tclass (G.next_token__save_tclass)
1057 #define save_info (G.next_token__save_info)
1058 /* Initialized to TC_OPTERM: */
1059 #define ltclass (G.next_token__ltclass)
1068 } else if (concat_inserted) {
1069 concat_inserted = FALSE;
1070 t_tclass = save_tclass;
1076 g_lineno = t_lineno;
1078 while (*p != '\n' && *p != '\0')
1086 debug_printf_parse("%s: token found: TC_EOF\n", __func__);
1087 } else if (*p == '\"') {
1090 while (*p != '\"') {
1092 if (*p == '\0' || *p == '\n')
1093 syntax_error(EMSG_UNEXP_EOS);
1095 *s++ = nextchar(&pp);
1101 debug_printf_parse("%s: token found:'%s' TC_STRING\n", __func__, t_string);
1102 } else if ((expected & TC_REGEXP) && *p == '/') {
1106 if (*p == '\0' || *p == '\n')
1107 syntax_error(EMSG_UNEXP_EOS);
1111 s[-1] = bb_process_escape_sequence((const char **)&pp);
1123 debug_printf_parse("%s: token found:'%s' TC_REGEXP\n", __func__, t_string);
1125 } else if (*p == '.' || isdigit(*p)) {
1128 t_double = my_strtod(&pp);
1131 syntax_error(EMSG_UNEXP_TOKEN);
1133 debug_printf_parse("%s: token found:%f TC_NUMBER\n", __func__, t_double);
1135 /* search for something known */
1140 int l = (unsigned char) *tl++;
1141 if (l == (unsigned char) NTCC) {
1145 /* if token class is expected,
1147 * and it's not a longer word,
1149 if ((tc & (expected | TC_WORD | TC_NEWLINE))
1150 && strncmp(p, tl, l) == 0
1151 && !((tc & TC_WORD) && isalnum_(p[l]))
1153 /* then this is what we are looking for */
1155 debug_printf_parse("%s: token found:'%.*s' t_info:%x\n", __func__, l, p, t_info);
1162 /* not a known token */
1164 /* is it a name? (var/array/function) */
1166 syntax_error(EMSG_UNEXP_TOKEN); /* no */
1169 while (isalnum_(*++p)) {
1174 /* also consume whitespace between functionname and bracket */
1175 if (!(expected & TC_VARIABLE) || (expected & TC_ARRAY))
1179 debug_printf_parse("%s: token found:'%s' TC_FUNCTION\n", __func__, t_string);
1184 debug_printf_parse("%s: token found:'%s' TC_ARRAY\n", __func__, t_string);
1186 debug_printf_parse("%s: token found:'%s' TC_VARIABLE\n", __func__, t_string);
1192 /* skipping newlines in some cases */
1193 if ((ltclass & TC_NOTERM) && (tc & TC_NEWLINE))
1196 /* insert concatenation operator when needed */
1197 if ((ltclass & TC_CONCAT1) && (tc & TC_CONCAT2) && (expected & TC_BINOP)) {
1198 concat_inserted = TRUE;
1202 t_info = OC_CONCAT | SS | P(35);
1209 /* Are we ready for this? */
1210 if (!(ltclass & expected)) {
1211 syntax_error((ltclass & (TC_NEWLINE | TC_EOF)) ?
1212 EMSG_UNEXP_EOS : EMSG_UNEXP_TOKEN);
1216 #undef concat_inserted
1222 static void rollback_token(void)
1227 static node *new_node(uint32_t info)
1231 n = xzalloc(sizeof(node));
1233 n->lineno = g_lineno;
1237 static void mk_re_node(const char *s, node *n, regex_t *re)
1239 n->info = OC_REGEXP;
1242 xregcomp(re, s, REG_EXTENDED);
1243 xregcomp(re + 1, s, REG_EXTENDED | REG_ICASE);
1246 static node *condition(void)
1248 next_token(TC_SEQSTART);
1249 return parse_expr(TC_SEQTERM);
1252 /* parse expression terminated by given argument, return ptr
1253 * to built subtree. Terminator is eaten by parse_expr */
1254 static node *parse_expr(uint32_t iexp)
1262 debug_printf_parse("%s(%x)\n", __func__, iexp);
1265 sn.r.n = glptr = NULL;
1266 xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP | iexp;
1268 while (!((tc = next_token(xtc)) & iexp)) {
1270 if (glptr && (t_info == (OC_COMPARE | VV | P(39) | 2))) {
1271 /* input redirection (<) attached to glptr node */
1272 debug_printf_parse("%s: input redir\n", __func__);
1273 cn = glptr->l.n = new_node(OC_CONCAT | SS | P(37));
1275 xtc = TC_OPERAND | TC_UOPPRE;
1278 } else if (tc & (TC_BINOP | TC_UOPPOST)) {
1279 debug_printf_parse("%s: TC_BINOP | TC_UOPPOST\n", __func__);
1280 /* for binary and postfix-unary operators, jump back over
1281 * previous operators with higher priority */
1283 while (((t_info & PRIMASK) > (vn->a.n->info & PRIMASK2))
1284 || ((t_info == vn->info) && ((t_info & OPCLSMASK) == OC_COLON))
1288 if ((t_info & OPCLSMASK) == OC_TERNARY)
1290 cn = vn->a.n->r.n = new_node(t_info);
1292 if (tc & TC_BINOP) {
1294 xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP;
1295 if ((t_info & OPCLSMASK) == OC_PGETLINE) {
1297 next_token(TC_GETLINE);
1298 /* give maximum priority to this pipe */
1299 cn->info &= ~PRIMASK;
1300 xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1304 xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1309 debug_printf_parse("%s: other\n", __func__);
1310 /* for operands and prefix-unary operators, attach them
1313 cn = vn->r.n = new_node(t_info);
1315 xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP;
1316 if (tc & (TC_OPERAND | TC_REGEXP)) {
1317 debug_printf_parse("%s: TC_OPERAND | TC_REGEXP\n", __func__);
1318 xtc = TC_UOPPRE | TC_UOPPOST | TC_BINOP | TC_OPERAND | iexp;
1319 /* one should be very careful with switch on tclass -
1320 * only simple tclasses should be used! */
1324 debug_printf_parse("%s: TC_VARIABLE | TC_ARRAY\n", __func__);
1326 v = hash_search(ahash, t_string);
1328 cn->info = OC_FNARG;
1329 cn->l.aidx = v->x.aidx;
1331 cn->l.v = newvar(t_string);
1333 if (tc & TC_ARRAY) {
1335 cn->r.n = parse_expr(TC_ARRTERM);
1341 debug_printf_parse("%s: TC_NUMBER | TC_STRING\n", __func__);
1343 v = cn->l.v = xzalloc(sizeof(var));
1345 setvar_i(v, t_double);
1347 setvar_s(v, t_string);
1351 debug_printf_parse("%s: TC_REGEXP\n", __func__);
1352 mk_re_node(t_string, cn, xzalloc(sizeof(regex_t)*2));
1356 debug_printf_parse("%s: TC_FUNCTION\n", __func__);
1358 cn->r.f = newfunc(t_string);
1359 cn->l.n = condition();
1363 debug_printf_parse("%s: TC_SEQSTART\n", __func__);
1364 cn = vn->r.n = parse_expr(TC_SEQTERM);
1366 syntax_error("Empty sequence");
1371 debug_printf_parse("%s: TC_GETLINE\n", __func__);
1373 xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
1377 debug_printf_parse("%s: TC_BUILTIN\n", __func__);
1378 cn->l.n = condition();
1382 debug_printf_parse("%s: TC_LENGTH\n", __func__);
1383 next_token(TC_SEQSTART | TC_OPTERM | TC_GRPTERM);
1385 if (t_tclass & TC_SEQSTART) {
1386 /* It was a "(" token. Handle just like TC_BUILTIN */
1387 cn->l.n = condition();
1395 debug_printf_parse("%s() returns %p\n", __func__, sn.r.n);
1399 /* add node to chain. Return ptr to alloc'd node */
1400 static node *chain_node(uint32_t info)
1405 seq->first = seq->last = new_node(0);
1407 if (seq->programname != g_progname) {
1408 seq->programname = g_progname;
1409 n = chain_node(OC_NEWSOURCE);
1410 n->l.new_progname = xstrdup(g_progname);
1415 seq->last = n->a.n = new_node(OC_DONE);
1420 static void chain_expr(uint32_t info)
1424 n = chain_node(info);
1425 n->l.n = parse_expr(TC_OPTERM | TC_GRPTERM);
1426 if (t_tclass & TC_GRPTERM)
1430 static node *chain_loop(node *nn)
1432 node *n, *n2, *save_brk, *save_cont;
1434 save_brk = break_ptr;
1435 save_cont = continue_ptr;
1437 n = chain_node(OC_BR | Vx);
1438 continue_ptr = new_node(OC_EXEC);
1439 break_ptr = new_node(OC_EXEC);
1441 n2 = chain_node(OC_EXEC | Vx);
1444 continue_ptr->a.n = n2;
1445 break_ptr->a.n = n->r.n = seq->last;
1447 continue_ptr = save_cont;
1448 break_ptr = save_brk;
1453 /* parse group and attach it to chain */
1454 static void chain_group(void)
1460 c = next_token(TC_GRPSEQ);
1461 } while (c & TC_NEWLINE);
1463 if (c & TC_GRPSTART) {
1464 debug_printf_parse("%s: TC_GRPSTART\n", __func__);
1465 while (next_token(TC_GRPSEQ | TC_GRPTERM) != TC_GRPTERM) {
1466 debug_printf_parse("%s: !TC_GRPTERM\n", __func__);
1467 if (t_tclass & TC_NEWLINE)
1472 debug_printf_parse("%s: TC_GRPTERM\n", __func__);
1473 } else if (c & (TC_OPSEQ | TC_OPTERM)) {
1474 debug_printf_parse("%s: TC_OPSEQ | TC_OPTERM\n", __func__);
1476 chain_expr(OC_EXEC | Vx);
1479 debug_printf_parse("%s: TC_STATEMNT(?)\n", __func__);
1480 switch (t_info & OPCLSMASK) {
1482 debug_printf_parse("%s: ST_IF\n", __func__);
1483 n = chain_node(OC_BR | Vx);
1484 n->l.n = condition();
1486 n2 = chain_node(OC_EXEC);
1488 if (next_token(TC_GRPSEQ | TC_GRPTERM | TC_ELSE) == TC_ELSE) {
1490 n2->a.n = seq->last;
1497 debug_printf_parse("%s: ST_WHILE\n", __func__);
1499 n = chain_loop(NULL);
1504 debug_printf_parse("%s: ST_DO\n", __func__);
1505 n2 = chain_node(OC_EXEC);
1506 n = chain_loop(NULL);
1508 next_token(TC_WHILE);
1509 n->l.n = condition();
1513 debug_printf_parse("%s: ST_FOR\n", __func__);
1514 next_token(TC_SEQSTART);
1515 n2 = parse_expr(TC_SEMICOL | TC_SEQTERM);
1516 if (t_tclass & TC_SEQTERM) { /* for-in */
1517 if ((n2->info & OPCLSMASK) != OC_IN)
1518 syntax_error(EMSG_UNEXP_TOKEN);
1519 n = chain_node(OC_WALKINIT | VV);
1522 n = chain_loop(NULL);
1523 n->info = OC_WALKNEXT | Vx;
1525 } else { /* for (;;) */
1526 n = chain_node(OC_EXEC | Vx);
1528 n2 = parse_expr(TC_SEMICOL);
1529 n3 = parse_expr(TC_SEQTERM);
1539 debug_printf_parse("%s: OC_PRINT[F]\n", __func__);
1540 n = chain_node(t_info);
1541 n->l.n = parse_expr(TC_OPTERM | TC_OUTRDR | TC_GRPTERM);
1542 if (t_tclass & TC_OUTRDR) {
1544 n->r.n = parse_expr(TC_OPTERM | TC_GRPTERM);
1546 if (t_tclass & TC_GRPTERM)
1551 debug_printf_parse("%s: OC_BREAK\n", __func__);
1552 n = chain_node(OC_EXEC);
1558 debug_printf_parse("%s: OC_CONTINUE\n", __func__);
1559 n = chain_node(OC_EXEC);
1560 n->a.n = continue_ptr;
1564 /* delete, next, nextfile, return, exit */
1566 debug_printf_parse("%s: default\n", __func__);
1572 static void parse_program(char *p)
1581 while ((tclass = next_token(TC_EOF | TC_OPSEQ | TC_GRPSTART |
1582 TC_OPTERM | TC_BEGIN | TC_END | TC_FUNCDECL)) != TC_EOF) {
1584 if (tclass & TC_OPTERM) {
1585 debug_printf_parse("%s: TC_OPTERM\n", __func__);
1590 if (tclass & TC_BEGIN) {
1591 debug_printf_parse("%s: TC_BEGIN\n", __func__);
1594 } else if (tclass & TC_END) {
1595 debug_printf_parse("%s: TC_END\n", __func__);
1598 } else if (tclass & TC_FUNCDECL) {
1599 debug_printf_parse("%s: TC_FUNCDECL\n", __func__);
1600 next_token(TC_FUNCTION);
1602 f = newfunc(t_string);
1603 f->body.first = NULL;
1605 while (next_token(TC_VARIABLE | TC_SEQTERM) & TC_VARIABLE) {
1606 v = findvar(ahash, t_string);
1607 v->x.aidx = f->nargs++;
1609 if (next_token(TC_COMMA | TC_SEQTERM) & TC_SEQTERM)
1615 } else if (tclass & TC_OPSEQ) {
1616 debug_printf_parse("%s: TC_OPSEQ\n", __func__);
1618 cn = chain_node(OC_TEST);
1619 cn->l.n = parse_expr(TC_OPTERM | TC_EOF | TC_GRPSTART);
1620 if (t_tclass & TC_GRPSTART) {
1621 debug_printf_parse("%s: TC_GRPSTART\n", __func__);
1625 debug_printf_parse("%s: !TC_GRPSTART\n", __func__);
1626 chain_node(OC_PRINT);
1628 cn->r.n = mainseq.last;
1629 } else /* if (tclass & TC_GRPSTART) */ {
1630 debug_printf_parse("%s: TC_GRPSTART(?)\n", __func__);
1635 debug_printf_parse("%s: TC_EOF\n", __func__);
1639 /* -------- program execution part -------- */
1641 static node *mk_splitter(const char *s, tsplitter *spl)
1649 if ((n->info & OPCLSMASK) == OC_REGEXP) {
1651 regfree(ire); // TODO: nuke ire, use re+1?
1653 if (s[0] && s[1]) { /* strlen(s) > 1 */
1654 mk_re_node(s, n, re);
1656 n->info = (uint32_t) s[0];
1662 /* use node as a regular expression. Supplied with node ptr and regex_t
1663 * storage space. Return ptr to regex (if result points to preg, it should
1664 * be later regfree'd manually
1666 static regex_t *as_regex(node *op, regex_t *preg)
1672 if ((op->info & OPCLSMASK) == OC_REGEXP) {
1673 return icase ? op->r.ire : op->l.re;
1676 s = getvar_s(evaluate(op, v));
1678 cflags = icase ? REG_EXTENDED | REG_ICASE : REG_EXTENDED;
1679 /* Testcase where REG_EXTENDED fails (unpaired '{'):
1680 * echo Hi | awk 'gsub("@(samp|code|file)\{","");'
1681 * gawk 3.1.5 eats this. We revert to ~REG_EXTENDED
1682 * (maybe gsub is not supposed to use REG_EXTENDED?).
1684 if (regcomp(preg, s, cflags)) {
1685 cflags &= ~REG_EXTENDED;
1686 xregcomp(preg, s, cflags);
1692 /* gradually increasing buffer.
1693 * note that we reallocate even if n == old_size,
1694 * and thus there is at least one extra allocated byte.
1696 static char* qrealloc(char *b, int n, int *size)
1698 if (!b || n >= *size) {
1699 *size = n + (n>>1) + 80;
1700 b = xrealloc(b, *size);
1705 /* resize field storage space */
1706 static void fsrealloc(int size)
1710 if (size >= maxfields) {
1712 maxfields = size + 16;
1713 Fields = xrealloc(Fields, maxfields * sizeof(Fields[0]));
1714 for (; i < maxfields; i++) {
1715 Fields[i].type = VF_SPECIAL;
1716 Fields[i].string = NULL;
1719 /* if size < nfields, clear extra field variables */
1720 for (i = size; i < nfields; i++) {
1726 static int awk_split(const char *s, node *spl, char **slist)
1731 regmatch_t pmatch[2]; // TODO: why [2]? [1] is enough...
1733 /* in worst case, each char would be a separate field */
1734 *slist = s1 = xzalloc(strlen(s) * 2 + 3);
1737 c[0] = c[1] = (char)spl->info;
1739 if (*getvar_s(intvar[RS]) == '\0')
1743 if ((spl->info & OPCLSMASK) == OC_REGEXP) { /* regex split */
1745 return n; /* "": zero fields */
1746 n++; /* at least one field will be there */
1748 l = strcspn(s, c+2); /* len till next NUL or \n */
1749 if (regexec(icase ? spl->r.ire : spl->l.re, s, 1, pmatch, 0) == 0
1750 && pmatch[0].rm_so <= l
1752 l = pmatch[0].rm_so;
1753 if (pmatch[0].rm_eo == 0) {
1757 n++; /* we saw yet another delimiter */
1759 pmatch[0].rm_eo = l;
1764 /* make sure we remove *all* of the separator chars */
1767 } while (++l < pmatch[0].rm_eo);
1769 s += pmatch[0].rm_eo;
1773 if (c[0] == '\0') { /* null split */
1781 if (c[0] != ' ') { /* single-character split */
1783 c[0] = toupper(c[0]);
1784 c[1] = tolower(c[1]);
1788 while ((s1 = strpbrk(s1, c)) != NULL) {
1796 s = skip_whitespace(s);
1800 while (*s && !isspace(*s))
1807 static void split_f0(void)
1809 /* static char *fstrings; */
1810 #define fstrings (G.split_f0__fstrings)
1821 n = awk_split(getvar_s(intvar[F0]), &fsplitter.n, &fstrings);
1824 for (i = 0; i < n; i++) {
1825 Fields[i].string = nextword(&s);
1826 Fields[i].type |= (VF_FSTR | VF_USER | VF_DIRTY);
1829 /* set NF manually to avoid side effects */
1831 intvar[NF]->type = VF_NUMBER | VF_SPECIAL;
1832 intvar[NF]->number = nfields;
1836 /* perform additional actions when some internal variables changed */
1837 static void handle_special(var *v)
1841 const char *sep, *s;
1842 int sl, l, len, i, bsize;
1844 if (!(v->type & VF_SPECIAL))
1847 if (v == intvar[NF]) {
1848 n = (int)getvar_i(v);
1851 /* recalculate $0 */
1852 sep = getvar_s(intvar[OFS]);
1856 for (i = 0; i < n; i++) {
1857 s = getvar_s(&Fields[i]);
1860 memcpy(b+len, sep, sl);
1863 b = qrealloc(b, len+l+sl, &bsize);
1864 memcpy(b+len, s, l);
1869 setvar_p(intvar[F0], b);
1872 } else if (v == intvar[F0]) {
1873 is_f0_split = FALSE;
1875 } else if (v == intvar[FS]) {
1877 * The POSIX-2008 standard says that changing FS should have no effect on the
1878 * current input line, but only on the next one. The language is:
1880 * > Before the first reference to a field in the record is evaluated, the record
1881 * > shall be split into fields, according to the rules in Regular Expressions,
1882 * > using the value of FS that was current at the time the record was read.
1884 * So, split up current line before assignment to FS:
1888 mk_splitter(getvar_s(v), &fsplitter);
1889 } else if (v == intvar[RS]) {
1890 mk_splitter(getvar_s(v), &rsplitter);
1891 } else if (v == intvar[IGNORECASE]) {
1894 n = getvar_i(intvar[NF]);
1895 setvar_i(intvar[NF], n > v-Fields ? n : v-Fields+1);
1896 /* right here v is invalid. Just to note... */
1900 /* step through func/builtin/etc arguments */
1901 static node *nextarg(node **pn)
1906 if (n && (n->info & OPCLSMASK) == OC_COMMA) {
1915 static void hashwalk_init(var *v, xhash *array)
1920 walker_list *prev_walker;
1922 if (v->type & VF_WALK) {
1923 prev_walker = v->x.walker;
1928 debug_printf_walker("hashwalk_init: prev_walker:%p\n", prev_walker);
1930 w = v->x.walker = xzalloc(sizeof(*w) + array->glen + 1); /* why + 1? */
1931 debug_printf_walker(" walker@%p=%p\n", &v->x.walker, w);
1932 w->cur = w->end = w->wbuf;
1933 w->prev = prev_walker;
1934 for (i = 0; i < array->csize; i++) {
1935 hi = array->items[i];
1937 strcpy(w->end, hi->name);
1944 static int hashwalk_next(var *v)
1946 walker_list *w = v->x.walker;
1948 if (w->cur >= w->end) {
1949 walker_list *prev_walker = w->prev;
1951 debug_printf_walker("end of iteration, free(walker@%p:%p), prev_walker:%p\n", &v->x.walker, w, prev_walker);
1953 v->x.walker = prev_walker;
1957 setvar_s(v, nextword(&w->cur));
1961 /* evaluate node, return 1 when result is true, 0 otherwise */
1962 static int ptest(node *pattern)
1964 /* ptest__v is "static": to save stack space? */
1965 return istrue(evaluate(pattern, &G.ptest__v));
1968 /* read next record from stream rsm into a variable v */
1969 static int awk_getline(rstream *rsm, var *v)
1972 regmatch_t pmatch[2];
1973 int size, a, p, pp = 0;
1974 int fd, so, eo, r, rp;
1977 debug_printf_eval("entered %s()\n", __func__);
1979 /* we're using our own buffer since we need access to accumulating
1982 fd = fileno(rsm->F);
1987 c = (char) rsplitter.n.info;
1991 m = qrealloc(m, 256, &size);
1998 if ((rsplitter.n.info & OPCLSMASK) == OC_REGEXP) {
1999 if (regexec(icase ? rsplitter.n.r.ire : rsplitter.n.l.re,
2000 b, 1, pmatch, 0) == 0) {
2001 so = pmatch[0].rm_so;
2002 eo = pmatch[0].rm_eo;
2006 } else if (c != '\0') {
2007 s = strchr(b+pp, c);
2009 s = memchr(b+pp, '\0', p - pp);
2016 while (b[rp] == '\n')
2018 s = strstr(b+rp, "\n\n");
2021 while (b[eo] == '\n')
2030 memmove(m, m+a, p+1);
2035 m = qrealloc(m, a+p+128, &size);
2038 p += safe_read(fd, b+p, size-p-1);
2042 setvar_i(intvar[ERRNO], errno);
2051 c = b[so]; b[so] = '\0';
2055 c = b[eo]; b[eo] = '\0';
2056 setvar_s(intvar[RT], b+so);
2065 debug_printf_eval("returning from %s(): %d\n", __func__, r);
2070 static int fmt_num(char *b, int size, const char *format, double n, int int_as_int)
2074 const char *s = format;
2076 if (int_as_int && n == (long long)n) {
2077 r = snprintf(b, size, "%lld", (long long)n);
2079 do { c = *s; } while (c && *++s);
2080 if (strchr("diouxX", c)) {
2081 r = snprintf(b, size, format, (int)n);
2082 } else if (strchr("eEfgG", c)) {
2083 r = snprintf(b, size, format, n);
2085 syntax_error(EMSG_INV_FMT);
2091 /* formatted output into an allocated buffer, return ptr to buffer */
2092 static char *awk_printf(node *n)
2097 int i, j, incr, bsize;
2102 fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), v)));
2107 while (*f && (*f != '%' || *++f == '%'))
2109 while (*f && !isalpha(*f)) {
2111 syntax_error("%*x formats are not supported");
2115 incr = (f - s) + MAXVARFMT;
2116 b = qrealloc(b, incr + i, &bsize);
2122 arg = evaluate(nextarg(&n), v);
2125 if (c == 'c' || !c) {
2126 i += sprintf(b+i, s, is_numeric(arg) ?
2127 (char)getvar_i(arg) : *getvar_s(arg));
2128 } else if (c == 's') {
2130 b = qrealloc(b, incr+i+strlen(s1), &bsize);
2131 i += sprintf(b+i, s, s1);
2133 i += fmt_num(b+i, incr, s, getvar_i(arg), FALSE);
2137 /* if there was an error while sprintf, return value is negative */
2144 b = xrealloc(b, i + 1);
2149 /* Common substitution routine.
2150 * Replace (nm)'th substring of (src) that matches (rn) with (repl),
2151 * store result into (dest), return number of substitutions.
2152 * If nm = 0, replace all matches.
2153 * If src or dst is NULL, use $0.
2154 * If subexp != 0, enable subexpression matching (\1-\9).
2156 static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest, int subexp)
2160 int match_no, residx, replen, resbufsize;
2162 regmatch_t pmatch[10];
2163 regex_t sreg, *regex;
2169 regex = as_regex(rn, &sreg);
2170 sp = getvar_s(src ? src : intvar[F0]);
2171 replen = strlen(repl);
2172 while (regexec(regex, sp, 10, pmatch, regexec_flags) == 0) {
2173 int so = pmatch[0].rm_so;
2174 int eo = pmatch[0].rm_eo;
2176 //bb_error_msg("match %u: [%u,%u] '%s'%p", match_no+1, so, eo, sp,sp);
2177 resbuf = qrealloc(resbuf, residx + eo + replen, &resbufsize);
2178 memcpy(resbuf + residx, sp, eo);
2180 if (++match_no >= nm) {
2185 residx -= (eo - so);
2187 for (s = repl; *s; s++) {
2188 char c = resbuf[residx++] = *s;
2193 if (c == '&' || (subexp && c >= '0' && c <= '9')) {
2195 residx -= ((nbs + 3) >> 1);
2202 resbuf[residx++] = c;
2204 int n = pmatch[j].rm_eo - pmatch[j].rm_so;
2205 resbuf = qrealloc(resbuf, residx + replen + n, &resbufsize);
2206 memcpy(resbuf + residx, sp + pmatch[j].rm_so, n);
2214 regexec_flags = REG_NOTBOL;
2219 /* Empty match (e.g. "b*" will match anywhere).
2220 * Advance by one char. */
2222 //gsub(/\<b*/,"") on "abc" will reach this point, advance to "bc"
2223 //... and will erroneously match "b" even though it is NOT at the word start.
2224 //we need REG_NOTBOW but it does not exist...
2225 //TODO: if EXTRA_COMPAT=y, use GNU matching and re_search,
2226 //it should be able to do it correctly.
2227 /* Subtle: this is safe only because
2228 * qrealloc allocated at least one extra byte */
2229 resbuf[residx] = *sp;
2237 resbuf = qrealloc(resbuf, residx + strlen(sp), &resbufsize);
2238 strcpy(resbuf + residx, sp);
2240 //bb_error_msg("end sp:'%s'%p", sp,sp);
2241 setvar_p(dest ? dest : intvar[F0], resbuf);
2247 static NOINLINE int do_mktime(const char *ds)
2252 /*memset(&then, 0, sizeof(then)); - not needed */
2253 then.tm_isdst = -1; /* default is unknown */
2255 /* manpage of mktime says these fields are ints,
2256 * so we can sscanf stuff directly into them */
2257 count = sscanf(ds, "%u %u %u %u %u %u %d",
2258 &then.tm_year, &then.tm_mon, &then.tm_mday,
2259 &then.tm_hour, &then.tm_min, &then.tm_sec,
2263 || (unsigned)then.tm_mon < 1
2264 || (unsigned)then.tm_year < 1900
2270 then.tm_year -= 1900;
2272 return mktime(&then);
2275 static NOINLINE var *exec_builtin(node *op, var *res)
2277 #define tspl (G.exec_builtin__tspl)
2283 regmatch_t pmatch[2];
2292 isr = info = op->info;
2295 av[2] = av[3] = NULL;
2296 for (i = 0; i < 4 && op; i++) {
2297 an[i] = nextarg(&op);
2298 if (isr & 0x09000000)
2299 av[i] = evaluate(an[i], &tv[i]);
2300 if (isr & 0x08000000)
2301 as[i] = getvar_s(av[i]);
2306 if ((uint32_t)nargs < (info >> 30))
2307 syntax_error(EMSG_TOO_FEW_ARGS);
2313 if (ENABLE_FEATURE_AWK_LIBM)
2314 setvar_i(res, atan2(getvar_i(av[0]), getvar_i(av[1])));
2316 syntax_error(EMSG_NO_MATH);
2323 spl = (an[2]->info & OPCLSMASK) == OC_REGEXP ?
2324 an[2] : mk_splitter(getvar_s(evaluate(an[2], &tv[2])), &tspl);
2329 n = awk_split(as[0], spl, &s);
2331 clear_array(iamarray(av[1]));
2332 for (i = 1; i <= n; i++)
2333 setari_u(av[1], i, nextword(&s));
2343 i = getvar_i(av[1]) - 1;
2348 n = (nargs > 2) ? getvar_i(av[2]) : l-i;
2351 s = xstrndup(as[0]+i, n);
2356 /* Bitwise ops must assume that operands are unsigned. GNU Awk 3.1.5:
2357 * awk '{ print or(-1,1) }' gives "4.29497e+09", not "-2.xxxe+09" */
2359 setvar_i(res, getvar_i_int(av[0]) & getvar_i_int(av[1]));
2363 setvar_i(res, ~getvar_i_int(av[0]));
2367 setvar_i(res, getvar_i_int(av[0]) << getvar_i_int(av[1]));
2371 setvar_i(res, getvar_i_int(av[0]) | getvar_i_int(av[1]));
2375 setvar_i(res, getvar_i_int(av[0]) >> getvar_i_int(av[1]));
2379 setvar_i(res, getvar_i_int(av[0]) ^ getvar_i_int(av[1]));
2385 s1 = s = xstrdup(as[0]);
2387 //*s1 = (info == B_up) ? toupper(*s1) : tolower(*s1);
2388 if ((unsigned char)((*s1 | 0x20) - 'a') <= ('z' - 'a'))
2389 *s1 = (info == B_up) ? (*s1 & 0xdf) : (*s1 | 0x20);
2399 l = strlen(as[0]) - ll;
2400 if (ll > 0 && l >= 0) {
2402 char *s = strstr(as[0], as[1]);
2404 n = (s - as[0]) + 1;
2406 /* this piece of code is terribly slow and
2407 * really should be rewritten
2409 for (i = 0; i <= l; i++) {
2410 if (strncasecmp(as[0]+i, as[1], ll) == 0) {
2422 tt = getvar_i(av[1]);
2425 //s = (nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y";
2426 i = strftime(g_buf, MAXVARFMT,
2427 ((nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y"),
2430 setvar_s(res, g_buf);
2434 setvar_i(res, do_mktime(as[0]));
2438 re = as_regex(an[1], &sreg);
2439 n = regexec(re, as[0], 1, pmatch, 0);
2444 pmatch[0].rm_so = 0;
2445 pmatch[0].rm_eo = -1;
2447 setvar_i(newvar("RSTART"), pmatch[0].rm_so);
2448 setvar_i(newvar("RLENGTH"), pmatch[0].rm_eo - pmatch[0].rm_so);
2449 setvar_i(res, pmatch[0].rm_so);
2455 awk_sub(an[0], as[1], getvar_i(av[2]), av[3], res, TRUE);
2459 setvar_i(res, awk_sub(an[0], as[1], 0, av[2], av[2], FALSE));
2463 setvar_i(res, awk_sub(an[0], as[1], 1, av[2], av[2], FALSE));
2473 * Evaluate node - the heart of the program. Supplied with subtree
2474 * and place where to store result. returns ptr to result.
2476 #define XC(n) ((n) >> 8)
2478 static var *evaluate(node *op, var *res)
2480 /* This procedure is recursive so we should count every byte */
2481 #define fnargs (G.evaluate__fnargs)
2482 /* seed is initialized to 1 */
2483 #define seed (G.evaluate__seed)
2484 #define sreg (G.evaluate__sreg)
2489 return setvar_s(res, NULL);
2491 debug_printf_eval("entered %s()\n", __func__);
2499 } L = L; /* for compiler */
2510 opn = (opinfo & OPNMASK);
2511 g_lineno = op->lineno;
2513 debug_printf_eval("opinfo:%08x opn:%08x\n", opinfo, opn);
2515 /* execute inevitable things */
2516 if (opinfo & OF_RES1)
2517 L.v = evaluate(op1, v1);
2518 if (opinfo & OF_RES2)
2519 R.v = evaluate(op->r.n, v1+1);
2520 if (opinfo & OF_STR1) {
2521 L.s = getvar_s(L.v);
2522 debug_printf_eval("L.s:'%s'\n", L.s);
2524 if (opinfo & OF_STR2) {
2525 R.s = getvar_s(R.v);
2526 debug_printf_eval("R.s:'%s'\n", R.s);
2528 if (opinfo & OF_NUM1) {
2529 L_d = getvar_i(L.v);
2530 debug_printf_eval("L_d:%f\n", L_d);
2533 debug_printf_eval("switch(0x%x)\n", XC(opinfo & OPCLSMASK));
2534 switch (XC(opinfo & OPCLSMASK)) {
2536 /* -- iterative node type -- */
2540 if ((op1->info & OPCLSMASK) == OC_COMMA) {
2541 /* it's range pattern */
2542 if ((opinfo & OF_CHECKED) || ptest(op1->l.n)) {
2543 op->info |= OF_CHECKED;
2544 if (ptest(op1->r.n))
2545 op->info &= ~OF_CHECKED;
2551 op = ptest(op1) ? op->a.n : op->r.n;
2555 /* just evaluate an expression, also used as unconditional jump */
2559 /* branch, used in if-else and various loops */
2561 op = istrue(L.v) ? op->a.n : op->r.n;
2564 /* initialize for-in loop */
2565 case XC( OC_WALKINIT ):
2566 hashwalk_init(L.v, iamarray(R.v));
2569 /* get next array item */
2570 case XC( OC_WALKNEXT ):
2571 op = hashwalk_next(L.v) ? op->a.n : op->r.n;
2574 case XC( OC_PRINT ):
2575 case XC( OC_PRINTF ): {
2579 rstream *rsm = newfile(R.s);
2582 rsm->F = popen(R.s, "w");
2584 bb_perror_msg_and_die("popen");
2587 rsm->F = xfopen(R.s, opn=='w' ? "w" : "a");
2593 if ((opinfo & OPCLSMASK) == OC_PRINT) {
2595 fputs(getvar_s(intvar[F0]), F);
2598 var *v = evaluate(nextarg(&op1), v1);
2599 if (v->type & VF_NUMBER) {
2600 fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[OFMT]),
2604 fputs(getvar_s(v), F);
2608 fputs(getvar_s(intvar[OFS]), F);
2611 fputs(getvar_s(intvar[ORS]), F);
2613 } else { /* OC_PRINTF */
2614 char *s = awk_printf(op1);
2622 case XC( OC_DELETE ): {
2623 uint32_t info = op1->info & OPCLSMASK;
2626 if (info == OC_VAR) {
2628 } else if (info == OC_FNARG) {
2629 v = &fnargs[op1->l.aidx];
2631 syntax_error(EMSG_NOT_ARRAY);
2637 s = getvar_s(evaluate(op1->r.n, v1));
2638 hash_remove(iamarray(v), s);
2640 clear_array(iamarray(v));
2645 case XC( OC_NEWSOURCE ):
2646 g_progname = op->l.new_progname;
2649 case XC( OC_RETURN ):
2653 case XC( OC_NEXTFILE ):
2664 /* -- recursive node type -- */
2668 if (L.v == intvar[NF])
2672 case XC( OC_FNARG ):
2673 L.v = &fnargs[op->l.aidx];
2675 res = op->r.n ? findvar(iamarray(L.v), R.s) : L.v;
2679 setvar_i(res, hash_search(iamarray(R.v), L.s) ? 1 : 0);
2682 case XC( OC_REGEXP ):
2684 L.s = getvar_s(intvar[F0]);
2687 case XC( OC_MATCH ):
2691 regex_t *re = as_regex(op1, &sreg);
2692 int i = regexec(re, L.s, 0, NULL, 0);
2695 setvar_i(res, (i == 0) ^ (opn == '!'));
2700 debug_printf_eval("MOVE\n");
2701 /* if source is a temporary string, jusk relink it to dest */
2702 //Disabled: if R.v is numeric but happens to have cached R.v->string,
2703 //then L.v ends up being a string, which is wrong
2704 // if (R.v == v1+1 && R.v->string) {
2705 // res = setvar_p(L.v, R.v->string);
2706 // R.v->string = NULL;
2708 res = copyvar(L.v, R.v);
2712 case XC( OC_TERNARY ):
2713 if ((op->r.n->info & OPCLSMASK) != OC_COLON)
2714 syntax_error(EMSG_POSSIBLE_ERROR);
2715 res = evaluate(istrue(L.v) ? op->r.n->l.n : op->r.n->r.n, res);
2718 case XC( OC_FUNC ): {
2720 const char *sv_progname;
2722 /* The body might be empty, still has to eval the args */
2723 if (!op->r.n->info && !op->r.f->body.first)
2724 syntax_error(EMSG_UNDEF_FUNC);
2726 vbeg = v = nvalloc(op->r.f->nargs + 1);
2728 var *arg = evaluate(nextarg(&op1), v1);
2730 v->type |= VF_CHILD;
2732 if (++v - vbeg >= op->r.f->nargs)
2738 sv_progname = g_progname;
2740 res = evaluate(op->r.f->body.first, res);
2742 g_progname = sv_progname;
2749 case XC( OC_GETLINE ):
2750 case XC( OC_PGETLINE ): {
2757 if ((opinfo & OPCLSMASK) == OC_PGETLINE) {
2758 rsm->F = popen(L.s, "r");
2759 rsm->is_pipe = TRUE;
2761 rsm->F = fopen_for_read(L.s); /* not xfopen! */
2766 iF = next_input_file();
2770 if (!rsm || !rsm->F) {
2771 setvar_i(intvar[ERRNO], errno);
2779 i = awk_getline(rsm, R.v);
2780 if (i > 0 && !op1) {
2781 incvar(intvar[FNR]);
2788 /* simple builtins */
2789 case XC( OC_FBLTIN ): {
2790 double R_d = R_d; /* for compiler */
2794 R_d = (long long)L_d;
2798 R_d = (double)rand() / (double)RAND_MAX;
2802 if (ENABLE_FEATURE_AWK_LIBM) {
2808 if (ENABLE_FEATURE_AWK_LIBM) {
2814 if (ENABLE_FEATURE_AWK_LIBM) {
2820 if (ENABLE_FEATURE_AWK_LIBM) {
2826 if (ENABLE_FEATURE_AWK_LIBM) {
2831 syntax_error(EMSG_NO_MATH);
2836 seed = op1 ? (unsigned)L_d : (unsigned)time(NULL);
2845 debug_printf_eval("length: L.s:'%s'\n", L.s);
2847 L.s = getvar_s(intvar[F0]);
2848 debug_printf_eval("length: L.s='%s'\n", L.s);
2850 else if (L.v->type & VF_ARRAY) {
2851 R_d = L.v->x.array->nel;
2852 debug_printf_eval("length: array_len:%d\n", L.v->x.array->nel);
2860 R_d = (ENABLE_FEATURE_ALLOW_EXEC && L.s && *L.s)
2861 ? (system(L.s) >> 8) : 0;
2867 } else if (L.s && *L.s) {
2868 rstream *rsm = newfile(L.s);
2878 rsm = (rstream *)hash_search(fdhash, L.s);
2879 debug_printf_eval("OC_FBLTIN F_cl rsm:%p\n", rsm);
2881 debug_printf_eval("OC_FBLTIN F_cl "
2882 "rsm->is_pipe:%d, ->F:%p\n",
2883 rsm->is_pipe, rsm->F);
2884 /* Can be NULL if open failed. Example:
2885 * getline line <"doesnt_exist";
2886 * close("doesnt_exist"); <--- here rsm->F is NULL
2889 err = rsm->is_pipe ? pclose(rsm->F) : fclose(rsm->F);
2891 hash_remove(fdhash, L.s);
2894 setvar_i(intvar[ERRNO], errno);
2903 case XC( OC_BUILTIN ):
2904 res = exec_builtin(op, res);
2907 case XC( OC_SPRINTF ):
2908 setvar_p(res, awk_printf(op1));
2911 case XC( OC_UNARY ): {
2914 Ld = R_d = getvar_i(R.v);
2941 case XC( OC_FIELD ): {
2942 int i = (int)getvar_i(R.v);
2949 res = &Fields[i - 1];
2954 /* concatenation (" ") and index joining (",") */
2955 case XC( OC_CONCAT ):
2956 case XC( OC_COMMA ): {
2957 const char *sep = "";
2958 if ((opinfo & OPCLSMASK) == OC_COMMA)
2959 sep = getvar_s(intvar[SUBSEP]);
2960 setvar_p(res, xasprintf("%s%s%s", L.s, sep, R.s));
2965 setvar_i(res, istrue(L.v) ? ptest(op->r.n) : 0);
2969 setvar_i(res, istrue(L.v) ? 1 : ptest(op->r.n));
2972 case XC( OC_BINARY ):
2973 case XC( OC_REPLACE ): {
2974 double R_d = getvar_i(R.v);
2975 debug_printf_eval("BINARY/REPLACE: R_d:%f opn:%c\n", R_d, opn);
2988 syntax_error(EMSG_DIV_BY_ZERO);
2992 if (ENABLE_FEATURE_AWK_LIBM)
2993 L_d = pow(L_d, R_d);
2995 syntax_error(EMSG_NO_MATH);
2999 syntax_error(EMSG_DIV_BY_ZERO);
3000 L_d -= (long long)(L_d / R_d) * R_d;
3003 debug_printf_eval("BINARY/REPLACE result:%f\n", L_d);
3004 res = setvar_i(((opinfo & OPCLSMASK) == OC_BINARY) ? res : L.v, L_d);
3008 case XC( OC_COMPARE ): {
3009 int i = i; /* for compiler */
3012 if (is_numeric(L.v) && is_numeric(R.v)) {
3013 Ld = getvar_i(L.v) - getvar_i(R.v);
3015 const char *l = getvar_s(L.v);
3016 const char *r = getvar_s(R.v);
3017 Ld = icase ? strcasecmp(l, r) : strcmp(l, r);
3019 switch (opn & 0xfe) {
3030 setvar_i(res, (i == 0) ^ (opn & 1));
3035 syntax_error(EMSG_POSSIBLE_ERROR);
3037 if ((opinfo & OPCLSMASK) <= SHIFT_TIL_THIS)
3039 if ((opinfo & OPCLSMASK) >= RECUR_FROM_THIS)
3046 debug_printf_eval("returning from %s(): %p\n", __func__, res);
3054 /* -------- main & co. -------- */
3056 static int awk_exit(int r)
3067 evaluate(endseq.first, &tv);
3070 /* waiting for children */
3071 for (i = 0; i < fdhash->csize; i++) {
3072 hi = fdhash->items[i];
3074 if (hi->data.rs.F && hi->data.rs.is_pipe)
3075 pclose(hi->data.rs.F);
3083 /* if expr looks like "var=value", perform assignment and return 1,
3084 * otherwise return 0 */
3085 static int is_assignment(const char *expr)
3089 if (!isalnum_(*expr) || (val = strchr(expr, '=')) == NULL) {
3093 exprc = xstrdup(expr);
3094 val = exprc + (val - expr);
3097 unescape_string_in_place(val);
3098 setvar_u(newvar(exprc), val);
3103 /* switch to next input file */
3104 static rstream *next_input_file(void)
3106 #define rsm (G.next_input_file__rsm)
3107 #define files_happen (G.next_input_file__files_happen)
3110 const char *fname, *ind;
3115 rsm.pos = rsm.adv = 0;
3118 if (getvar_i(intvar[ARGIND])+1 >= getvar_i(intvar[ARGC])) {
3125 ind = getvar_s(incvar(intvar[ARGIND]));
3126 fname = getvar_s(findvar(iamarray(intvar[ARGV]), ind));
3127 if (fname && *fname && !is_assignment(fname)) {
3128 F = xfopen_stdin(fname);
3133 files_happen = TRUE;
3134 setvar_s(intvar[FILENAME], fname);
3141 int awk_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3142 int awk_main(int argc, char **argv)
3146 llist_t *list_v = NULL;
3147 llist_t *list_f = NULL;
3148 #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
3149 llist_t *list_e = NULL;
3155 char *vnames = (char *)vNames; /* cheat */
3156 char *vvalues = (char *)vValues;
3160 /* Undo busybox.c, or else strtod may eat ','! This breaks parsing:
3161 * $1,$2 == '$1,' '$2', NOT '$1' ',' '$2' */
3162 if (ENABLE_LOCALE_SUPPORT)
3163 setlocale(LC_NUMERIC, "C");
3167 /* allocate global buffer */
3168 g_buf = xmalloc(MAXVARFMT + 1);
3170 vhash = hash_init();
3171 ahash = hash_init();
3172 fdhash = hash_init();
3173 fnhash = hash_init();
3175 /* initialize variables */
3176 for (i = 0; *vnames; i++) {
3177 intvar[i] = v = newvar(nextword(&vnames));
3178 if (*vvalues != '\377')
3179 setvar_s(v, nextword(&vvalues));
3183 if (*vnames == '*') {
3184 v->type |= VF_SPECIAL;
3189 handle_special(intvar[FS]);
3190 handle_special(intvar[RS]);
3192 newfile("/dev/stdin")->F = stdin;
3193 newfile("/dev/stdout")->F = stdout;
3194 newfile("/dev/stderr")->F = stderr;
3196 /* Huh, people report that sometimes environ is NULL. Oh well. */
3197 if (environ) for (envp = environ; *envp; envp++) {
3198 /* environ is writable, thus we don't strdup it needlessly */
3200 char *s1 = strchr(s, '=');
3203 /* Both findvar and setvar_u take const char*
3204 * as 2nd arg -> environment is not trashed */
3205 setvar_u(findvar(iamarray(intvar[ENVIRON]), s), s1 + 1);
3209 opt = getopt32(argv, OPTSTR_AWK, &opt_F, &list_v, &list_f, IF_FEATURE_AWK_GNU_EXTENSIONS(&list_e,) NULL);
3213 bb_error_msg("warning: option -W is ignored");
3215 unescape_string_in_place(opt_F);
3216 setvar_s(intvar[FS], opt_F);
3219 if (!is_assignment(llist_pop(&list_v)))
3226 g_progname = llist_pop(&list_f);
3227 from_file = xfopen_stdin(g_progname);
3228 /* one byte is reserved for some trick in next_token */
3229 for (i = j = 1; j > 0; i += j) {
3230 s = xrealloc(s, i + 4096);
3231 j = fread(s + i, 1, 4094, from_file);
3235 parse_program(s + 1);
3238 g_progname = "cmd. line";
3239 #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
3241 parse_program(llist_pop(&list_e));
3244 if (!(opt & (OPT_f | OPT_e))) {
3247 parse_program(*argv++);
3251 /* fill in ARGV array */
3252 setvar_i(intvar[ARGC], argc + 1);
3253 setari_u(intvar[ARGV], 0, "awk");
3256 setari_u(intvar[ARGV], ++i, *argv++);
3258 evaluate(beginseq.first, &tv);
3259 if (!mainseq.first && !endseq.first)
3260 awk_exit(EXIT_SUCCESS);
3262 /* input file could already be opened in BEGIN block */
3264 iF = next_input_file();
3266 /* passing through input files */
3269 setvar_i(intvar[FNR], 0);
3271 while ((i = awk_getline(iF, intvar[F0])) > 0) {
3274 incvar(intvar[FNR]);
3275 evaluate(mainseq.first, &tv);
3282 syntax_error(strerror(errno));
3284 iF = next_input_file();
3287 awk_exit(EXIT_SUCCESS);