awk.c 63 KB

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