awk.c 77 KB

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