awk.c 64 KB

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