awk.c 75 KB

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