3
0

awk.c 69 KB

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