awk.c 58 KB

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