awk.c 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889
  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. struct globals {
  348. chain beginseq, mainseq, endseq;
  349. chain *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 *)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. SET_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 ALWAYS_INLINE int isalnum_(int c)
  588. {
  589. return (isalnum(c) || c == '_');
  590. }
  591. /* -------- working with variables (set/get/copy/etc) -------- */
  592. static xhash *iamarray(var *v)
  593. {
  594. var *a = v;
  595. while (a->type & VF_CHILD)
  596. a = a->x.parent;
  597. if (!(a->type & VF_ARRAY)) {
  598. a->type |= VF_ARRAY;
  599. a->x.array = hash_init();
  600. }
  601. return a->x.array;
  602. }
  603. static void clear_array(xhash *array)
  604. {
  605. unsigned i;
  606. hash_item *hi, *thi;
  607. for (i = 0; i < array->csize; i++) {
  608. hi = array->items[i];
  609. while (hi) {
  610. thi = hi;
  611. hi = hi->next;
  612. free(thi->data.v.string);
  613. free(thi);
  614. }
  615. array->items[i] = NULL;
  616. }
  617. array->glen = array->nel = 0;
  618. }
  619. /* clear a variable */
  620. static var *clrvar(var *v)
  621. {
  622. if (!(v->type & VF_FSTR))
  623. free(v->string);
  624. v->type &= VF_DONTTOUCH;
  625. v->type |= VF_DIRTY;
  626. v->string = NULL;
  627. return v;
  628. }
  629. /* assign string value to variable */
  630. static var *setvar_p(var *v, char *value)
  631. {
  632. clrvar(v);
  633. v->string = value;
  634. handle_special(v);
  635. return v;
  636. }
  637. /* same as setvar_p but make a copy of string */
  638. static var *setvar_s(var *v, const char *value)
  639. {
  640. return setvar_p(v, (value && *value) ? xstrdup(value) : NULL);
  641. }
  642. /* same as setvar_s but set USER flag */
  643. static var *setvar_u(var *v, const char *value)
  644. {
  645. setvar_s(v, value);
  646. v->type |= VF_USER;
  647. return v;
  648. }
  649. /* set array element to user string */
  650. static void setari_u(var *a, int idx, const char *s)
  651. {
  652. char sidx[sizeof(int)*3 + 1];
  653. var *v;
  654. sprintf(sidx, "%d", idx);
  655. v = findvar(iamarray(a), sidx);
  656. setvar_u(v, s);
  657. }
  658. /* assign numeric value to variable */
  659. static var *setvar_i(var *v, double value)
  660. {
  661. clrvar(v);
  662. v->type |= VF_NUMBER;
  663. v->number = value;
  664. handle_special(v);
  665. return v;
  666. }
  667. static const char *getvar_s(var *v)
  668. {
  669. /* if v is numeric and has no cached string, convert it to string */
  670. if ((v->type & (VF_NUMBER | VF_CACHED)) == VF_NUMBER) {
  671. fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[CONVFMT]), v->number, TRUE);
  672. v->string = xstrdup(g_buf);
  673. v->type |= VF_CACHED;
  674. }
  675. return (v->string == NULL) ? "" : v->string;
  676. }
  677. static double getvar_i(var *v)
  678. {
  679. char *s;
  680. if ((v->type & (VF_NUMBER | VF_CACHED)) == 0) {
  681. v->number = 0;
  682. s = v->string;
  683. if (s && *s) {
  684. v->number = strtod(s, &s);
  685. if (v->type & VF_USER) {
  686. skip_spaces(&s);
  687. if (*s != '\0')
  688. v->type &= ~VF_USER;
  689. }
  690. } else {
  691. v->type &= ~VF_USER;
  692. }
  693. v->type |= VF_CACHED;
  694. }
  695. return v->number;
  696. }
  697. static var *copyvar(var *dest, const var *src)
  698. {
  699. if (dest != src) {
  700. clrvar(dest);
  701. dest->type |= (src->type & ~(VF_DONTTOUCH | VF_FSTR));
  702. dest->number = src->number;
  703. if (src->string)
  704. dest->string = xstrdup(src->string);
  705. }
  706. handle_special(dest);
  707. return dest;
  708. }
  709. static var *incvar(var *v)
  710. {
  711. return setvar_i(v, getvar_i(v) + 1.);
  712. }
  713. /* return true if v is number or numeric string */
  714. static int is_numeric(var *v)
  715. {
  716. getvar_i(v);
  717. return ((v->type ^ VF_DIRTY) & (VF_NUMBER | VF_USER | VF_DIRTY));
  718. }
  719. /* return 1 when value of v corresponds to true, 0 otherwise */
  720. static int istrue(var *v)
  721. {
  722. if (is_numeric(v))
  723. return (v->number == 0) ? 0 : 1;
  724. return (v->string && *(v->string)) ? 1 : 0;
  725. }
  726. /* temporary variables allocator. Last allocated should be first freed */
  727. static var *nvalloc(int n)
  728. {
  729. nvblock *pb = NULL;
  730. var *v, *r;
  731. int size;
  732. while (g_cb) {
  733. pb = g_cb;
  734. if ((g_cb->pos - g_cb->nv) + n <= g_cb->size) break;
  735. g_cb = g_cb->next;
  736. }
  737. if (!g_cb) {
  738. size = (n <= MINNVBLOCK) ? MINNVBLOCK : n;
  739. g_cb = xmalloc(sizeof(nvblock) + size * sizeof(var));
  740. g_cb->size = size;
  741. g_cb->pos = g_cb->nv;
  742. g_cb->prev = pb;
  743. g_cb->next = NULL;
  744. if (pb) pb->next = g_cb;
  745. }
  746. v = r = g_cb->pos;
  747. g_cb->pos += n;
  748. while (v < g_cb->pos) {
  749. v->type = 0;
  750. v->string = NULL;
  751. v++;
  752. }
  753. return r;
  754. }
  755. static void nvfree(var *v)
  756. {
  757. var *p;
  758. if (v < g_cb->nv || v >= g_cb->pos)
  759. syntax_error(EMSG_INTERNAL_ERROR);
  760. for (p = v; p < g_cb->pos; p++) {
  761. if ((p->type & (VF_ARRAY | VF_CHILD)) == VF_ARRAY) {
  762. clear_array(iamarray(p));
  763. free(p->x.array->items);
  764. free(p->x.array);
  765. }
  766. if (p->type & VF_WALK)
  767. free(p->x.walker);
  768. clrvar(p);
  769. }
  770. g_cb->pos = v;
  771. while (g_cb->prev && g_cb->pos == g_cb->nv) {
  772. g_cb = g_cb->prev;
  773. }
  774. }
  775. /* ------- awk program text parsing ------- */
  776. /* Parse next token pointed by global pos, place results into global ttt.
  777. * If token isn't expected, give away. Return token class
  778. */
  779. static uint32_t next_token(uint32_t expected)
  780. {
  781. #define concat_inserted (G.next_token__concat_inserted)
  782. #define save_tclass (G.next_token__save_tclass)
  783. #define save_info (G.next_token__save_info)
  784. /* Initialized to TC_OPTERM: */
  785. #define ltclass (G.next_token__ltclass)
  786. char *p, *pp, *s;
  787. const char *tl;
  788. uint32_t tc;
  789. const uint32_t *ti;
  790. int l;
  791. if (t_rollback) {
  792. t_rollback = FALSE;
  793. } else if (concat_inserted) {
  794. concat_inserted = FALSE;
  795. t_tclass = save_tclass;
  796. t_info = save_info;
  797. } else {
  798. p = g_pos;
  799. readnext:
  800. skip_spaces(&p);
  801. g_lineno = t_lineno;
  802. if (*p == '#')
  803. while (*p != '\n' && *p != '\0')
  804. p++;
  805. if (*p == '\n')
  806. t_lineno++;
  807. if (*p == '\0') {
  808. tc = TC_EOF;
  809. } else if (*p == '\"') {
  810. /* it's a string */
  811. t_string = s = ++p;
  812. while (*p != '\"') {
  813. if (*p == '\0' || *p == '\n')
  814. syntax_error(EMSG_UNEXP_EOS);
  815. *(s++) = nextchar(&p);
  816. }
  817. p++;
  818. *s = '\0';
  819. tc = TC_STRING;
  820. } else if ((expected & TC_REGEXP) && *p == '/') {
  821. /* it's regexp */
  822. t_string = s = ++p;
  823. while (*p != '/') {
  824. if (*p == '\0' || *p == '\n')
  825. syntax_error(EMSG_UNEXP_EOS);
  826. *s = *p++;
  827. if (*s++ == '\\') {
  828. pp = p;
  829. *(s-1) = bb_process_escape_sequence((const char **)&p);
  830. if (*pp == '\\')
  831. *s++ = '\\';
  832. if (p == pp)
  833. *s++ = *p++;
  834. }
  835. }
  836. p++;
  837. *s = '\0';
  838. tc = TC_REGEXP;
  839. } else if (*p == '.' || isdigit(*p)) {
  840. /* it's a number */
  841. t_double = strtod(p, &p);
  842. if (*p == '.')
  843. syntax_error(EMSG_UNEXP_TOKEN);
  844. tc = TC_NUMBER;
  845. } else {
  846. /* search for something known */
  847. tl = tokenlist;
  848. tc = 0x00000001;
  849. ti = tokeninfo;
  850. while (*tl) {
  851. l = *(tl++);
  852. if (l == NTCC) {
  853. tc <<= 1;
  854. continue;
  855. }
  856. /* if token class is expected, token
  857. * matches and it's not a longer word,
  858. * then this is what we are looking for
  859. */
  860. if ((tc & (expected | TC_WORD | TC_NEWLINE))
  861. && *tl == *p && strncmp(p, tl, l) == 0
  862. && !((tc & TC_WORD) && isalnum_(p[l]))
  863. ) {
  864. t_info = *ti;
  865. p += l;
  866. break;
  867. }
  868. ti++;
  869. tl += l;
  870. }
  871. if (!*tl) {
  872. /* it's a name (var/array/function),
  873. * otherwise it's something wrong
  874. */
  875. if (!isalnum_(*p))
  876. syntax_error(EMSG_UNEXP_TOKEN);
  877. t_string = --p;
  878. while (isalnum_(*(++p))) {
  879. *(p-1) = *p;
  880. }
  881. *(p-1) = '\0';
  882. tc = TC_VARIABLE;
  883. /* also consume whitespace between functionname and bracket */
  884. if (!(expected & TC_VARIABLE))
  885. skip_spaces(&p);
  886. if (*p == '(') {
  887. tc = TC_FUNCTION;
  888. } else {
  889. if (*p == '[') {
  890. p++;
  891. tc = TC_ARRAY;
  892. }
  893. }
  894. }
  895. }
  896. g_pos = p;
  897. /* skipping newlines in some cases */
  898. if ((ltclass & TC_NOTERM) && (tc & TC_NEWLINE))
  899. goto readnext;
  900. /* insert concatenation operator when needed */
  901. if ((ltclass & TC_CONCAT1) && (tc & TC_CONCAT2) && (expected & TC_BINOP)) {
  902. concat_inserted = TRUE;
  903. save_tclass = tc;
  904. save_info = t_info;
  905. tc = TC_BINOP;
  906. t_info = OC_CONCAT | SS | P(35);
  907. }
  908. t_tclass = tc;
  909. }
  910. ltclass = t_tclass;
  911. /* Are we ready for this? */
  912. if (!(ltclass & expected))
  913. syntax_error((ltclass & (TC_NEWLINE | TC_EOF)) ?
  914. EMSG_UNEXP_EOS : EMSG_UNEXP_TOKEN);
  915. return ltclass;
  916. #undef concat_inserted
  917. #undef save_tclass
  918. #undef save_info
  919. #undef ltclass
  920. }
  921. static void rollback_token(void)
  922. {
  923. t_rollback = TRUE;
  924. }
  925. static node *new_node(uint32_t info)
  926. {
  927. node *n;
  928. n = xzalloc(sizeof(node));
  929. n->info = info;
  930. n->lineno = g_lineno;
  931. return n;
  932. }
  933. static node *mk_re_node(const char *s, node *n, regex_t *re)
  934. {
  935. n->info = OC_REGEXP;
  936. n->l.re = re;
  937. n->r.ire = re + 1;
  938. xregcomp(re, s, REG_EXTENDED);
  939. xregcomp(re + 1, s, REG_EXTENDED | REG_ICASE);
  940. return n;
  941. }
  942. static node *condition(void)
  943. {
  944. next_token(TC_SEQSTART);
  945. return parse_expr(TC_SEQTERM);
  946. }
  947. /* parse expression terminated by given argument, return ptr
  948. * to built subtree. Terminator is eaten by parse_expr */
  949. static node *parse_expr(uint32_t iexp)
  950. {
  951. node sn;
  952. node *cn = &sn;
  953. node *vn, *glptr;
  954. uint32_t tc, xtc;
  955. var *v;
  956. sn.info = PRIMASK;
  957. sn.r.n = glptr = NULL;
  958. xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP | iexp;
  959. while (!((tc = next_token(xtc)) & iexp)) {
  960. if (glptr && (t_info == (OC_COMPARE | VV | P(39) | 2))) {
  961. /* input redirection (<) attached to glptr node */
  962. cn = glptr->l.n = new_node(OC_CONCAT | SS | P(37));
  963. cn->a.n = glptr;
  964. xtc = TC_OPERAND | TC_UOPPRE;
  965. glptr = NULL;
  966. } else if (tc & (TC_BINOP | TC_UOPPOST)) {
  967. /* for binary and postfix-unary operators, jump back over
  968. * previous operators with higher priority */
  969. vn = cn;
  970. while ( ((t_info & PRIMASK) > (vn->a.n->info & PRIMASK2))
  971. || ((t_info == vn->info) && ((t_info & OPCLSMASK) == OC_COLON)) )
  972. vn = vn->a.n;
  973. if ((t_info & OPCLSMASK) == OC_TERNARY)
  974. t_info += P(6);
  975. cn = vn->a.n->r.n = new_node(t_info);
  976. cn->a.n = vn->a.n;
  977. if (tc & TC_BINOP) {
  978. cn->l.n = vn;
  979. xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP;
  980. if ((t_info & OPCLSMASK) == OC_PGETLINE) {
  981. /* it's a pipe */
  982. next_token(TC_GETLINE);
  983. /* give maximum priority to this pipe */
  984. cn->info &= ~PRIMASK;
  985. xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
  986. }
  987. } else {
  988. cn->r.n = vn;
  989. xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
  990. }
  991. vn->a.n = cn;
  992. } else {
  993. /* for operands and prefix-unary operators, attach them
  994. * to last node */
  995. vn = cn;
  996. cn = vn->r.n = new_node(t_info);
  997. cn->a.n = vn;
  998. xtc = TC_OPERAND | TC_UOPPRE | TC_REGEXP;
  999. if (tc & (TC_OPERAND | TC_REGEXP)) {
  1000. xtc = TC_UOPPRE | TC_UOPPOST | TC_BINOP | TC_OPERAND | iexp;
  1001. /* one should be very careful with switch on tclass -
  1002. * only simple tclasses should be used! */
  1003. switch (tc) {
  1004. case TC_VARIABLE:
  1005. case TC_ARRAY:
  1006. cn->info = OC_VAR;
  1007. v = hash_search(ahash, t_string);
  1008. if (v != NULL) {
  1009. cn->info = OC_FNARG;
  1010. cn->l.i = v->x.aidx;
  1011. } else {
  1012. cn->l.v = newvar(t_string);
  1013. }
  1014. if (tc & TC_ARRAY) {
  1015. cn->info |= xS;
  1016. cn->r.n = parse_expr(TC_ARRTERM);
  1017. }
  1018. break;
  1019. case TC_NUMBER:
  1020. case TC_STRING:
  1021. cn->info = OC_VAR;
  1022. v = cn->l.v = xzalloc(sizeof(var));
  1023. if (tc & TC_NUMBER)
  1024. setvar_i(v, t_double);
  1025. else
  1026. setvar_s(v, t_string);
  1027. break;
  1028. case TC_REGEXP:
  1029. mk_re_node(t_string, cn, xzalloc(sizeof(regex_t)*2));
  1030. break;
  1031. case TC_FUNCTION:
  1032. cn->info = OC_FUNC;
  1033. cn->r.f = newfunc(t_string);
  1034. cn->l.n = condition();
  1035. break;
  1036. case TC_SEQSTART:
  1037. cn = vn->r.n = parse_expr(TC_SEQTERM);
  1038. cn->a.n = vn;
  1039. break;
  1040. case TC_GETLINE:
  1041. glptr = cn;
  1042. xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
  1043. break;
  1044. case TC_BUILTIN:
  1045. cn->l.n = condition();
  1046. break;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. return sn.r.n;
  1052. }
  1053. /* add node to chain. Return ptr to alloc'd node */
  1054. static node *chain_node(uint32_t info)
  1055. {
  1056. node *n;
  1057. if (!seq->first)
  1058. seq->first = seq->last = new_node(0);
  1059. if (seq->programname != g_progname) {
  1060. seq->programname = g_progname;
  1061. n = chain_node(OC_NEWSOURCE);
  1062. n->l.s = xstrdup(g_progname);
  1063. }
  1064. n = seq->last;
  1065. n->info = info;
  1066. seq->last = n->a.n = new_node(OC_DONE);
  1067. return n;
  1068. }
  1069. static void chain_expr(uint32_t info)
  1070. {
  1071. node *n;
  1072. n = chain_node(info);
  1073. n->l.n = parse_expr(TC_OPTERM | TC_GRPTERM);
  1074. if (t_tclass & TC_GRPTERM)
  1075. rollback_token();
  1076. }
  1077. static node *chain_loop(node *nn)
  1078. {
  1079. node *n, *n2, *save_brk, *save_cont;
  1080. save_brk = break_ptr;
  1081. save_cont = continue_ptr;
  1082. n = chain_node(OC_BR | Vx);
  1083. continue_ptr = new_node(OC_EXEC);
  1084. break_ptr = new_node(OC_EXEC);
  1085. chain_group();
  1086. n2 = chain_node(OC_EXEC | Vx);
  1087. n2->l.n = nn;
  1088. n2->a.n = n;
  1089. continue_ptr->a.n = n2;
  1090. break_ptr->a.n = n->r.n = seq->last;
  1091. continue_ptr = save_cont;
  1092. break_ptr = save_brk;
  1093. return n;
  1094. }
  1095. /* parse group and attach it to chain */
  1096. static void chain_group(void)
  1097. {
  1098. uint32_t c;
  1099. node *n, *n2, *n3;
  1100. do {
  1101. c = next_token(TC_GRPSEQ);
  1102. } while (c & TC_NEWLINE);
  1103. if (c & TC_GRPSTART) {
  1104. while (next_token(TC_GRPSEQ | TC_GRPTERM) != TC_GRPTERM) {
  1105. if (t_tclass & TC_NEWLINE) continue;
  1106. rollback_token();
  1107. chain_group();
  1108. }
  1109. } else if (c & (TC_OPSEQ | TC_OPTERM)) {
  1110. rollback_token();
  1111. chain_expr(OC_EXEC | Vx);
  1112. } else { /* TC_STATEMNT */
  1113. switch (t_info & OPCLSMASK) {
  1114. case ST_IF:
  1115. n = chain_node(OC_BR | Vx);
  1116. n->l.n = condition();
  1117. chain_group();
  1118. n2 = chain_node(OC_EXEC);
  1119. n->r.n = seq->last;
  1120. if (next_token(TC_GRPSEQ | TC_GRPTERM | TC_ELSE) == TC_ELSE) {
  1121. chain_group();
  1122. n2->a.n = seq->last;
  1123. } else {
  1124. rollback_token();
  1125. }
  1126. break;
  1127. case ST_WHILE:
  1128. n2 = condition();
  1129. n = chain_loop(NULL);
  1130. n->l.n = n2;
  1131. break;
  1132. case ST_DO:
  1133. n2 = chain_node(OC_EXEC);
  1134. n = chain_loop(NULL);
  1135. n2->a.n = n->a.n;
  1136. next_token(TC_WHILE);
  1137. n->l.n = condition();
  1138. break;
  1139. case ST_FOR:
  1140. next_token(TC_SEQSTART);
  1141. n2 = parse_expr(TC_SEMICOL | TC_SEQTERM);
  1142. if (t_tclass & TC_SEQTERM) { /* for-in */
  1143. if ((n2->info & OPCLSMASK) != OC_IN)
  1144. syntax_error(EMSG_UNEXP_TOKEN);
  1145. n = chain_node(OC_WALKINIT | VV);
  1146. n->l.n = n2->l.n;
  1147. n->r.n = n2->r.n;
  1148. n = chain_loop(NULL);
  1149. n->info = OC_WALKNEXT | Vx;
  1150. n->l.n = n2->l.n;
  1151. } else { /* for (;;) */
  1152. n = chain_node(OC_EXEC | Vx);
  1153. n->l.n = n2;
  1154. n2 = parse_expr(TC_SEMICOL);
  1155. n3 = parse_expr(TC_SEQTERM);
  1156. n = chain_loop(n3);
  1157. n->l.n = n2;
  1158. if (!n2)
  1159. n->info = OC_EXEC;
  1160. }
  1161. break;
  1162. case OC_PRINT:
  1163. case OC_PRINTF:
  1164. n = chain_node(t_info);
  1165. n->l.n = parse_expr(TC_OPTERM | TC_OUTRDR | TC_GRPTERM);
  1166. if (t_tclass & TC_OUTRDR) {
  1167. n->info |= t_info;
  1168. n->r.n = parse_expr(TC_OPTERM | TC_GRPTERM);
  1169. }
  1170. if (t_tclass & TC_GRPTERM)
  1171. rollback_token();
  1172. break;
  1173. case OC_BREAK:
  1174. n = chain_node(OC_EXEC);
  1175. n->a.n = break_ptr;
  1176. break;
  1177. case OC_CONTINUE:
  1178. n = chain_node(OC_EXEC);
  1179. n->a.n = continue_ptr;
  1180. break;
  1181. /* delete, next, nextfile, return, exit */
  1182. default:
  1183. chain_expr(t_info);
  1184. }
  1185. }
  1186. }
  1187. static void parse_program(char *p)
  1188. {
  1189. uint32_t tclass;
  1190. node *cn;
  1191. func *f;
  1192. var *v;
  1193. g_pos = p;
  1194. t_lineno = 1;
  1195. while ((tclass = next_token(TC_EOF | TC_OPSEQ | TC_GRPSTART |
  1196. TC_OPTERM | TC_BEGIN | TC_END | TC_FUNCDECL)) != TC_EOF) {
  1197. if (tclass & TC_OPTERM)
  1198. continue;
  1199. seq = &mainseq;
  1200. if (tclass & TC_BEGIN) {
  1201. seq = &beginseq;
  1202. chain_group();
  1203. } else if (tclass & TC_END) {
  1204. seq = &endseq;
  1205. chain_group();
  1206. } else if (tclass & TC_FUNCDECL) {
  1207. next_token(TC_FUNCTION);
  1208. g_pos++;
  1209. f = newfunc(t_string);
  1210. f->body.first = NULL;
  1211. f->nargs = 0;
  1212. while (next_token(TC_VARIABLE | TC_SEQTERM) & TC_VARIABLE) {
  1213. v = findvar(ahash, t_string);
  1214. v->x.aidx = (f->nargs)++;
  1215. if (next_token(TC_COMMA | TC_SEQTERM) & TC_SEQTERM)
  1216. break;
  1217. }
  1218. seq = &(f->body);
  1219. chain_group();
  1220. clear_array(ahash);
  1221. } else if (tclass & TC_OPSEQ) {
  1222. rollback_token();
  1223. cn = chain_node(OC_TEST);
  1224. cn->l.n = parse_expr(TC_OPTERM | TC_EOF | TC_GRPSTART);
  1225. if (t_tclass & TC_GRPSTART) {
  1226. rollback_token();
  1227. chain_group();
  1228. } else {
  1229. chain_node(OC_PRINT);
  1230. }
  1231. cn->r.n = mainseq.last;
  1232. } else /* if (tclass & TC_GRPSTART) */ {
  1233. rollback_token();
  1234. chain_group();
  1235. }
  1236. }
  1237. }
  1238. /* -------- program execution part -------- */
  1239. static node *mk_splitter(const char *s, tsplitter *spl)
  1240. {
  1241. regex_t *re, *ire;
  1242. node *n;
  1243. re = &spl->re[0];
  1244. ire = &spl->re[1];
  1245. n = &spl->n;
  1246. if ((n->info & OPCLSMASK) == OC_REGEXP) {
  1247. regfree(re);
  1248. regfree(ire); // TODO: nuke ire, use re+1?
  1249. }
  1250. if (strlen(s) > 1) {
  1251. mk_re_node(s, n, re);
  1252. } else {
  1253. n->info = (uint32_t) *s;
  1254. }
  1255. return n;
  1256. }
  1257. /* use node as a regular expression. Supplied with node ptr and regex_t
  1258. * storage space. Return ptr to regex (if result points to preg, it should
  1259. * be later regfree'd manually
  1260. */
  1261. static regex_t *as_regex(node *op, regex_t *preg)
  1262. {
  1263. var *v;
  1264. const char *s;
  1265. if ((op->info & OPCLSMASK) == OC_REGEXP) {
  1266. return icase ? op->r.ire : op->l.re;
  1267. }
  1268. v = nvalloc(1);
  1269. s = getvar_s(evaluate(op, v));
  1270. xregcomp(preg, s, icase ? REG_EXTENDED | REG_ICASE : REG_EXTENDED);
  1271. nvfree(v);
  1272. return preg;
  1273. }
  1274. /* gradually increasing buffer */
  1275. static void qrealloc(char **b, int n, int *size)
  1276. {
  1277. if (!*b || n >= *size)
  1278. *b = xrealloc(*b, *size = n + (n>>1) + 80);
  1279. }
  1280. /* resize field storage space */
  1281. static void fsrealloc(int size)
  1282. {
  1283. int i;
  1284. if (size >= maxfields) {
  1285. i = maxfields;
  1286. maxfields = size + 16;
  1287. Fields = xrealloc(Fields, maxfields * sizeof(var));
  1288. for (; i < maxfields; i++) {
  1289. Fields[i].type = VF_SPECIAL;
  1290. Fields[i].string = NULL;
  1291. }
  1292. }
  1293. if (size < nfields) {
  1294. for (i = size; i < nfields; i++) {
  1295. clrvar(Fields + i);
  1296. }
  1297. }
  1298. nfields = size;
  1299. }
  1300. static int awk_split(const char *s, node *spl, char **slist)
  1301. {
  1302. int l, n = 0;
  1303. char c[4];
  1304. char *s1;
  1305. regmatch_t pmatch[2]; // TODO: why [2]? [1] is enough...
  1306. /* in worst case, each char would be a separate field */
  1307. *slist = s1 = xzalloc(strlen(s) * 2 + 3);
  1308. strcpy(s1, s);
  1309. c[0] = c[1] = (char)spl->info;
  1310. c[2] = c[3] = '\0';
  1311. if (*getvar_s(intvar[RS]) == '\0')
  1312. c[2] = '\n';
  1313. if ((spl->info & OPCLSMASK) == OC_REGEXP) { /* regex split */
  1314. if (!*s)
  1315. return n; /* "": zero fields */
  1316. n++; /* at least one field will be there */
  1317. do {
  1318. l = strcspn(s, c+2); /* len till next NUL or \n */
  1319. if (regexec(icase ? spl->r.ire : spl->l.re, s, 1, pmatch, 0) == 0
  1320. && pmatch[0].rm_so <= l
  1321. ) {
  1322. l = pmatch[0].rm_so;
  1323. if (pmatch[0].rm_eo == 0) {
  1324. l++;
  1325. pmatch[0].rm_eo++;
  1326. }
  1327. n++; /* we saw yet another delimiter */
  1328. } else {
  1329. pmatch[0].rm_eo = l;
  1330. if (s[l]) pmatch[0].rm_eo++;
  1331. }
  1332. memcpy(s1, s, l);
  1333. s1[l] = '\0';
  1334. nextword(&s1);
  1335. s += pmatch[0].rm_eo;
  1336. } while (*s);
  1337. return n;
  1338. }
  1339. if (c[0] == '\0') { /* null split */
  1340. while (*s) {
  1341. *s1++ = *s++;
  1342. *s1++ = '\0';
  1343. n++;
  1344. }
  1345. return n;
  1346. }
  1347. if (c[0] != ' ') { /* single-character split */
  1348. if (icase) {
  1349. c[0] = toupper(c[0]);
  1350. c[1] = tolower(c[1]);
  1351. }
  1352. if (*s1) n++;
  1353. while ((s1 = strpbrk(s1, c))) {
  1354. *s1++ = '\0';
  1355. n++;
  1356. }
  1357. return n;
  1358. }
  1359. /* space split */
  1360. while (*s) {
  1361. s = skip_whitespace(s);
  1362. if (!*s) break;
  1363. n++;
  1364. while (*s && !isspace(*s))
  1365. *s1++ = *s++;
  1366. *s1++ = '\0';
  1367. }
  1368. return n;
  1369. }
  1370. static void split_f0(void)
  1371. {
  1372. /* static char *fstrings; */
  1373. #define fstrings (G.split_f0__fstrings)
  1374. int i, n;
  1375. char *s;
  1376. if (is_f0_split)
  1377. return;
  1378. is_f0_split = TRUE;
  1379. free(fstrings);
  1380. fsrealloc(0);
  1381. n = awk_split(getvar_s(intvar[F0]), &fsplitter.n, &fstrings);
  1382. fsrealloc(n);
  1383. s = fstrings;
  1384. for (i = 0; i < n; i++) {
  1385. Fields[i].string = nextword(&s);
  1386. Fields[i].type |= (VF_FSTR | VF_USER | VF_DIRTY);
  1387. }
  1388. /* set NF manually to avoid side effects */
  1389. clrvar(intvar[NF]);
  1390. intvar[NF]->type = VF_NUMBER | VF_SPECIAL;
  1391. intvar[NF]->number = nfields;
  1392. #undef fstrings
  1393. }
  1394. /* perform additional actions when some internal variables changed */
  1395. static void handle_special(var *v)
  1396. {
  1397. int n;
  1398. char *b;
  1399. const char *sep, *s;
  1400. int sl, l, len, i, bsize;
  1401. if (!(v->type & VF_SPECIAL))
  1402. return;
  1403. if (v == intvar[NF]) {
  1404. n = (int)getvar_i(v);
  1405. fsrealloc(n);
  1406. /* recalculate $0 */
  1407. sep = getvar_s(intvar[OFS]);
  1408. sl = strlen(sep);
  1409. b = NULL;
  1410. len = 0;
  1411. for (i = 0; i < n; i++) {
  1412. s = getvar_s(&Fields[i]);
  1413. l = strlen(s);
  1414. if (b) {
  1415. memcpy(b+len, sep, sl);
  1416. len += sl;
  1417. }
  1418. qrealloc(&b, len+l+sl, &bsize);
  1419. memcpy(b+len, s, l);
  1420. len += l;
  1421. }
  1422. if (b)
  1423. b[len] = '\0';
  1424. setvar_p(intvar[F0], b);
  1425. is_f0_split = TRUE;
  1426. } else if (v == intvar[F0]) {
  1427. is_f0_split = FALSE;
  1428. } else if (v == intvar[FS]) {
  1429. mk_splitter(getvar_s(v), &fsplitter);
  1430. } else if (v == intvar[RS]) {
  1431. mk_splitter(getvar_s(v), &rsplitter);
  1432. } else if (v == intvar[IGNORECASE]) {
  1433. icase = istrue(v);
  1434. } else { /* $n */
  1435. n = getvar_i(intvar[NF]);
  1436. setvar_i(intvar[NF], n > v-Fields ? n : v-Fields+1);
  1437. /* right here v is invalid. Just to note... */
  1438. }
  1439. }
  1440. /* step through func/builtin/etc arguments */
  1441. static node *nextarg(node **pn)
  1442. {
  1443. node *n;
  1444. n = *pn;
  1445. if (n && (n->info & OPCLSMASK) == OC_COMMA) {
  1446. *pn = n->r.n;
  1447. n = n->l.n;
  1448. } else {
  1449. *pn = NULL;
  1450. }
  1451. return n;
  1452. }
  1453. static void hashwalk_init(var *v, xhash *array)
  1454. {
  1455. char **w;
  1456. hash_item *hi;
  1457. unsigned i;
  1458. if (v->type & VF_WALK)
  1459. free(v->x.walker);
  1460. v->type |= VF_WALK;
  1461. w = v->x.walker = xzalloc(2 + 2*sizeof(char *) + array->glen);
  1462. w[0] = w[1] = (char *)(w + 2);
  1463. for (i = 0; i < array->csize; i++) {
  1464. hi = array->items[i];
  1465. while (hi) {
  1466. strcpy(*w, hi->name);
  1467. nextword(w);
  1468. hi = hi->next;
  1469. }
  1470. }
  1471. }
  1472. static int hashwalk_next(var *v)
  1473. {
  1474. char **w;
  1475. w = v->x.walker;
  1476. if (w[1] == w[0])
  1477. return FALSE;
  1478. setvar_s(v, nextword(w+1));
  1479. return TRUE;
  1480. }
  1481. /* evaluate node, return 1 when result is true, 0 otherwise */
  1482. static int ptest(node *pattern)
  1483. {
  1484. /* ptest__v is "static": to save stack space? */
  1485. return istrue(evaluate(pattern, &G.ptest__v));
  1486. }
  1487. /* read next record from stream rsm into a variable v */
  1488. static int awk_getline(rstream *rsm, var *v)
  1489. {
  1490. char *b;
  1491. regmatch_t pmatch[2];
  1492. int a, p, pp=0, size;
  1493. int fd, so, eo, r, rp;
  1494. char c, *m, *s;
  1495. /* we're using our own buffer since we need access to accumulating
  1496. * characters
  1497. */
  1498. fd = fileno(rsm->F);
  1499. m = rsm->buffer;
  1500. a = rsm->adv;
  1501. p = rsm->pos;
  1502. size = rsm->size;
  1503. c = (char) rsplitter.n.info;
  1504. rp = 0;
  1505. if (!m) qrealloc(&m, 256, &size);
  1506. do {
  1507. b = m + a;
  1508. so = eo = p;
  1509. r = 1;
  1510. if (p > 0) {
  1511. if ((rsplitter.n.info & OPCLSMASK) == OC_REGEXP) {
  1512. if (regexec(icase ? rsplitter.n.r.ire : rsplitter.n.l.re,
  1513. b, 1, pmatch, 0) == 0) {
  1514. so = pmatch[0].rm_so;
  1515. eo = pmatch[0].rm_eo;
  1516. if (b[eo] != '\0')
  1517. break;
  1518. }
  1519. } else if (c != '\0') {
  1520. s = strchr(b+pp, c);
  1521. if (!s) s = memchr(b+pp, '\0', p - pp);
  1522. if (s) {
  1523. so = eo = s-b;
  1524. eo++;
  1525. break;
  1526. }
  1527. } else {
  1528. while (b[rp] == '\n')
  1529. rp++;
  1530. s = strstr(b+rp, "\n\n");
  1531. if (s) {
  1532. so = eo = s-b;
  1533. while (b[eo] == '\n') eo++;
  1534. if (b[eo] != '\0')
  1535. break;
  1536. }
  1537. }
  1538. }
  1539. if (a > 0) {
  1540. memmove(m, (const void *)(m+a), p+1);
  1541. b = m;
  1542. a = 0;
  1543. }
  1544. qrealloc(&m, a+p+128, &size);
  1545. b = m + a;
  1546. pp = p;
  1547. p += safe_read(fd, b+p, size-p-1);
  1548. if (p < pp) {
  1549. p = 0;
  1550. r = 0;
  1551. setvar_i(intvar[ERRNO], errno);
  1552. }
  1553. b[p] = '\0';
  1554. } while (p > pp);
  1555. if (p == 0) {
  1556. r--;
  1557. } else {
  1558. c = b[so]; b[so] = '\0';
  1559. setvar_s(v, b+rp);
  1560. v->type |= VF_USER;
  1561. b[so] = c;
  1562. c = b[eo]; b[eo] = '\0';
  1563. setvar_s(intvar[RT], b+so);
  1564. b[eo] = c;
  1565. }
  1566. rsm->buffer = m;
  1567. rsm->adv = a + eo;
  1568. rsm->pos = p - eo;
  1569. rsm->size = size;
  1570. return r;
  1571. }
  1572. static int fmt_num(char *b, int size, const char *format, double n, int int_as_int)
  1573. {
  1574. int r = 0;
  1575. char c;
  1576. const char *s = format;
  1577. if (int_as_int && n == (int)n) {
  1578. r = snprintf(b, size, "%d", (int)n);
  1579. } else {
  1580. do { c = *s; } while (c && *++s);
  1581. if (strchr("diouxX", c)) {
  1582. r = snprintf(b, size, format, (int)n);
  1583. } else if (strchr("eEfgG", c)) {
  1584. r = snprintf(b, size, format, n);
  1585. } else {
  1586. syntax_error(EMSG_INV_FMT);
  1587. }
  1588. }
  1589. return r;
  1590. }
  1591. /* formatted output into an allocated buffer, return ptr to buffer */
  1592. static char *awk_printf(node *n)
  1593. {
  1594. char *b = NULL;
  1595. char *fmt, *s, *f;
  1596. const char *s1;
  1597. int i, j, incr, bsize;
  1598. char c, c1;
  1599. var *v, *arg;
  1600. v = nvalloc(1);
  1601. fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), v)));
  1602. i = 0;
  1603. while (*f) {
  1604. s = f;
  1605. while (*f && (*f != '%' || *(++f) == '%'))
  1606. f++;
  1607. while (*f && !isalpha(*f)) {
  1608. if (*f == '*')
  1609. syntax_error("%*x formats are not supported");
  1610. f++;
  1611. }
  1612. incr = (f - s) + MAXVARFMT;
  1613. qrealloc(&b, incr + i, &bsize);
  1614. c = *f;
  1615. if (c != '\0') f++;
  1616. c1 = *f;
  1617. *f = '\0';
  1618. arg = evaluate(nextarg(&n), v);
  1619. j = i;
  1620. if (c == 'c' || !c) {
  1621. i += sprintf(b+i, s, is_numeric(arg) ?
  1622. (char)getvar_i(arg) : *getvar_s(arg));
  1623. } else if (c == 's') {
  1624. s1 = getvar_s(arg);
  1625. qrealloc(&b, incr+i+strlen(s1), &bsize);
  1626. i += sprintf(b+i, s, s1);
  1627. } else {
  1628. i += fmt_num(b+i, incr, s, getvar_i(arg), FALSE);
  1629. }
  1630. *f = c1;
  1631. /* if there was an error while sprintf, return value is negative */
  1632. if (i < j) i = j;
  1633. }
  1634. b = xrealloc(b, i + 1);
  1635. free(fmt);
  1636. nvfree(v);
  1637. b[i] = '\0';
  1638. return b;
  1639. }
  1640. /* common substitution routine
  1641. * replace (nm) substring of (src) that match (n) with (repl), store
  1642. * result into (dest), return number of substitutions. If nm=0, replace
  1643. * all matches. If src or dst is NULL, use $0. If ex=TRUE, enable
  1644. * subexpression matching (\1-\9)
  1645. */
  1646. static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest, int ex)
  1647. {
  1648. char *ds = NULL;
  1649. const char *s;
  1650. const char *sp;
  1651. int c, i, j, di, rl, so, eo, nbs, n, dssize;
  1652. regmatch_t pmatch[10];
  1653. regex_t sreg, *re;
  1654. re = as_regex(rn, &sreg);
  1655. if (!src) src = intvar[F0];
  1656. if (!dest) dest = intvar[F0];
  1657. i = di = 0;
  1658. sp = getvar_s(src);
  1659. rl = strlen(repl);
  1660. while (regexec(re, sp, 10, pmatch, sp==getvar_s(src) ? 0 : REG_NOTBOL) == 0) {
  1661. so = pmatch[0].rm_so;
  1662. eo = pmatch[0].rm_eo;
  1663. qrealloc(&ds, di + eo + rl, &dssize);
  1664. memcpy(ds + di, sp, eo);
  1665. di += eo;
  1666. if (++i >= nm) {
  1667. /* replace */
  1668. di -= (eo - so);
  1669. nbs = 0;
  1670. for (s = repl; *s; s++) {
  1671. ds[di++] = c = *s;
  1672. if (c == '\\') {
  1673. nbs++;
  1674. continue;
  1675. }
  1676. if (c == '&' || (ex && c >= '0' && c <= '9')) {
  1677. di -= ((nbs + 3) >> 1);
  1678. j = 0;
  1679. if (c != '&') {
  1680. j = c - '0';
  1681. nbs++;
  1682. }
  1683. if (nbs % 2) {
  1684. ds[di++] = c;
  1685. } else {
  1686. n = pmatch[j].rm_eo - pmatch[j].rm_so;
  1687. qrealloc(&ds, di + rl + n, &dssize);
  1688. memcpy(ds + di, sp + pmatch[j].rm_so, n);
  1689. di += n;
  1690. }
  1691. }
  1692. nbs = 0;
  1693. }
  1694. }
  1695. sp += eo;
  1696. if (i == nm) break;
  1697. if (eo == so) {
  1698. ds[di] = *sp++;
  1699. if (!ds[di++]) break;
  1700. }
  1701. }
  1702. qrealloc(&ds, di + strlen(sp), &dssize);
  1703. strcpy(ds + di, sp);
  1704. setvar_p(dest, ds);
  1705. if (re == &sreg) regfree(re);
  1706. return i;
  1707. }
  1708. static var *exec_builtin(node *op, var *res)
  1709. {
  1710. #define tspl (G.exec_builtin__tspl)
  1711. int (*to_xxx)(int);
  1712. var *tv;
  1713. node *an[4];
  1714. var *av[4];
  1715. const char *as[4];
  1716. regmatch_t pmatch[2];
  1717. regex_t sreg, *re;
  1718. node *spl;
  1719. uint32_t isr, info;
  1720. int nargs;
  1721. time_t tt;
  1722. char *s, *s1;
  1723. int i, l, ll, n;
  1724. tv = nvalloc(4);
  1725. isr = info = op->info;
  1726. op = op->l.n;
  1727. av[2] = av[3] = NULL;
  1728. for (i = 0; i < 4 && op; i++) {
  1729. an[i] = nextarg(&op);
  1730. if (isr & 0x09000000) av[i] = evaluate(an[i], &tv[i]);
  1731. if (isr & 0x08000000) as[i] = getvar_s(av[i]);
  1732. isr >>= 1;
  1733. }
  1734. nargs = i;
  1735. if ((uint32_t)nargs < (info >> 30))
  1736. syntax_error(EMSG_TOO_FEW_ARGS);
  1737. switch (info & OPNMASK) {
  1738. case B_a2:
  1739. #if ENABLE_FEATURE_AWK_MATH
  1740. setvar_i(res, atan2(getvar_i(av[i]), getvar_i(av[1])));
  1741. #else
  1742. syntax_error(EMSG_NO_MATH);
  1743. #endif
  1744. break;
  1745. case B_sp:
  1746. if (nargs > 2) {
  1747. spl = (an[2]->info & OPCLSMASK) == OC_REGEXP ?
  1748. an[2] : mk_splitter(getvar_s(evaluate(an[2], &tv[2])), &tspl);
  1749. } else {
  1750. spl = &fsplitter.n;
  1751. }
  1752. n = awk_split(as[0], spl, &s);
  1753. s1 = s;
  1754. clear_array(iamarray(av[1]));
  1755. for (i=1; i<=n; i++)
  1756. setari_u(av[1], i, nextword(&s1));
  1757. free(s);
  1758. setvar_i(res, n);
  1759. break;
  1760. case B_ss:
  1761. l = strlen(as[0]);
  1762. i = getvar_i(av[1]) - 1;
  1763. if (i > l) i = l;
  1764. if (i < 0) i = 0;
  1765. n = (nargs > 2) ? getvar_i(av[2]) : l-i;
  1766. if (n < 0) n = 0;
  1767. s = xmalloc(n+1);
  1768. strncpy(s, as[0]+i, n);
  1769. s[n] = '\0';
  1770. setvar_p(res, s);
  1771. break;
  1772. case B_an:
  1773. setvar_i(res, (long)getvar_i(av[0]) & (long)getvar_i(av[1]));
  1774. break;
  1775. case B_co:
  1776. setvar_i(res, ~(long)getvar_i(av[0]));
  1777. break;
  1778. case B_ls:
  1779. setvar_i(res, (long)getvar_i(av[0]) << (long)getvar_i(av[1]));
  1780. break;
  1781. case B_or:
  1782. setvar_i(res, (long)getvar_i(av[0]) | (long)getvar_i(av[1]));
  1783. break;
  1784. case B_rs:
  1785. setvar_i(res, (long)((unsigned long)getvar_i(av[0]) >> (unsigned long)getvar_i(av[1])));
  1786. break;
  1787. case B_xo:
  1788. setvar_i(res, (long)getvar_i(av[0]) ^ (long)getvar_i(av[1]));
  1789. break;
  1790. case B_lo:
  1791. to_xxx = tolower;
  1792. goto lo_cont;
  1793. case B_up:
  1794. to_xxx = toupper;
  1795. lo_cont:
  1796. s1 = s = xstrdup(as[0]);
  1797. while (*s1) {
  1798. *s1 = (*to_xxx)(*s1);
  1799. s1++;
  1800. }
  1801. setvar_p(res, s);
  1802. break;
  1803. case B_ix:
  1804. n = 0;
  1805. ll = strlen(as[1]);
  1806. l = strlen(as[0]) - ll;
  1807. if (ll > 0 && l >= 0) {
  1808. if (!icase) {
  1809. s = strstr(as[0], as[1]);
  1810. if (s) n = (s - as[0]) + 1;
  1811. } else {
  1812. /* this piece of code is terribly slow and
  1813. * really should be rewritten
  1814. */
  1815. for (i=0; i<=l; i++) {
  1816. if (strncasecmp(as[0]+i, as[1], ll) == 0) {
  1817. n = i+1;
  1818. break;
  1819. }
  1820. }
  1821. }
  1822. }
  1823. setvar_i(res, n);
  1824. break;
  1825. case B_ti:
  1826. if (nargs > 1)
  1827. tt = getvar_i(av[1]);
  1828. else
  1829. time(&tt);
  1830. //s = (nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y";
  1831. i = strftime(g_buf, MAXVARFMT,
  1832. ((nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y"),
  1833. localtime(&tt));
  1834. g_buf[i] = '\0';
  1835. setvar_s(res, g_buf);
  1836. break;
  1837. case B_ma:
  1838. re = as_regex(an[1], &sreg);
  1839. n = regexec(re, as[0], 1, pmatch, 0);
  1840. if (n == 0) {
  1841. pmatch[0].rm_so++;
  1842. pmatch[0].rm_eo++;
  1843. } else {
  1844. pmatch[0].rm_so = 0;
  1845. pmatch[0].rm_eo = -1;
  1846. }
  1847. setvar_i(newvar("RSTART"), pmatch[0].rm_so);
  1848. setvar_i(newvar("RLENGTH"), pmatch[0].rm_eo - pmatch[0].rm_so);
  1849. setvar_i(res, pmatch[0].rm_so);
  1850. if (re == &sreg) regfree(re);
  1851. break;
  1852. case B_ge:
  1853. awk_sub(an[0], as[1], getvar_i(av[2]), av[3], res, TRUE);
  1854. break;
  1855. case B_gs:
  1856. setvar_i(res, awk_sub(an[0], as[1], 0, av[2], av[2], FALSE));
  1857. break;
  1858. case B_su:
  1859. setvar_i(res, awk_sub(an[0], as[1], 1, av[2], av[2], FALSE));
  1860. break;
  1861. }
  1862. nvfree(tv);
  1863. return res;
  1864. #undef tspl
  1865. }
  1866. /*
  1867. * Evaluate node - the heart of the program. Supplied with subtree
  1868. * and place where to store result. returns ptr to result.
  1869. */
  1870. #define XC(n) ((n) >> 8)
  1871. static var *evaluate(node *op, var *res)
  1872. {
  1873. /* This procedure is recursive so we should count every byte */
  1874. #define fnargs (G.evaluate__fnargs)
  1875. /* seed is initialized to 1 */
  1876. #define seed (G.evaluate__seed)
  1877. #define sreg (G.evaluate__sreg)
  1878. node *op1;
  1879. var *v1;
  1880. union {
  1881. var *v;
  1882. const char *s;
  1883. double d;
  1884. int i;
  1885. } L, R;
  1886. uint32_t opinfo;
  1887. int opn;
  1888. union {
  1889. char *s;
  1890. rstream *rsm;
  1891. FILE *F;
  1892. var *v;
  1893. regex_t *re;
  1894. uint32_t info;
  1895. } X;
  1896. if (!op)
  1897. return setvar_s(res, NULL);
  1898. v1 = nvalloc(2);
  1899. while (op) {
  1900. opinfo = op->info;
  1901. opn = (opinfo & OPNMASK);
  1902. g_lineno = op->lineno;
  1903. /* execute inevitable things */
  1904. op1 = op->l.n;
  1905. if (opinfo & OF_RES1) X.v = L.v = evaluate(op1, v1);
  1906. if (opinfo & OF_RES2) R.v = evaluate(op->r.n, v1+1);
  1907. if (opinfo & OF_STR1) L.s = getvar_s(L.v);
  1908. if (opinfo & OF_STR2) R.s = getvar_s(R.v);
  1909. if (opinfo & OF_NUM1) L.d = getvar_i(L.v);
  1910. switch (XC(opinfo & OPCLSMASK)) {
  1911. /* -- iterative node type -- */
  1912. /* test pattern */
  1913. case XC( OC_TEST ):
  1914. if ((op1->info & OPCLSMASK) == OC_COMMA) {
  1915. /* it's range pattern */
  1916. if ((opinfo & OF_CHECKED) || ptest(op1->l.n)) {
  1917. op->info |= OF_CHECKED;
  1918. if (ptest(op1->r.n))
  1919. op->info &= ~OF_CHECKED;
  1920. op = op->a.n;
  1921. } else {
  1922. op = op->r.n;
  1923. }
  1924. } else {
  1925. op = (ptest(op1)) ? op->a.n : op->r.n;
  1926. }
  1927. break;
  1928. /* just evaluate an expression, also used as unconditional jump */
  1929. case XC( OC_EXEC ):
  1930. break;
  1931. /* branch, used in if-else and various loops */
  1932. case XC( OC_BR ):
  1933. op = istrue(L.v) ? op->a.n : op->r.n;
  1934. break;
  1935. /* initialize for-in loop */
  1936. case XC( OC_WALKINIT ):
  1937. hashwalk_init(L.v, iamarray(R.v));
  1938. break;
  1939. /* get next array item */
  1940. case XC( OC_WALKNEXT ):
  1941. op = hashwalk_next(L.v) ? op->a.n : op->r.n;
  1942. break;
  1943. case XC( OC_PRINT ):
  1944. case XC( OC_PRINTF ):
  1945. X.F = stdout;
  1946. if (op->r.n) {
  1947. X.rsm = newfile(R.s);
  1948. if (!X.rsm->F) {
  1949. if (opn == '|') {
  1950. X.rsm->F = popen(R.s, "w");
  1951. if (X.rsm->F == NULL)
  1952. bb_perror_msg_and_die("popen");
  1953. X.rsm->is_pipe = 1;
  1954. } else {
  1955. X.rsm->F = xfopen(R.s, opn=='w' ? "w" : "a");
  1956. }
  1957. }
  1958. X.F = X.rsm->F;
  1959. }
  1960. if ((opinfo & OPCLSMASK) == OC_PRINT) {
  1961. if (!op1) {
  1962. fputs(getvar_s(intvar[F0]), X.F);
  1963. } else {
  1964. while (op1) {
  1965. L.v = evaluate(nextarg(&op1), v1);
  1966. if (L.v->type & VF_NUMBER) {
  1967. fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[OFMT]),
  1968. getvar_i(L.v), TRUE);
  1969. fputs(g_buf, X.F);
  1970. } else {
  1971. fputs(getvar_s(L.v), X.F);
  1972. }
  1973. if (op1) fputs(getvar_s(intvar[OFS]), X.F);
  1974. }
  1975. }
  1976. fputs(getvar_s(intvar[ORS]), X.F);
  1977. } else { /* OC_PRINTF */
  1978. L.s = awk_printf(op1);
  1979. fputs(L.s, X.F);
  1980. free((char*)L.s);
  1981. }
  1982. fflush(X.F);
  1983. break;
  1984. case XC( OC_DELETE ):
  1985. X.info = op1->info & OPCLSMASK;
  1986. if (X.info == OC_VAR) {
  1987. R.v = op1->l.v;
  1988. } else if (X.info == OC_FNARG) {
  1989. R.v = &fnargs[op1->l.i];
  1990. } else {
  1991. syntax_error(EMSG_NOT_ARRAY);
  1992. }
  1993. if (op1->r.n) {
  1994. clrvar(L.v);
  1995. L.s = getvar_s(evaluate(op1->r.n, v1));
  1996. hash_remove(iamarray(R.v), L.s);
  1997. } else {
  1998. clear_array(iamarray(R.v));
  1999. }
  2000. break;
  2001. case XC( OC_NEWSOURCE ):
  2002. g_progname = op->l.s;
  2003. break;
  2004. case XC( OC_RETURN ):
  2005. copyvar(res, L.v);
  2006. break;
  2007. case XC( OC_NEXTFILE ):
  2008. nextfile = TRUE;
  2009. case XC( OC_NEXT ):
  2010. nextrec = TRUE;
  2011. case XC( OC_DONE ):
  2012. clrvar(res);
  2013. break;
  2014. case XC( OC_EXIT ):
  2015. awk_exit(L.d);
  2016. /* -- recursive node type -- */
  2017. case XC( OC_VAR ):
  2018. L.v = op->l.v;
  2019. if (L.v == intvar[NF])
  2020. split_f0();
  2021. goto v_cont;
  2022. case XC( OC_FNARG ):
  2023. L.v = &fnargs[op->l.i];
  2024. v_cont:
  2025. res = op->r.n ? findvar(iamarray(L.v), R.s) : L.v;
  2026. break;
  2027. case XC( OC_IN ):
  2028. setvar_i(res, hash_search(iamarray(R.v), L.s) ? 1 : 0);
  2029. break;
  2030. case XC( OC_REGEXP ):
  2031. op1 = op;
  2032. L.s = getvar_s(intvar[F0]);
  2033. goto re_cont;
  2034. case XC( OC_MATCH ):
  2035. op1 = op->r.n;
  2036. re_cont:
  2037. X.re = as_regex(op1, &sreg);
  2038. R.i = regexec(X.re, L.s, 0, NULL, 0);
  2039. if (X.re == &sreg) regfree(X.re);
  2040. setvar_i(res, (R.i == 0 ? 1 : 0) ^ (opn == '!' ? 1 : 0));
  2041. break;
  2042. case XC( OC_MOVE ):
  2043. /* if source is a temporary string, jusk relink it to dest */
  2044. if (R.v == v1+1 && R.v->string) {
  2045. res = setvar_p(L.v, R.v->string);
  2046. R.v->string = NULL;
  2047. } else {
  2048. res = copyvar(L.v, R.v);
  2049. }
  2050. break;
  2051. case XC( OC_TERNARY ):
  2052. if ((op->r.n->info & OPCLSMASK) != OC_COLON)
  2053. syntax_error(EMSG_POSSIBLE_ERROR);
  2054. res = evaluate(istrue(L.v) ? op->r.n->l.n : op->r.n->r.n, res);
  2055. break;
  2056. case XC( OC_FUNC ):
  2057. if (!op->r.f->body.first)
  2058. syntax_error(EMSG_UNDEF_FUNC);
  2059. X.v = R.v = nvalloc(op->r.f->nargs+1);
  2060. while (op1) {
  2061. L.v = evaluate(nextarg(&op1), v1);
  2062. copyvar(R.v, L.v);
  2063. R.v->type |= VF_CHILD;
  2064. R.v->x.parent = L.v;
  2065. if (++R.v - X.v >= op->r.f->nargs)
  2066. break;
  2067. }
  2068. R.v = fnargs;
  2069. fnargs = X.v;
  2070. L.s = g_progname;
  2071. res = evaluate(op->r.f->body.first, res);
  2072. g_progname = L.s;
  2073. nvfree(fnargs);
  2074. fnargs = R.v;
  2075. break;
  2076. case XC( OC_GETLINE ):
  2077. case XC( OC_PGETLINE ):
  2078. if (op1) {
  2079. X.rsm = newfile(L.s);
  2080. if (!X.rsm->F) {
  2081. if ((opinfo & OPCLSMASK) == OC_PGETLINE) {
  2082. X.rsm->F = popen(L.s, "r");
  2083. X.rsm->is_pipe = TRUE;
  2084. } else {
  2085. X.rsm->F = fopen(L.s, "r"); /* not xfopen! */
  2086. }
  2087. }
  2088. } else {
  2089. if (!iF) iF = next_input_file();
  2090. X.rsm = iF;
  2091. }
  2092. if (!X.rsm->F) {
  2093. setvar_i(intvar[ERRNO], errno);
  2094. setvar_i(res, -1);
  2095. break;
  2096. }
  2097. if (!op->r.n)
  2098. R.v = intvar[F0];
  2099. L.i = awk_getline(X.rsm, R.v);
  2100. if (L.i > 0) {
  2101. if (!op1) {
  2102. incvar(intvar[FNR]);
  2103. incvar(intvar[NR]);
  2104. }
  2105. }
  2106. setvar_i(res, L.i);
  2107. break;
  2108. /* simple builtins */
  2109. case XC( OC_FBLTIN ):
  2110. switch (opn) {
  2111. case F_in:
  2112. R.d = (int)L.d;
  2113. break;
  2114. case F_rn:
  2115. R.d = (double)rand() / (double)RAND_MAX;
  2116. break;
  2117. #if ENABLE_FEATURE_AWK_MATH
  2118. case F_co:
  2119. R.d = cos(L.d);
  2120. break;
  2121. case F_ex:
  2122. R.d = exp(L.d);
  2123. break;
  2124. case F_lg:
  2125. R.d = log(L.d);
  2126. break;
  2127. case F_si:
  2128. R.d = sin(L.d);
  2129. break;
  2130. case F_sq:
  2131. R.d = sqrt(L.d);
  2132. break;
  2133. #else
  2134. case F_co:
  2135. case F_ex:
  2136. case F_lg:
  2137. case F_si:
  2138. case F_sq:
  2139. syntax_error(EMSG_NO_MATH);
  2140. break;
  2141. #endif
  2142. case F_sr:
  2143. R.d = (double)seed;
  2144. seed = op1 ? (unsigned)L.d : (unsigned)time(NULL);
  2145. srand(seed);
  2146. break;
  2147. case F_ti:
  2148. R.d = time(NULL);
  2149. break;
  2150. case F_le:
  2151. if (!op1)
  2152. L.s = getvar_s(intvar[F0]);
  2153. R.d = strlen(L.s);
  2154. break;
  2155. case F_sy:
  2156. fflush(NULL);
  2157. R.d = (ENABLE_FEATURE_ALLOW_EXEC && L.s && *L.s)
  2158. ? (system(L.s) >> 8) : 0;
  2159. break;
  2160. case F_ff:
  2161. if (!op1)
  2162. fflush(stdout);
  2163. else {
  2164. if (L.s && *L.s) {
  2165. X.rsm = newfile(L.s);
  2166. fflush(X.rsm->F);
  2167. } else {
  2168. fflush(NULL);
  2169. }
  2170. }
  2171. break;
  2172. case F_cl:
  2173. X.rsm = (rstream *)hash_search(fdhash, L.s);
  2174. if (X.rsm) {
  2175. R.i = X.rsm->is_pipe ? pclose(X.rsm->F) : fclose(X.rsm->F);
  2176. free(X.rsm->buffer);
  2177. hash_remove(fdhash, L.s);
  2178. }
  2179. if (R.i != 0)
  2180. setvar_i(intvar[ERRNO], errno);
  2181. R.d = (double)R.i;
  2182. break;
  2183. }
  2184. setvar_i(res, R.d);
  2185. break;
  2186. case XC( OC_BUILTIN ):
  2187. res = exec_builtin(op, res);
  2188. break;
  2189. case XC( OC_SPRINTF ):
  2190. setvar_p(res, awk_printf(op1));
  2191. break;
  2192. case XC( OC_UNARY ):
  2193. X.v = R.v;
  2194. L.d = R.d = getvar_i(R.v);
  2195. switch (opn) {
  2196. case 'P':
  2197. L.d = ++R.d;
  2198. goto r_op_change;
  2199. case 'p':
  2200. R.d++;
  2201. goto r_op_change;
  2202. case 'M':
  2203. L.d = --R.d;
  2204. goto r_op_change;
  2205. case 'm':
  2206. R.d--;
  2207. goto r_op_change;
  2208. case '!':
  2209. L.d = istrue(X.v) ? 0 : 1;
  2210. break;
  2211. case '-':
  2212. L.d = -R.d;
  2213. break;
  2214. r_op_change:
  2215. setvar_i(X.v, R.d);
  2216. }
  2217. setvar_i(res, L.d);
  2218. break;
  2219. case XC( OC_FIELD ):
  2220. R.i = (int)getvar_i(R.v);
  2221. if (R.i == 0) {
  2222. res = intvar[F0];
  2223. } else {
  2224. split_f0();
  2225. if (R.i > nfields)
  2226. fsrealloc(R.i);
  2227. res = &Fields[R.i - 1];
  2228. }
  2229. break;
  2230. /* concatenation (" ") and index joining (",") */
  2231. case XC( OC_CONCAT ):
  2232. case XC( OC_COMMA ):
  2233. opn = strlen(L.s) + strlen(R.s) + 2;
  2234. X.s = xmalloc(opn);
  2235. strcpy(X.s, L.s);
  2236. if ((opinfo & OPCLSMASK) == OC_COMMA) {
  2237. L.s = getvar_s(intvar[SUBSEP]);
  2238. X.s = xrealloc(X.s, opn + strlen(L.s));
  2239. strcat(X.s, L.s);
  2240. }
  2241. strcat(X.s, R.s);
  2242. setvar_p(res, X.s);
  2243. break;
  2244. case XC( OC_LAND ):
  2245. setvar_i(res, istrue(L.v) ? ptest(op->r.n) : 0);
  2246. break;
  2247. case XC( OC_LOR ):
  2248. setvar_i(res, istrue(L.v) ? 1 : ptest(op->r.n));
  2249. break;
  2250. case XC( OC_BINARY ):
  2251. case XC( OC_REPLACE ):
  2252. R.d = getvar_i(R.v);
  2253. switch (opn) {
  2254. case '+':
  2255. L.d += R.d;
  2256. break;
  2257. case '-':
  2258. L.d -= R.d;
  2259. break;
  2260. case '*':
  2261. L.d *= R.d;
  2262. break;
  2263. case '/':
  2264. if (R.d == 0) syntax_error(EMSG_DIV_BY_ZERO);
  2265. L.d /= R.d;
  2266. break;
  2267. case '&':
  2268. #if ENABLE_FEATURE_AWK_MATH
  2269. L.d = pow(L.d, R.d);
  2270. #else
  2271. syntax_error(EMSG_NO_MATH);
  2272. #endif
  2273. break;
  2274. case '%':
  2275. if (R.d == 0) syntax_error(EMSG_DIV_BY_ZERO);
  2276. L.d -= (int)(L.d / R.d) * R.d;
  2277. break;
  2278. }
  2279. res = setvar_i(((opinfo & OPCLSMASK) == OC_BINARY) ? res : X.v, L.d);
  2280. break;
  2281. case XC( OC_COMPARE ):
  2282. if (is_numeric(L.v) && is_numeric(R.v)) {
  2283. L.d = getvar_i(L.v) - getvar_i(R.v);
  2284. } else {
  2285. L.s = getvar_s(L.v);
  2286. R.s = getvar_s(R.v);
  2287. L.d = icase ? strcasecmp(L.s, R.s) : strcmp(L.s, R.s);
  2288. }
  2289. switch (opn & 0xfe) {
  2290. case 0:
  2291. R.i = (L.d > 0);
  2292. break;
  2293. case 2:
  2294. R.i = (L.d >= 0);
  2295. break;
  2296. case 4:
  2297. R.i = (L.d == 0);
  2298. break;
  2299. }
  2300. setvar_i(res, (opn & 0x1 ? R.i : !R.i) ? 1 : 0);
  2301. break;
  2302. default:
  2303. syntax_error(EMSG_POSSIBLE_ERROR);
  2304. }
  2305. if ((opinfo & OPCLSMASK) <= SHIFT_TIL_THIS)
  2306. op = op->a.n;
  2307. if ((opinfo & OPCLSMASK) >= RECUR_FROM_THIS)
  2308. break;
  2309. if (nextrec)
  2310. break;
  2311. }
  2312. nvfree(v1);
  2313. return res;
  2314. #undef fnargs
  2315. #undef seed
  2316. #undef sreg
  2317. }
  2318. /* -------- main & co. -------- */
  2319. static int awk_exit(int r)
  2320. {
  2321. var tv;
  2322. unsigned i;
  2323. hash_item *hi;
  2324. zero_out_var(&tv);
  2325. if (!exiting) {
  2326. exiting = TRUE;
  2327. nextrec = FALSE;
  2328. evaluate(endseq.first, &tv);
  2329. }
  2330. /* waiting for children */
  2331. for (i = 0; i < fdhash->csize; i++) {
  2332. hi = fdhash->items[i];
  2333. while (hi) {
  2334. if (hi->data.rs.F && hi->data.rs.is_pipe)
  2335. pclose(hi->data.rs.F);
  2336. hi = hi->next;
  2337. }
  2338. }
  2339. exit(r);
  2340. }
  2341. /* if expr looks like "var=value", perform assignment and return 1,
  2342. * otherwise return 0 */
  2343. static int is_assignment(const char *expr)
  2344. {
  2345. char *exprc, *s, *s0, *s1;
  2346. exprc = xstrdup(expr);
  2347. if (!isalnum_(*exprc) || (s = strchr(exprc, '=')) == NULL) {
  2348. free(exprc);
  2349. return FALSE;
  2350. }
  2351. *(s++) = '\0';
  2352. s0 = s1 = s;
  2353. while (*s)
  2354. *(s1++) = nextchar(&s);
  2355. *s1 = '\0';
  2356. setvar_u(newvar(exprc), s0);
  2357. free(exprc);
  2358. return TRUE;
  2359. }
  2360. /* switch to next input file */
  2361. static rstream *next_input_file(void)
  2362. {
  2363. #define rsm (G.next_input_file__rsm)
  2364. #define files_happen (G.next_input_file__files_happen)
  2365. FILE *F = NULL;
  2366. const char *fname, *ind;
  2367. if (rsm.F) fclose(rsm.F);
  2368. rsm.F = NULL;
  2369. rsm.pos = rsm.adv = 0;
  2370. do {
  2371. if (getvar_i(intvar[ARGIND])+1 >= getvar_i(intvar[ARGC])) {
  2372. if (files_happen)
  2373. return NULL;
  2374. fname = "-";
  2375. F = stdin;
  2376. } else {
  2377. ind = getvar_s(incvar(intvar[ARGIND]));
  2378. fname = getvar_s(findvar(iamarray(intvar[ARGV]), ind));
  2379. if (fname && *fname && !is_assignment(fname))
  2380. F = xfopen_stdin(fname);
  2381. }
  2382. } while (!F);
  2383. files_happen = TRUE;
  2384. setvar_s(intvar[FILENAME], fname);
  2385. rsm.F = F;
  2386. return &rsm;
  2387. #undef rsm
  2388. #undef files_happen
  2389. }
  2390. int awk_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  2391. int awk_main(int argc, char **argv)
  2392. {
  2393. unsigned opt;
  2394. char *opt_F, *opt_W;
  2395. llist_t *list_v = NULL;
  2396. llist_t *list_f = NULL;
  2397. int i, j;
  2398. var *v;
  2399. var tv;
  2400. char **envp;
  2401. char *vnames = (char *)vNames; /* cheat */
  2402. char *vvalues = (char *)vValues;
  2403. INIT_G();
  2404. /* Undo busybox.c, or else strtod may eat ','! This breaks parsing:
  2405. * $1,$2 == '$1,' '$2', NOT '$1' ',' '$2' */
  2406. if (ENABLE_LOCALE_SUPPORT)
  2407. setlocale(LC_NUMERIC, "C");
  2408. zero_out_var(&tv);
  2409. /* allocate global buffer */
  2410. g_buf = xmalloc(MAXVARFMT + 1);
  2411. vhash = hash_init();
  2412. ahash = hash_init();
  2413. fdhash = hash_init();
  2414. fnhash = hash_init();
  2415. /* initialize variables */
  2416. for (i = 0; *vnames; i++) {
  2417. intvar[i] = v = newvar(nextword(&vnames));
  2418. if (*vvalues != '\377')
  2419. setvar_s(v, nextword(&vvalues));
  2420. else
  2421. setvar_i(v, 0);
  2422. if (*vnames == '*') {
  2423. v->type |= VF_SPECIAL;
  2424. vnames++;
  2425. }
  2426. }
  2427. handle_special(intvar[FS]);
  2428. handle_special(intvar[RS]);
  2429. newfile("/dev/stdin")->F = stdin;
  2430. newfile("/dev/stdout")->F = stdout;
  2431. newfile("/dev/stderr")->F = stderr;
  2432. /* Huh, people report that sometimes environ is NULL. Oh well. */
  2433. if (environ) for (envp = environ; *envp; envp++) {
  2434. /* environ is writable, thus we don't strdup it needlessly */
  2435. char *s = *envp;
  2436. char *s1 = strchr(s, '=');
  2437. if (s1) {
  2438. *s1 = '\0';
  2439. /* Both findvar and setvar_u take const char*
  2440. * as 2nd arg -> environment is not trashed */
  2441. setvar_u(findvar(iamarray(intvar[ENVIRON]), s), s1 + 1);
  2442. *s1 = '=';
  2443. }
  2444. }
  2445. opt_complementary = "v::f::"; /* -v and -f can occur multiple times */
  2446. opt = getopt32(argv, "F:v:f:W:", &opt_F, &list_v, &list_f, &opt_W);
  2447. argv += optind;
  2448. argc -= optind;
  2449. if (opt & 0x1)
  2450. setvar_s(intvar[FS], opt_F); // -F
  2451. while (list_v) { /* -v */
  2452. if (!is_assignment(llist_pop(&list_v)))
  2453. bb_show_usage();
  2454. }
  2455. if (list_f) { /* -f */
  2456. do {
  2457. char *s = NULL;
  2458. FILE *from_file;
  2459. g_progname = llist_pop(&list_f);
  2460. from_file = xfopen_stdin(g_progname);
  2461. /* one byte is reserved for some trick in next_token */
  2462. for (i = j = 1; j > 0; i += j) {
  2463. s = xrealloc(s, i + 4096);
  2464. j = fread(s + i, 1, 4094, from_file);
  2465. }
  2466. s[i] = '\0';
  2467. fclose(from_file);
  2468. parse_program(s + 1);
  2469. free(s);
  2470. } while (list_f);
  2471. } else { // no -f: take program from 1st parameter
  2472. if (!argc)
  2473. bb_show_usage();
  2474. g_progname = "cmd. line";
  2475. parse_program(*argv++);
  2476. argc--;
  2477. }
  2478. if (opt & 0x8) // -W
  2479. bb_error_msg("warning: unrecognized option '-W %s' ignored", opt_W);
  2480. /* fill in ARGV array */
  2481. setvar_i(intvar[ARGC], argc + 1);
  2482. setari_u(intvar[ARGV], 0, "awk");
  2483. i = 0;
  2484. while (*argv)
  2485. setari_u(intvar[ARGV], ++i, *argv++);
  2486. evaluate(beginseq.first, &tv);
  2487. if (!mainseq.first && !endseq.first)
  2488. awk_exit(EXIT_SUCCESS);
  2489. /* input file could already be opened in BEGIN block */
  2490. if (!iF) iF = next_input_file();
  2491. /* passing through input files */
  2492. while (iF) {
  2493. nextfile = FALSE;
  2494. setvar_i(intvar[FNR], 0);
  2495. while ((i = awk_getline(iF, intvar[F0])) > 0) {
  2496. nextrec = FALSE;
  2497. incvar(intvar[NR]);
  2498. incvar(intvar[FNR]);
  2499. evaluate(mainseq.first, &tv);
  2500. if (nextfile)
  2501. break;
  2502. }
  2503. if (i < 0)
  2504. syntax_error(strerror(errno));
  2505. iF = next_input_file();
  2506. }
  2507. awk_exit(EXIT_SUCCESS);
  2508. /*return 0;*/
  2509. }