awk.c 76 KB

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