awk.c 58 KB

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