awk.c 58 KB

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