3
0

awk.c 65 KB

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