awk.c 63 KB

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