awk.c 79 KB

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