awk.c 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338
  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[] = {
  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. break;
  1208. case TC_REGEXP:
  1209. debug_printf_parse("%s: TC_REGEXP\n", __func__);
  1210. mk_re_node(t_string, cn, xzalloc(sizeof(regex_t)*2));
  1211. break;
  1212. case TC_FUNCTION:
  1213. debug_printf_parse("%s: TC_FUNCTION\n", __func__);
  1214. cn->info = OC_FUNC;
  1215. cn->r.f = newfunc(t_string);
  1216. cn->l.n = condition();
  1217. break;
  1218. case TC_SEQSTART:
  1219. debug_printf_parse("%s: TC_SEQSTART\n", __func__);
  1220. cn = vn->r.n = parse_expr(TC_SEQTERM);
  1221. if (!cn)
  1222. syntax_error("Empty sequence");
  1223. cn->a.n = vn;
  1224. break;
  1225. case TC_GETLINE:
  1226. debug_printf_parse("%s: TC_GETLINE\n", __func__);
  1227. glptr = cn;
  1228. xtc = TC_OPERAND | TC_UOPPRE | TC_BINOP | iexp;
  1229. break;
  1230. case TC_BUILTIN:
  1231. debug_printf_parse("%s: TC_BUILTIN\n", __func__);
  1232. cn->l.n = condition();
  1233. break;
  1234. case TC_LENGTH:
  1235. debug_printf_parse("%s: TC_LENGTH\n", __func__);
  1236. next_token(TC_SEQSTART /* length(...) */
  1237. | TC_OPTERM /* length; (or newline)*/
  1238. | TC_GRPTERM /* length } */
  1239. | TC_BINOPX /* length <op> NUM */
  1240. | TC_COMMA /* print length, 1 */
  1241. );
  1242. rollback_token();
  1243. if (t_tclass & TC_SEQSTART) {
  1244. /* It was a "(" token. Handle just like TC_BUILTIN */
  1245. cn->l.n = condition();
  1246. }
  1247. break;
  1248. }
  1249. }
  1250. }
  1251. }
  1252. debug_printf_parse("%s() returns %p\n", __func__, sn.r.n);
  1253. return sn.r.n;
  1254. }
  1255. /* add node to chain. Return ptr to alloc'd node */
  1256. static node *chain_node(uint32_t info)
  1257. {
  1258. node *n;
  1259. if (!seq->first)
  1260. seq->first = seq->last = new_node(0);
  1261. if (seq->programname != g_progname) {
  1262. seq->programname = g_progname;
  1263. n = chain_node(OC_NEWSOURCE);
  1264. n->l.new_progname = xstrdup(g_progname);
  1265. }
  1266. n = seq->last;
  1267. n->info = info;
  1268. seq->last = n->a.n = new_node(OC_DONE);
  1269. return n;
  1270. }
  1271. static void chain_expr(uint32_t info)
  1272. {
  1273. node *n;
  1274. n = chain_node(info);
  1275. n->l.n = parse_expr(TC_OPTERM | TC_GRPTERM);
  1276. if ((info & OF_REQUIRED) && !n->l.n)
  1277. syntax_error(EMSG_TOO_FEW_ARGS);
  1278. if (t_tclass & TC_GRPTERM)
  1279. rollback_token();
  1280. }
  1281. static node *chain_loop(node *nn)
  1282. {
  1283. node *n, *n2, *save_brk, *save_cont;
  1284. save_brk = break_ptr;
  1285. save_cont = continue_ptr;
  1286. n = chain_node(OC_BR | Vx);
  1287. continue_ptr = new_node(OC_EXEC);
  1288. break_ptr = new_node(OC_EXEC);
  1289. chain_group();
  1290. n2 = chain_node(OC_EXEC | Vx);
  1291. n2->l.n = nn;
  1292. n2->a.n = n;
  1293. continue_ptr->a.n = n2;
  1294. break_ptr->a.n = n->r.n = seq->last;
  1295. continue_ptr = save_cont;
  1296. break_ptr = save_brk;
  1297. return n;
  1298. }
  1299. /* parse group and attach it to chain */
  1300. static void chain_group(void)
  1301. {
  1302. uint32_t c;
  1303. node *n, *n2, *n3;
  1304. do {
  1305. c = next_token(TC_GRPSEQ);
  1306. } while (c & TC_NEWLINE);
  1307. if (c & TC_GRPSTART) {
  1308. debug_printf_parse("%s: TC_GRPSTART\n", __func__);
  1309. while (next_token(TC_GRPSEQ | TC_GRPTERM) != TC_GRPTERM) {
  1310. debug_printf_parse("%s: !TC_GRPTERM\n", __func__);
  1311. if (t_tclass & TC_NEWLINE)
  1312. continue;
  1313. rollback_token();
  1314. chain_group();
  1315. }
  1316. debug_printf_parse("%s: TC_GRPTERM\n", __func__);
  1317. } else if (c & (TC_OPSEQ | TC_OPTERM)) {
  1318. debug_printf_parse("%s: TC_OPSEQ | TC_OPTERM\n", __func__);
  1319. rollback_token();
  1320. chain_expr(OC_EXEC | Vx);
  1321. } else {
  1322. /* TC_STATEMNT */
  1323. debug_printf_parse("%s: TC_STATEMNT(?)\n", __func__);
  1324. switch (t_info & OPCLSMASK) {
  1325. case ST_IF:
  1326. debug_printf_parse("%s: ST_IF\n", __func__);
  1327. n = chain_node(OC_BR | Vx);
  1328. n->l.n = condition();
  1329. chain_group();
  1330. n2 = chain_node(OC_EXEC);
  1331. n->r.n = seq->last;
  1332. if (next_token(TC_GRPSEQ | TC_GRPTERM | TC_ELSE) == TC_ELSE) {
  1333. chain_group();
  1334. n2->a.n = seq->last;
  1335. } else {
  1336. rollback_token();
  1337. }
  1338. break;
  1339. case ST_WHILE:
  1340. debug_printf_parse("%s: ST_WHILE\n", __func__);
  1341. n2 = condition();
  1342. n = chain_loop(NULL);
  1343. n->l.n = n2;
  1344. break;
  1345. case ST_DO:
  1346. debug_printf_parse("%s: ST_DO\n", __func__);
  1347. n2 = chain_node(OC_EXEC);
  1348. n = chain_loop(NULL);
  1349. n2->a.n = n->a.n;
  1350. next_token(TC_WHILE);
  1351. n->l.n = condition();
  1352. break;
  1353. case ST_FOR:
  1354. debug_printf_parse("%s: ST_FOR\n", __func__);
  1355. next_token(TC_SEQSTART);
  1356. n2 = parse_expr(TC_SEMICOL | TC_SEQTERM);
  1357. if (t_tclass & TC_SEQTERM) { /* for-in */
  1358. if (!n2 || (n2->info & OPCLSMASK) != OC_IN)
  1359. syntax_error(EMSG_UNEXP_TOKEN);
  1360. n = chain_node(OC_WALKINIT | VV);
  1361. n->l.n = n2->l.n;
  1362. n->r.n = n2->r.n;
  1363. n = chain_loop(NULL);
  1364. n->info = OC_WALKNEXT | Vx;
  1365. n->l.n = n2->l.n;
  1366. } else { /* for (;;) */
  1367. n = chain_node(OC_EXEC | Vx);
  1368. n->l.n = n2;
  1369. n2 = parse_expr(TC_SEMICOL);
  1370. n3 = parse_expr(TC_SEQTERM);
  1371. n = chain_loop(n3);
  1372. n->l.n = n2;
  1373. if (!n2)
  1374. n->info = OC_EXEC;
  1375. }
  1376. break;
  1377. case OC_PRINT:
  1378. case OC_PRINTF:
  1379. debug_printf_parse("%s: OC_PRINT[F]\n", __func__);
  1380. n = chain_node(t_info);
  1381. n->l.n = parse_expr(TC_OPTERM | TC_OUTRDR | TC_GRPTERM);
  1382. if (t_tclass & TC_OUTRDR) {
  1383. n->info |= t_info;
  1384. n->r.n = parse_expr(TC_OPTERM | TC_GRPTERM);
  1385. }
  1386. if (t_tclass & TC_GRPTERM)
  1387. rollback_token();
  1388. break;
  1389. case OC_BREAK:
  1390. debug_printf_parse("%s: OC_BREAK\n", __func__);
  1391. n = chain_node(OC_EXEC);
  1392. n->a.n = break_ptr;
  1393. chain_expr(t_info);
  1394. break;
  1395. case OC_CONTINUE:
  1396. debug_printf_parse("%s: OC_CONTINUE\n", __func__);
  1397. n = chain_node(OC_EXEC);
  1398. n->a.n = continue_ptr;
  1399. chain_expr(t_info);
  1400. break;
  1401. /* delete, next, nextfile, return, exit */
  1402. default:
  1403. debug_printf_parse("%s: default\n", __func__);
  1404. chain_expr(t_info);
  1405. }
  1406. }
  1407. }
  1408. static void parse_program(char *p)
  1409. {
  1410. uint32_t tclass;
  1411. node *cn;
  1412. func *f;
  1413. var *v;
  1414. g_pos = p;
  1415. t_lineno = 1;
  1416. while ((tclass = next_token(TC_EOF | TC_OPSEQ | TC_GRPSTART |
  1417. TC_OPTERM | TC_BEGIN | TC_END | TC_FUNCDECL)) != TC_EOF) {
  1418. if (tclass & TC_OPTERM) {
  1419. debug_printf_parse("%s: TC_OPTERM\n", __func__);
  1420. continue;
  1421. }
  1422. seq = &mainseq;
  1423. if (tclass & TC_BEGIN) {
  1424. debug_printf_parse("%s: TC_BEGIN\n", __func__);
  1425. seq = &beginseq;
  1426. chain_group();
  1427. } else if (tclass & TC_END) {
  1428. debug_printf_parse("%s: TC_END\n", __func__);
  1429. seq = &endseq;
  1430. chain_group();
  1431. } else if (tclass & TC_FUNCDECL) {
  1432. debug_printf_parse("%s: TC_FUNCDECL\n", __func__);
  1433. next_token(TC_FUNCTION);
  1434. g_pos++;
  1435. f = newfunc(t_string);
  1436. f->body.first = NULL;
  1437. f->nargs = 0;
  1438. /* Match func arg list: a comma sep list of >= 0 args, and a close paren */
  1439. while (next_token(TC_VARIABLE | TC_SEQTERM | TC_COMMA)) {
  1440. /* Either an empty arg list, or trailing comma from prev iter
  1441. * must be followed by an arg */
  1442. if (f->nargs == 0 && t_tclass == TC_SEQTERM)
  1443. break;
  1444. /* TC_SEQSTART/TC_COMMA must be followed by TC_VARIABLE */
  1445. if (t_tclass != TC_VARIABLE)
  1446. syntax_error(EMSG_UNEXP_TOKEN);
  1447. v = findvar(ahash, t_string);
  1448. v->x.aidx = f->nargs++;
  1449. /* Arg followed either by end of arg list or 1 comma */
  1450. if (next_token(TC_COMMA | TC_SEQTERM) & TC_SEQTERM)
  1451. break;
  1452. if (t_tclass != TC_COMMA)
  1453. syntax_error(EMSG_UNEXP_TOKEN);
  1454. }
  1455. seq = &f->body;
  1456. chain_group();
  1457. clear_array(ahash);
  1458. } else if (tclass & TC_OPSEQ) {
  1459. debug_printf_parse("%s: TC_OPSEQ\n", __func__);
  1460. rollback_token();
  1461. cn = chain_node(OC_TEST);
  1462. cn->l.n = parse_expr(TC_OPTERM | TC_EOF | TC_GRPSTART);
  1463. if (t_tclass & TC_GRPSTART) {
  1464. debug_printf_parse("%s: TC_GRPSTART\n", __func__);
  1465. rollback_token();
  1466. chain_group();
  1467. } else {
  1468. debug_printf_parse("%s: !TC_GRPSTART\n", __func__);
  1469. chain_node(OC_PRINT);
  1470. }
  1471. cn->r.n = mainseq.last;
  1472. } else /* if (tclass & TC_GRPSTART) */ {
  1473. debug_printf_parse("%s: TC_GRPSTART(?)\n", __func__);
  1474. rollback_token();
  1475. chain_group();
  1476. }
  1477. }
  1478. debug_printf_parse("%s: TC_EOF\n", __func__);
  1479. }
  1480. /* -------- program execution part -------- */
  1481. static node *mk_splitter(const char *s, tsplitter *spl)
  1482. {
  1483. regex_t *re, *ire;
  1484. node *n;
  1485. re = &spl->re[0];
  1486. ire = &spl->re[1];
  1487. n = &spl->n;
  1488. if ((n->info & OPCLSMASK) == OC_REGEXP) {
  1489. regfree(re);
  1490. regfree(ire); // TODO: nuke ire, use re+1?
  1491. }
  1492. if (s[0] && s[1]) { /* strlen(s) > 1 */
  1493. mk_re_node(s, n, re);
  1494. } else {
  1495. n->info = (uint32_t) s[0];
  1496. }
  1497. return n;
  1498. }
  1499. /* use node as a regular expression. Supplied with node ptr and regex_t
  1500. * storage space. Return ptr to regex (if result points to preg, it should
  1501. * be later regfree'd manually
  1502. */
  1503. static regex_t *as_regex(node *op, regex_t *preg)
  1504. {
  1505. int cflags;
  1506. var *v;
  1507. const char *s;
  1508. if ((op->info & OPCLSMASK) == OC_REGEXP) {
  1509. return icase ? op->r.ire : op->l.re;
  1510. }
  1511. v = nvalloc(1);
  1512. s = getvar_s(evaluate(op, v));
  1513. cflags = icase ? REG_EXTENDED | REG_ICASE : REG_EXTENDED;
  1514. /* Testcase where REG_EXTENDED fails (unpaired '{'):
  1515. * echo Hi | awk 'gsub("@(samp|code|file)\{","");'
  1516. * gawk 3.1.5 eats this. We revert to ~REG_EXTENDED
  1517. * (maybe gsub is not supposed to use REG_EXTENDED?).
  1518. */
  1519. if (regcomp(preg, s, cflags)) {
  1520. cflags &= ~REG_EXTENDED;
  1521. xregcomp(preg, s, cflags);
  1522. }
  1523. nvfree(v);
  1524. return preg;
  1525. }
  1526. /* gradually increasing buffer.
  1527. * note that we reallocate even if n == old_size,
  1528. * and thus there is at least one extra allocated byte.
  1529. */
  1530. static char* qrealloc(char *b, int n, int *size)
  1531. {
  1532. if (!b || n >= *size) {
  1533. *size = n + (n>>1) + 80;
  1534. b = xrealloc(b, *size);
  1535. }
  1536. return b;
  1537. }
  1538. /* resize field storage space */
  1539. static void fsrealloc(int size)
  1540. {
  1541. int i;
  1542. if (size >= maxfields) {
  1543. i = maxfields;
  1544. maxfields = size + 16;
  1545. Fields = xrealloc(Fields, maxfields * sizeof(Fields[0]));
  1546. for (; i < maxfields; i++) {
  1547. Fields[i].type = VF_SPECIAL;
  1548. Fields[i].string = NULL;
  1549. }
  1550. }
  1551. /* if size < nfields, clear extra field variables */
  1552. for (i = size; i < nfields; i++) {
  1553. clrvar(Fields + i);
  1554. }
  1555. nfields = size;
  1556. }
  1557. static int awk_split(const char *s, node *spl, char **slist)
  1558. {
  1559. int l, n;
  1560. char c[4];
  1561. char *s1;
  1562. regmatch_t pmatch[2]; // TODO: why [2]? [1] is enough...
  1563. /* in worst case, each char would be a separate field */
  1564. *slist = s1 = xzalloc(strlen(s) * 2 + 3);
  1565. strcpy(s1, s);
  1566. c[0] = c[1] = (char)spl->info;
  1567. c[2] = c[3] = '\0';
  1568. if (*getvar_s(intvar[RS]) == '\0')
  1569. c[2] = '\n';
  1570. n = 0;
  1571. if ((spl->info & OPCLSMASK) == OC_REGEXP) { /* regex split */
  1572. if (!*s)
  1573. return n; /* "": zero fields */
  1574. n++; /* at least one field will be there */
  1575. do {
  1576. l = strcspn(s, c+2); /* len till next NUL or \n */
  1577. if (regexec(icase ? spl->r.ire : spl->l.re, s, 1, pmatch, 0) == 0
  1578. && pmatch[0].rm_so <= l
  1579. ) {
  1580. l = pmatch[0].rm_so;
  1581. if (pmatch[0].rm_eo == 0) {
  1582. l++;
  1583. pmatch[0].rm_eo++;
  1584. }
  1585. n++; /* we saw yet another delimiter */
  1586. } else {
  1587. pmatch[0].rm_eo = l;
  1588. if (s[l])
  1589. pmatch[0].rm_eo++;
  1590. }
  1591. memcpy(s1, s, l);
  1592. /* make sure we remove *all* of the separator chars */
  1593. do {
  1594. s1[l] = '\0';
  1595. } while (++l < pmatch[0].rm_eo);
  1596. nextword(&s1);
  1597. s += pmatch[0].rm_eo;
  1598. } while (*s);
  1599. return n;
  1600. }
  1601. if (c[0] == '\0') { /* null split */
  1602. while (*s) {
  1603. *s1++ = *s++;
  1604. *s1++ = '\0';
  1605. n++;
  1606. }
  1607. return n;
  1608. }
  1609. if (c[0] != ' ') { /* single-character split */
  1610. if (icase) {
  1611. c[0] = toupper(c[0]);
  1612. c[1] = tolower(c[1]);
  1613. }
  1614. if (*s1)
  1615. n++;
  1616. while ((s1 = strpbrk(s1, c)) != NULL) {
  1617. *s1++ = '\0';
  1618. n++;
  1619. }
  1620. return n;
  1621. }
  1622. /* space split */
  1623. while (*s) {
  1624. s = skip_whitespace(s);
  1625. if (!*s)
  1626. break;
  1627. n++;
  1628. while (*s && !isspace(*s))
  1629. *s1++ = *s++;
  1630. *s1++ = '\0';
  1631. }
  1632. return n;
  1633. }
  1634. static void split_f0(void)
  1635. {
  1636. /* static char *fstrings; */
  1637. #define fstrings (G.split_f0__fstrings)
  1638. int i, n;
  1639. char *s;
  1640. if (is_f0_split)
  1641. return;
  1642. is_f0_split = TRUE;
  1643. free(fstrings);
  1644. fsrealloc(0);
  1645. n = awk_split(getvar_s(intvar[F0]), &fsplitter.n, &fstrings);
  1646. fsrealloc(n);
  1647. s = fstrings;
  1648. for (i = 0; i < n; i++) {
  1649. Fields[i].string = nextword(&s);
  1650. Fields[i].type |= (VF_FSTR | VF_USER | VF_DIRTY);
  1651. }
  1652. /* set NF manually to avoid side effects */
  1653. clrvar(intvar[NF]);
  1654. intvar[NF]->type = VF_NUMBER | VF_SPECIAL;
  1655. intvar[NF]->number = nfields;
  1656. #undef fstrings
  1657. }
  1658. /* perform additional actions when some internal variables changed */
  1659. static void handle_special(var *v)
  1660. {
  1661. int n;
  1662. char *b;
  1663. const char *sep, *s;
  1664. int sl, l, len, i, bsize;
  1665. if (!(v->type & VF_SPECIAL))
  1666. return;
  1667. if (v == intvar[NF]) {
  1668. n = (int)getvar_i(v);
  1669. if (n < 0)
  1670. syntax_error("NF set to negative value");
  1671. fsrealloc(n);
  1672. /* recalculate $0 */
  1673. sep = getvar_s(intvar[OFS]);
  1674. sl = strlen(sep);
  1675. b = NULL;
  1676. len = 0;
  1677. for (i = 0; i < n; i++) {
  1678. s = getvar_s(&Fields[i]);
  1679. l = strlen(s);
  1680. if (b) {
  1681. memcpy(b+len, sep, sl);
  1682. len += sl;
  1683. }
  1684. b = qrealloc(b, len+l+sl, &bsize);
  1685. memcpy(b+len, s, l);
  1686. len += l;
  1687. }
  1688. if (b)
  1689. b[len] = '\0';
  1690. setvar_p(intvar[F0], b);
  1691. is_f0_split = TRUE;
  1692. } else if (v == intvar[F0]) {
  1693. is_f0_split = FALSE;
  1694. } else if (v == intvar[FS]) {
  1695. /*
  1696. * The POSIX-2008 standard says that changing FS should have no effect on the
  1697. * current input line, but only on the next one. The language is:
  1698. *
  1699. * > Before the first reference to a field in the record is evaluated, the record
  1700. * > shall be split into fields, according to the rules in Regular Expressions,
  1701. * > using the value of FS that was current at the time the record was read.
  1702. *
  1703. * So, split up current line before assignment to FS:
  1704. */
  1705. split_f0();
  1706. mk_splitter(getvar_s(v), &fsplitter);
  1707. } else if (v == intvar[RS]) {
  1708. mk_splitter(getvar_s(v), &rsplitter);
  1709. } else if (v == intvar[IGNORECASE]) {
  1710. icase = istrue(v);
  1711. } else { /* $n */
  1712. n = getvar_i(intvar[NF]);
  1713. setvar_i(intvar[NF], n > v-Fields ? n : v-Fields+1);
  1714. /* right here v is invalid. Just to note... */
  1715. }
  1716. }
  1717. /* step through func/builtin/etc arguments */
  1718. static node *nextarg(node **pn)
  1719. {
  1720. node *n;
  1721. n = *pn;
  1722. if (n && (n->info & OPCLSMASK) == OC_COMMA) {
  1723. *pn = n->r.n;
  1724. n = n->l.n;
  1725. } else {
  1726. *pn = NULL;
  1727. }
  1728. return n;
  1729. }
  1730. static void hashwalk_init(var *v, xhash *array)
  1731. {
  1732. hash_item *hi;
  1733. unsigned i;
  1734. walker_list *w;
  1735. walker_list *prev_walker;
  1736. if (v->type & VF_WALK) {
  1737. prev_walker = v->x.walker;
  1738. } else {
  1739. v->type |= VF_WALK;
  1740. prev_walker = NULL;
  1741. }
  1742. debug_printf_walker("hashwalk_init: prev_walker:%p\n", prev_walker);
  1743. w = v->x.walker = xzalloc(sizeof(*w) + array->glen + 1); /* why + 1? */
  1744. debug_printf_walker(" walker@%p=%p\n", &v->x.walker, w);
  1745. w->cur = w->end = w->wbuf;
  1746. w->prev = prev_walker;
  1747. for (i = 0; i < array->csize; i++) {
  1748. hi = array->items[i];
  1749. while (hi) {
  1750. strcpy(w->end, hi->name);
  1751. nextword(&w->end);
  1752. hi = hi->next;
  1753. }
  1754. }
  1755. }
  1756. static int hashwalk_next(var *v)
  1757. {
  1758. walker_list *w = v->x.walker;
  1759. if (w->cur >= w->end) {
  1760. walker_list *prev_walker = w->prev;
  1761. debug_printf_walker("end of iteration, free(walker@%p:%p), prev_walker:%p\n", &v->x.walker, w, prev_walker);
  1762. free(w);
  1763. v->x.walker = prev_walker;
  1764. return FALSE;
  1765. }
  1766. setvar_s(v, nextword(&w->cur));
  1767. return TRUE;
  1768. }
  1769. /* evaluate node, return 1 when result is true, 0 otherwise */
  1770. static int ptest(node *pattern)
  1771. {
  1772. /* ptest__v is "static": to save stack space? */
  1773. return istrue(evaluate(pattern, &G.ptest__v));
  1774. }
  1775. /* read next record from stream rsm into a variable v */
  1776. static int awk_getline(rstream *rsm, var *v)
  1777. {
  1778. char *b;
  1779. regmatch_t pmatch[2];
  1780. int size, a, p, pp = 0;
  1781. int fd, so, eo, r, rp;
  1782. char c, *m, *s;
  1783. debug_printf_eval("entered %s()\n", __func__);
  1784. /* we're using our own buffer since we need access to accumulating
  1785. * characters
  1786. */
  1787. fd = fileno(rsm->F);
  1788. m = rsm->buffer;
  1789. a = rsm->adv;
  1790. p = rsm->pos;
  1791. size = rsm->size;
  1792. c = (char) rsplitter.n.info;
  1793. rp = 0;
  1794. if (!m)
  1795. m = qrealloc(m, 256, &size);
  1796. do {
  1797. b = m + a;
  1798. so = eo = p;
  1799. r = 1;
  1800. if (p > 0) {
  1801. if ((rsplitter.n.info & OPCLSMASK) == OC_REGEXP) {
  1802. if (regexec(icase ? rsplitter.n.r.ire : rsplitter.n.l.re,
  1803. b, 1, pmatch, 0) == 0) {
  1804. so = pmatch[0].rm_so;
  1805. eo = pmatch[0].rm_eo;
  1806. if (b[eo] != '\0')
  1807. break;
  1808. }
  1809. } else if (c != '\0') {
  1810. s = strchr(b+pp, c);
  1811. if (!s)
  1812. s = memchr(b+pp, '\0', p - pp);
  1813. if (s) {
  1814. so = eo = s-b;
  1815. eo++;
  1816. break;
  1817. }
  1818. } else {
  1819. while (b[rp] == '\n')
  1820. rp++;
  1821. s = strstr(b+rp, "\n\n");
  1822. if (s) {
  1823. so = eo = s-b;
  1824. while (b[eo] == '\n')
  1825. eo++;
  1826. if (b[eo] != '\0')
  1827. break;
  1828. }
  1829. }
  1830. }
  1831. if (a > 0) {
  1832. memmove(m, m+a, p+1);
  1833. b = m;
  1834. a = 0;
  1835. }
  1836. m = qrealloc(m, a+p+128, &size);
  1837. b = m + a;
  1838. pp = p;
  1839. p += safe_read(fd, b+p, size-p-1);
  1840. if (p < pp) {
  1841. p = 0;
  1842. r = 0;
  1843. setvar_i(intvar[ERRNO], errno);
  1844. }
  1845. b[p] = '\0';
  1846. } while (p > pp);
  1847. if (p == 0) {
  1848. r--;
  1849. } else {
  1850. c = b[so]; b[so] = '\0';
  1851. setvar_s(v, b+rp);
  1852. v->type |= VF_USER;
  1853. b[so] = c;
  1854. c = b[eo]; b[eo] = '\0';
  1855. setvar_s(intvar[RT], b+so);
  1856. b[eo] = c;
  1857. }
  1858. rsm->buffer = m;
  1859. rsm->adv = a + eo;
  1860. rsm->pos = p - eo;
  1861. rsm->size = size;
  1862. debug_printf_eval("returning from %s(): %d\n", __func__, r);
  1863. return r;
  1864. }
  1865. static int fmt_num(char *b, int size, const char *format, double n, int int_as_int)
  1866. {
  1867. int r = 0;
  1868. char c;
  1869. const char *s = format;
  1870. if (int_as_int && n == (long long)n) {
  1871. r = snprintf(b, size, "%lld", (long long)n);
  1872. } else {
  1873. do { c = *s; } while (c && *++s);
  1874. if (strchr("diouxX", c)) {
  1875. r = snprintf(b, size, format, (int)n);
  1876. } else if (strchr("eEfgG", c)) {
  1877. r = snprintf(b, size, format, n);
  1878. } else {
  1879. syntax_error(EMSG_INV_FMT);
  1880. }
  1881. }
  1882. return r;
  1883. }
  1884. /* formatted output into an allocated buffer, return ptr to buffer */
  1885. static char *awk_printf(node *n)
  1886. {
  1887. char *b = NULL;
  1888. char *fmt, *s, *f;
  1889. const char *s1;
  1890. int i, j, incr, bsize;
  1891. char c, c1;
  1892. var *v, *arg;
  1893. v = nvalloc(1);
  1894. fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), v)));
  1895. i = 0;
  1896. while (*f) {
  1897. s = f;
  1898. while (*f && (*f != '%' || *++f == '%'))
  1899. f++;
  1900. while (*f && !isalpha(*f)) {
  1901. if (*f == '*')
  1902. syntax_error("%*x formats are not supported");
  1903. f++;
  1904. }
  1905. incr = (f - s) + MAXVARFMT;
  1906. b = qrealloc(b, incr + i, &bsize);
  1907. c = *f;
  1908. if (c != '\0')
  1909. f++;
  1910. c1 = *f;
  1911. *f = '\0';
  1912. arg = evaluate(nextarg(&n), v);
  1913. j = i;
  1914. if (c == 'c' || !c) {
  1915. i += sprintf(b+i, s, is_numeric(arg) ?
  1916. (char)getvar_i(arg) : *getvar_s(arg));
  1917. } else if (c == 's') {
  1918. s1 = getvar_s(arg);
  1919. b = qrealloc(b, incr+i+strlen(s1), &bsize);
  1920. i += sprintf(b+i, s, s1);
  1921. } else {
  1922. i += fmt_num(b+i, incr, s, getvar_i(arg), FALSE);
  1923. }
  1924. *f = c1;
  1925. /* if there was an error while sprintf, return value is negative */
  1926. if (i < j)
  1927. i = j;
  1928. }
  1929. free(fmt);
  1930. nvfree(v);
  1931. b = xrealloc(b, i + 1);
  1932. b[i] = '\0';
  1933. return b;
  1934. }
  1935. /* Common substitution routine.
  1936. * Replace (nm)'th substring of (src) that matches (rn) with (repl),
  1937. * store result into (dest), return number of substitutions.
  1938. * If nm = 0, replace all matches.
  1939. * If src or dst is NULL, use $0.
  1940. * If subexp != 0, enable subexpression matching (\1-\9).
  1941. */
  1942. static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest, int subexp)
  1943. {
  1944. char *resbuf;
  1945. const char *sp;
  1946. int match_no, residx, replen, resbufsize;
  1947. int regexec_flags;
  1948. regmatch_t pmatch[10];
  1949. regex_t sreg, *regex;
  1950. resbuf = NULL;
  1951. residx = 0;
  1952. match_no = 0;
  1953. regexec_flags = 0;
  1954. regex = as_regex(rn, &sreg);
  1955. sp = getvar_s(src ? src : intvar[F0]);
  1956. replen = strlen(repl);
  1957. while (regexec(regex, sp, 10, pmatch, regexec_flags) == 0) {
  1958. int so = pmatch[0].rm_so;
  1959. int eo = pmatch[0].rm_eo;
  1960. //bb_error_msg("match %u: [%u,%u] '%s'%p", match_no+1, so, eo, sp,sp);
  1961. resbuf = qrealloc(resbuf, residx + eo + replen, &resbufsize);
  1962. memcpy(resbuf + residx, sp, eo);
  1963. residx += eo;
  1964. if (++match_no >= nm) {
  1965. const char *s;
  1966. int nbs;
  1967. /* replace */
  1968. residx -= (eo - so);
  1969. nbs = 0;
  1970. for (s = repl; *s; s++) {
  1971. char c = resbuf[residx++] = *s;
  1972. if (c == '\\') {
  1973. nbs++;
  1974. continue;
  1975. }
  1976. if (c == '&' || (subexp && c >= '0' && c <= '9')) {
  1977. int j;
  1978. residx -= ((nbs + 3) >> 1);
  1979. j = 0;
  1980. if (c != '&') {
  1981. j = c - '0';
  1982. nbs++;
  1983. }
  1984. if (nbs % 2) {
  1985. resbuf[residx++] = c;
  1986. } else {
  1987. int n = pmatch[j].rm_eo - pmatch[j].rm_so;
  1988. resbuf = qrealloc(resbuf, residx + replen + n, &resbufsize);
  1989. memcpy(resbuf + residx, sp + pmatch[j].rm_so, n);
  1990. residx += n;
  1991. }
  1992. }
  1993. nbs = 0;
  1994. }
  1995. }
  1996. regexec_flags = REG_NOTBOL;
  1997. sp += eo;
  1998. if (match_no == nm)
  1999. break;
  2000. if (eo == so) {
  2001. /* Empty match (e.g. "b*" will match anywhere).
  2002. * Advance by one char. */
  2003. //BUG (bug 1333):
  2004. //gsub(/\<b*/,"") on "abc" will reach this point, advance to "bc"
  2005. //... and will erroneously match "b" even though it is NOT at the word start.
  2006. //we need REG_NOTBOW but it does not exist...
  2007. //TODO: if EXTRA_COMPAT=y, use GNU matching and re_search,
  2008. //it should be able to do it correctly.
  2009. /* Subtle: this is safe only because
  2010. * qrealloc allocated at least one extra byte */
  2011. resbuf[residx] = *sp;
  2012. if (*sp == '\0')
  2013. goto ret;
  2014. sp++;
  2015. residx++;
  2016. }
  2017. }
  2018. resbuf = qrealloc(resbuf, residx + strlen(sp), &resbufsize);
  2019. strcpy(resbuf + residx, sp);
  2020. ret:
  2021. //bb_error_msg("end sp:'%s'%p", sp,sp);
  2022. setvar_p(dest ? dest : intvar[F0], resbuf);
  2023. if (regex == &sreg)
  2024. regfree(regex);
  2025. return match_no;
  2026. }
  2027. static NOINLINE int do_mktime(const char *ds)
  2028. {
  2029. struct tm then;
  2030. int count;
  2031. /*memset(&then, 0, sizeof(then)); - not needed */
  2032. then.tm_isdst = -1; /* default is unknown */
  2033. /* manpage of mktime says these fields are ints,
  2034. * so we can sscanf stuff directly into them */
  2035. count = sscanf(ds, "%u %u %u %u %u %u %d",
  2036. &then.tm_year, &then.tm_mon, &then.tm_mday,
  2037. &then.tm_hour, &then.tm_min, &then.tm_sec,
  2038. &then.tm_isdst);
  2039. if (count < 6
  2040. || (unsigned)then.tm_mon < 1
  2041. || (unsigned)then.tm_year < 1900
  2042. ) {
  2043. return -1;
  2044. }
  2045. then.tm_mon -= 1;
  2046. then.tm_year -= 1900;
  2047. return mktime(&then);
  2048. }
  2049. static NOINLINE var *exec_builtin(node *op, var *res)
  2050. {
  2051. #define tspl (G.exec_builtin__tspl)
  2052. var *tv;
  2053. node *an[4];
  2054. var *av[4];
  2055. const char *as[4];
  2056. regmatch_t pmatch[2];
  2057. regex_t sreg, *re;
  2058. node *spl;
  2059. uint32_t isr, info;
  2060. int nargs;
  2061. time_t tt;
  2062. int i, l, ll, n;
  2063. tv = nvalloc(4);
  2064. isr = info = op->info;
  2065. op = op->l.n;
  2066. av[2] = av[3] = NULL;
  2067. for (i = 0; i < 4 && op; i++) {
  2068. an[i] = nextarg(&op);
  2069. if (isr & 0x09000000)
  2070. av[i] = evaluate(an[i], &tv[i]);
  2071. if (isr & 0x08000000)
  2072. as[i] = getvar_s(av[i]);
  2073. isr >>= 1;
  2074. }
  2075. nargs = i;
  2076. if ((uint32_t)nargs < (info >> 30))
  2077. syntax_error(EMSG_TOO_FEW_ARGS);
  2078. info &= OPNMASK;
  2079. switch (info) {
  2080. case B_a2:
  2081. if (ENABLE_FEATURE_AWK_LIBM)
  2082. setvar_i(res, atan2(getvar_i(av[0]), getvar_i(av[1])));
  2083. else
  2084. syntax_error(EMSG_NO_MATH);
  2085. break;
  2086. case B_sp: {
  2087. char *s, *s1;
  2088. if (nargs > 2) {
  2089. spl = (an[2]->info & OPCLSMASK) == OC_REGEXP ?
  2090. an[2] : mk_splitter(getvar_s(evaluate(an[2], &tv[2])), &tspl);
  2091. } else {
  2092. spl = &fsplitter.n;
  2093. }
  2094. n = awk_split(as[0], spl, &s);
  2095. s1 = s;
  2096. clear_array(iamarray(av[1]));
  2097. for (i = 1; i <= n; i++)
  2098. setari_u(av[1], i, nextword(&s));
  2099. free(s1);
  2100. setvar_i(res, n);
  2101. break;
  2102. }
  2103. case B_ss: {
  2104. char *s;
  2105. l = strlen(as[0]);
  2106. i = getvar_i(av[1]) - 1;
  2107. if (i > l)
  2108. i = l;
  2109. if (i < 0)
  2110. i = 0;
  2111. n = (nargs > 2) ? getvar_i(av[2]) : l-i;
  2112. if (n < 0)
  2113. n = 0;
  2114. s = xstrndup(as[0]+i, n);
  2115. setvar_p(res, s);
  2116. break;
  2117. }
  2118. /* Bitwise ops must assume that operands are unsigned. GNU Awk 3.1.5:
  2119. * awk '{ print or(-1,1) }' gives "4.29497e+09", not "-2.xxxe+09" */
  2120. case B_an:
  2121. setvar_i(res, getvar_i_int(av[0]) & getvar_i_int(av[1]));
  2122. break;
  2123. case B_co:
  2124. setvar_i(res, ~getvar_i_int(av[0]));
  2125. break;
  2126. case B_ls:
  2127. setvar_i(res, getvar_i_int(av[0]) << getvar_i_int(av[1]));
  2128. break;
  2129. case B_or:
  2130. setvar_i(res, getvar_i_int(av[0]) | getvar_i_int(av[1]));
  2131. break;
  2132. case B_rs:
  2133. setvar_i(res, getvar_i_int(av[0]) >> getvar_i_int(av[1]));
  2134. break;
  2135. case B_xo:
  2136. setvar_i(res, getvar_i_int(av[0]) ^ getvar_i_int(av[1]));
  2137. break;
  2138. case B_lo:
  2139. case B_up: {
  2140. char *s, *s1;
  2141. s1 = s = xstrdup(as[0]);
  2142. while (*s1) {
  2143. //*s1 = (info == B_up) ? toupper(*s1) : tolower(*s1);
  2144. if ((unsigned char)((*s1 | 0x20) - 'a') <= ('z' - 'a'))
  2145. *s1 = (info == B_up) ? (*s1 & 0xdf) : (*s1 | 0x20);
  2146. s1++;
  2147. }
  2148. setvar_p(res, s);
  2149. break;
  2150. }
  2151. case B_ix:
  2152. n = 0;
  2153. ll = strlen(as[1]);
  2154. l = strlen(as[0]) - ll;
  2155. if (ll > 0 && l >= 0) {
  2156. if (!icase) {
  2157. char *s = strstr(as[0], as[1]);
  2158. if (s)
  2159. n = (s - as[0]) + 1;
  2160. } else {
  2161. /* this piece of code is terribly slow and
  2162. * really should be rewritten
  2163. */
  2164. for (i = 0; i <= l; i++) {
  2165. if (strncasecmp(as[0]+i, as[1], ll) == 0) {
  2166. n = i+1;
  2167. break;
  2168. }
  2169. }
  2170. }
  2171. }
  2172. setvar_i(res, n);
  2173. break;
  2174. case B_ti:
  2175. if (nargs > 1)
  2176. tt = getvar_i(av[1]);
  2177. else
  2178. time(&tt);
  2179. //s = (nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y";
  2180. i = strftime(g_buf, MAXVARFMT,
  2181. ((nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y"),
  2182. localtime(&tt));
  2183. g_buf[i] = '\0';
  2184. setvar_s(res, g_buf);
  2185. break;
  2186. case B_mt:
  2187. setvar_i(res, do_mktime(as[0]));
  2188. break;
  2189. case B_ma:
  2190. re = as_regex(an[1], &sreg);
  2191. n = regexec(re, as[0], 1, pmatch, 0);
  2192. if (n == 0) {
  2193. pmatch[0].rm_so++;
  2194. pmatch[0].rm_eo++;
  2195. } else {
  2196. pmatch[0].rm_so = 0;
  2197. pmatch[0].rm_eo = -1;
  2198. }
  2199. setvar_i(newvar("RSTART"), pmatch[0].rm_so);
  2200. setvar_i(newvar("RLENGTH"), pmatch[0].rm_eo - pmatch[0].rm_so);
  2201. setvar_i(res, pmatch[0].rm_so);
  2202. if (re == &sreg)
  2203. regfree(re);
  2204. break;
  2205. case B_ge:
  2206. awk_sub(an[0], as[1], getvar_i(av[2]), av[3], res, TRUE);
  2207. break;
  2208. case B_gs:
  2209. setvar_i(res, awk_sub(an[0], as[1], 0, av[2], av[2], FALSE));
  2210. break;
  2211. case B_su:
  2212. setvar_i(res, awk_sub(an[0], as[1], 1, av[2], av[2], FALSE));
  2213. break;
  2214. }
  2215. nvfree(tv);
  2216. return res;
  2217. #undef tspl
  2218. }
  2219. /*
  2220. * Evaluate node - the heart of the program. Supplied with subtree
  2221. * and place where to store result. returns ptr to result.
  2222. */
  2223. #define XC(n) ((n) >> 8)
  2224. static var *evaluate(node *op, var *res)
  2225. {
  2226. /* This procedure is recursive so we should count every byte */
  2227. #define fnargs (G.evaluate__fnargs)
  2228. /* seed is initialized to 1 */
  2229. #define seed (G.evaluate__seed)
  2230. #define sreg (G.evaluate__sreg)
  2231. var *v1;
  2232. if (!op)
  2233. return setvar_s(res, NULL);
  2234. debug_printf_eval("entered %s()\n", __func__);
  2235. v1 = nvalloc(2);
  2236. while (op) {
  2237. struct {
  2238. var *v;
  2239. const char *s;
  2240. } L = L; /* for compiler */
  2241. struct {
  2242. var *v;
  2243. const char *s;
  2244. } R = R;
  2245. double L_d = L_d;
  2246. uint32_t opinfo;
  2247. int opn;
  2248. node *op1;
  2249. opinfo = op->info;
  2250. opn = (opinfo & OPNMASK);
  2251. g_lineno = op->lineno;
  2252. op1 = op->l.n;
  2253. debug_printf_eval("opinfo:%08x opn:%08x\n", opinfo, opn);
  2254. /* "delete" is special:
  2255. * "delete array[var--]" must evaluate index expr only once,
  2256. * must not evaluate it in "execute inevitable things" part.
  2257. */
  2258. if (XC(opinfo & OPCLSMASK) == XC(OC_DELETE)) {
  2259. uint32_t info = op1->info & OPCLSMASK;
  2260. var *v;
  2261. debug_printf_eval("DELETE\n");
  2262. if (info == OC_VAR) {
  2263. v = op1->l.v;
  2264. } else if (info == OC_FNARG) {
  2265. v = &fnargs[op1->l.aidx];
  2266. } else {
  2267. syntax_error(EMSG_NOT_ARRAY);
  2268. }
  2269. if (op1->r.n) { /* array ref? */
  2270. const char *s;
  2271. s = getvar_s(evaluate(op1->r.n, v1));
  2272. hash_remove(iamarray(v), s);
  2273. } else {
  2274. clear_array(iamarray(v));
  2275. }
  2276. goto next;
  2277. }
  2278. /* execute inevitable things */
  2279. if (opinfo & OF_RES1)
  2280. L.v = evaluate(op1, v1);
  2281. if (opinfo & OF_RES2)
  2282. R.v = evaluate(op->r.n, v1+1);
  2283. if (opinfo & OF_STR1) {
  2284. L.s = getvar_s(L.v);
  2285. debug_printf_eval("L.s:'%s'\n", L.s);
  2286. }
  2287. if (opinfo & OF_STR2) {
  2288. R.s = getvar_s(R.v);
  2289. debug_printf_eval("R.s:'%s'\n", R.s);
  2290. }
  2291. if (opinfo & OF_NUM1) {
  2292. L_d = getvar_i(L.v);
  2293. debug_printf_eval("L_d:%f\n", L_d);
  2294. }
  2295. debug_printf_eval("switch(0x%x)\n", XC(opinfo & OPCLSMASK));
  2296. switch (XC(opinfo & OPCLSMASK)) {
  2297. /* -- iterative node type -- */
  2298. /* test pattern */
  2299. case XC( OC_TEST ):
  2300. if ((op1->info & OPCLSMASK) == OC_COMMA) {
  2301. /* it's range pattern */
  2302. if ((opinfo & OF_CHECKED) || ptest(op1->l.n)) {
  2303. op->info |= OF_CHECKED;
  2304. if (ptest(op1->r.n))
  2305. op->info &= ~OF_CHECKED;
  2306. op = op->a.n;
  2307. } else {
  2308. op = op->r.n;
  2309. }
  2310. } else {
  2311. op = ptest(op1) ? op->a.n : op->r.n;
  2312. }
  2313. break;
  2314. /* just evaluate an expression, also used as unconditional jump */
  2315. case XC( OC_EXEC ):
  2316. break;
  2317. /* branch, used in if-else and various loops */
  2318. case XC( OC_BR ):
  2319. op = istrue(L.v) ? op->a.n : op->r.n;
  2320. break;
  2321. /* initialize for-in loop */
  2322. case XC( OC_WALKINIT ):
  2323. hashwalk_init(L.v, iamarray(R.v));
  2324. break;
  2325. /* get next array item */
  2326. case XC( OC_WALKNEXT ):
  2327. op = hashwalk_next(L.v) ? op->a.n : op->r.n;
  2328. break;
  2329. case XC( OC_PRINT ):
  2330. case XC( OC_PRINTF ): {
  2331. FILE *F = stdout;
  2332. if (op->r.n) {
  2333. rstream *rsm = newfile(R.s);
  2334. if (!rsm->F) {
  2335. if (opn == '|') {
  2336. rsm->F = popen(R.s, "w");
  2337. if (rsm->F == NULL)
  2338. bb_simple_perror_msg_and_die("popen");
  2339. rsm->is_pipe = 1;
  2340. } else {
  2341. rsm->F = xfopen(R.s, opn=='w' ? "w" : "a");
  2342. }
  2343. }
  2344. F = rsm->F;
  2345. }
  2346. if ((opinfo & OPCLSMASK) == OC_PRINT) {
  2347. if (!op1) {
  2348. fputs(getvar_s(intvar[F0]), F);
  2349. } else {
  2350. while (op1) {
  2351. var *v = evaluate(nextarg(&op1), v1);
  2352. if (v->type & VF_NUMBER) {
  2353. fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[OFMT]),
  2354. getvar_i(v), TRUE);
  2355. fputs(g_buf, F);
  2356. } else {
  2357. fputs(getvar_s(v), F);
  2358. }
  2359. if (op1)
  2360. fputs(getvar_s(intvar[OFS]), F);
  2361. }
  2362. }
  2363. fputs(getvar_s(intvar[ORS]), F);
  2364. } else { /* OC_PRINTF */
  2365. char *s = awk_printf(op1);
  2366. fputs(s, F);
  2367. free(s);
  2368. }
  2369. fflush(F);
  2370. break;
  2371. }
  2372. /* case XC( OC_DELETE ): - moved to happen before arg evaluation */
  2373. case XC( OC_NEWSOURCE ):
  2374. g_progname = op->l.new_progname;
  2375. break;
  2376. case XC( OC_RETURN ):
  2377. copyvar(res, L.v);
  2378. break;
  2379. case XC( OC_NEXTFILE ):
  2380. nextfile = TRUE;
  2381. case XC( OC_NEXT ):
  2382. nextrec = TRUE;
  2383. case XC( OC_DONE ):
  2384. clrvar(res);
  2385. break;
  2386. case XC( OC_EXIT ):
  2387. awk_exit(L_d);
  2388. /* -- recursive node type -- */
  2389. case XC( OC_VAR ):
  2390. debug_printf_eval("VAR\n");
  2391. L.v = op->l.v;
  2392. if (L.v == intvar[NF])
  2393. split_f0();
  2394. goto v_cont;
  2395. case XC( OC_FNARG ):
  2396. debug_printf_eval("FNARG[%d]\n", op->l.aidx);
  2397. L.v = &fnargs[op->l.aidx];
  2398. v_cont:
  2399. res = op->r.n ? findvar(iamarray(L.v), R.s) : L.v;
  2400. break;
  2401. case XC( OC_IN ):
  2402. setvar_i(res, hash_search(iamarray(R.v), L.s) ? 1 : 0);
  2403. break;
  2404. case XC( OC_REGEXP ):
  2405. op1 = op;
  2406. L.s = getvar_s(intvar[F0]);
  2407. goto re_cont;
  2408. case XC( OC_MATCH ):
  2409. op1 = op->r.n;
  2410. re_cont:
  2411. {
  2412. regex_t *re = as_regex(op1, &sreg);
  2413. int i = regexec(re, L.s, 0, NULL, 0);
  2414. if (re == &sreg)
  2415. regfree(re);
  2416. setvar_i(res, (i == 0) ^ (opn == '!'));
  2417. }
  2418. break;
  2419. case XC( OC_MOVE ):
  2420. debug_printf_eval("MOVE\n");
  2421. /* if source is a temporary string, jusk relink it to dest */
  2422. //Disabled: if R.v is numeric but happens to have cached R.v->string,
  2423. //then L.v ends up being a string, which is wrong
  2424. // if (R.v == v1+1 && R.v->string) {
  2425. // res = setvar_p(L.v, R.v->string);
  2426. // R.v->string = NULL;
  2427. // } else {
  2428. res = copyvar(L.v, R.v);
  2429. // }
  2430. break;
  2431. case XC( OC_TERNARY ):
  2432. if ((op->r.n->info & OPCLSMASK) != OC_COLON)
  2433. syntax_error(EMSG_POSSIBLE_ERROR);
  2434. res = evaluate(istrue(L.v) ? op->r.n->l.n : op->r.n->r.n, res);
  2435. break;
  2436. case XC( OC_FUNC ): {
  2437. var *vbeg, *v;
  2438. const char *sv_progname;
  2439. /* The body might be empty, still has to eval the args */
  2440. if (!op->r.n->info && !op->r.f->body.first)
  2441. syntax_error(EMSG_UNDEF_FUNC);
  2442. vbeg = v = nvalloc(op->r.f->nargs + 1);
  2443. while (op1) {
  2444. var *arg = evaluate(nextarg(&op1), v1);
  2445. copyvar(v, arg);
  2446. v->type |= VF_CHILD;
  2447. v->x.parent = arg;
  2448. if (++v - vbeg >= op->r.f->nargs)
  2449. break;
  2450. }
  2451. v = fnargs;
  2452. fnargs = vbeg;
  2453. sv_progname = g_progname;
  2454. res = evaluate(op->r.f->body.first, res);
  2455. g_progname = sv_progname;
  2456. nvfree(fnargs);
  2457. fnargs = v;
  2458. break;
  2459. }
  2460. case XC( OC_GETLINE ):
  2461. case XC( OC_PGETLINE ): {
  2462. rstream *rsm;
  2463. int i;
  2464. if (op1) {
  2465. rsm = newfile(L.s);
  2466. if (!rsm->F) {
  2467. if ((opinfo & OPCLSMASK) == OC_PGETLINE) {
  2468. rsm->F = popen(L.s, "r");
  2469. rsm->is_pipe = TRUE;
  2470. } else {
  2471. rsm->F = fopen_for_read(L.s); /* not xfopen! */
  2472. }
  2473. }
  2474. } else {
  2475. if (!iF)
  2476. iF = next_input_file();
  2477. rsm = iF;
  2478. }
  2479. if (!rsm || !rsm->F) {
  2480. setvar_i(intvar[ERRNO], errno);
  2481. setvar_i(res, -1);
  2482. break;
  2483. }
  2484. if (!op->r.n)
  2485. R.v = intvar[F0];
  2486. i = awk_getline(rsm, R.v);
  2487. if (i > 0 && !op1) {
  2488. incvar(intvar[FNR]);
  2489. incvar(intvar[NR]);
  2490. }
  2491. setvar_i(res, i);
  2492. break;
  2493. }
  2494. /* simple builtins */
  2495. case XC( OC_FBLTIN ): {
  2496. double R_d = R_d; /* for compiler */
  2497. switch (opn) {
  2498. case F_in:
  2499. R_d = (long long)L_d;
  2500. break;
  2501. case F_rn:
  2502. R_d = (double)rand() / (double)RAND_MAX;
  2503. break;
  2504. case F_co:
  2505. if (ENABLE_FEATURE_AWK_LIBM) {
  2506. R_d = cos(L_d);
  2507. break;
  2508. }
  2509. case F_ex:
  2510. if (ENABLE_FEATURE_AWK_LIBM) {
  2511. R_d = exp(L_d);
  2512. break;
  2513. }
  2514. case F_lg:
  2515. if (ENABLE_FEATURE_AWK_LIBM) {
  2516. R_d = log(L_d);
  2517. break;
  2518. }
  2519. case F_si:
  2520. if (ENABLE_FEATURE_AWK_LIBM) {
  2521. R_d = sin(L_d);
  2522. break;
  2523. }
  2524. case F_sq:
  2525. if (ENABLE_FEATURE_AWK_LIBM) {
  2526. R_d = sqrt(L_d);
  2527. break;
  2528. }
  2529. syntax_error(EMSG_NO_MATH);
  2530. break;
  2531. case F_sr:
  2532. R_d = (double)seed;
  2533. seed = op1 ? (unsigned)L_d : (unsigned)time(NULL);
  2534. srand(seed);
  2535. break;
  2536. case F_ti:
  2537. R_d = time(NULL);
  2538. break;
  2539. case F_le:
  2540. debug_printf_eval("length: L.s:'%s'\n", L.s);
  2541. if (!op1) {
  2542. L.s = getvar_s(intvar[F0]);
  2543. debug_printf_eval("length: L.s='%s'\n", L.s);
  2544. }
  2545. else if (L.v->type & VF_ARRAY) {
  2546. R_d = L.v->x.array->nel;
  2547. debug_printf_eval("length: array_len:%d\n", L.v->x.array->nel);
  2548. break;
  2549. }
  2550. R_d = strlen(L.s);
  2551. break;
  2552. case F_sy:
  2553. fflush_all();
  2554. R_d = (ENABLE_FEATURE_ALLOW_EXEC && L.s && *L.s)
  2555. ? (system(L.s) >> 8) : 0;
  2556. break;
  2557. case F_ff:
  2558. if (!op1) {
  2559. fflush(stdout);
  2560. } else if (L.s && *L.s) {
  2561. rstream *rsm = newfile(L.s);
  2562. fflush(rsm->F);
  2563. } else {
  2564. fflush_all();
  2565. }
  2566. break;
  2567. case F_cl: {
  2568. rstream *rsm;
  2569. int err = 0;
  2570. rsm = (rstream *)hash_search(fdhash, L.s);
  2571. debug_printf_eval("OC_FBLTIN F_cl rsm:%p\n", rsm);
  2572. if (rsm) {
  2573. debug_printf_eval("OC_FBLTIN F_cl "
  2574. "rsm->is_pipe:%d, ->F:%p\n",
  2575. rsm->is_pipe, rsm->F);
  2576. /* Can be NULL if open failed. Example:
  2577. * getline line <"doesnt_exist";
  2578. * close("doesnt_exist"); <--- here rsm->F is NULL
  2579. */
  2580. if (rsm->F)
  2581. err = rsm->is_pipe ? pclose(rsm->F) : fclose(rsm->F);
  2582. free(rsm->buffer);
  2583. hash_remove(fdhash, L.s);
  2584. }
  2585. if (err)
  2586. setvar_i(intvar[ERRNO], errno);
  2587. R_d = (double)err;
  2588. break;
  2589. }
  2590. } /* switch */
  2591. setvar_i(res, R_d);
  2592. break;
  2593. }
  2594. case XC( OC_BUILTIN ):
  2595. res = exec_builtin(op, res);
  2596. break;
  2597. case XC( OC_SPRINTF ):
  2598. setvar_p(res, awk_printf(op1));
  2599. break;
  2600. case XC( OC_UNARY ): {
  2601. double Ld, R_d;
  2602. Ld = R_d = getvar_i(R.v);
  2603. switch (opn) {
  2604. case 'P':
  2605. Ld = ++R_d;
  2606. goto r_op_change;
  2607. case 'p':
  2608. R_d++;
  2609. goto r_op_change;
  2610. case 'M':
  2611. Ld = --R_d;
  2612. goto r_op_change;
  2613. case 'm':
  2614. R_d--;
  2615. r_op_change:
  2616. setvar_i(R.v, R_d);
  2617. break;
  2618. case '!':
  2619. Ld = !istrue(R.v);
  2620. break;
  2621. case '-':
  2622. Ld = -R_d;
  2623. break;
  2624. }
  2625. setvar_i(res, Ld);
  2626. break;
  2627. }
  2628. case XC( OC_FIELD ): {
  2629. int i = (int)getvar_i(R.v);
  2630. if (i < 0)
  2631. syntax_error(EMSG_NEGATIVE_FIELD);
  2632. if (i == 0) {
  2633. res = intvar[F0];
  2634. } else {
  2635. split_f0();
  2636. if (i > nfields)
  2637. fsrealloc(i);
  2638. res = &Fields[i - 1];
  2639. }
  2640. break;
  2641. }
  2642. /* concatenation (" ") and index joining (",") */
  2643. case XC( OC_CONCAT ):
  2644. case XC( OC_COMMA ): {
  2645. const char *sep = "";
  2646. if ((opinfo & OPCLSMASK) == OC_COMMA)
  2647. sep = getvar_s(intvar[SUBSEP]);
  2648. setvar_p(res, xasprintf("%s%s%s", L.s, sep, R.s));
  2649. break;
  2650. }
  2651. case XC( OC_LAND ):
  2652. setvar_i(res, istrue(L.v) ? ptest(op->r.n) : 0);
  2653. break;
  2654. case XC( OC_LOR ):
  2655. setvar_i(res, istrue(L.v) ? 1 : ptest(op->r.n));
  2656. break;
  2657. case XC( OC_BINARY ):
  2658. case XC( OC_REPLACE ): {
  2659. double R_d = getvar_i(R.v);
  2660. debug_printf_eval("BINARY/REPLACE: R_d:%f opn:%c\n", R_d, opn);
  2661. switch (opn) {
  2662. case '+':
  2663. L_d += R_d;
  2664. break;
  2665. case '-':
  2666. L_d -= R_d;
  2667. break;
  2668. case '*':
  2669. L_d *= R_d;
  2670. break;
  2671. case '/':
  2672. if (R_d == 0)
  2673. syntax_error(EMSG_DIV_BY_ZERO);
  2674. L_d /= R_d;
  2675. break;
  2676. case '&':
  2677. if (ENABLE_FEATURE_AWK_LIBM)
  2678. L_d = pow(L_d, R_d);
  2679. else
  2680. syntax_error(EMSG_NO_MATH);
  2681. break;
  2682. case '%':
  2683. if (R_d == 0)
  2684. syntax_error(EMSG_DIV_BY_ZERO);
  2685. L_d -= (long long)(L_d / R_d) * R_d;
  2686. break;
  2687. }
  2688. debug_printf_eval("BINARY/REPLACE result:%f\n", L_d);
  2689. res = setvar_i(((opinfo & OPCLSMASK) == OC_BINARY) ? res : L.v, L_d);
  2690. break;
  2691. }
  2692. case XC( OC_COMPARE ): {
  2693. int i = i; /* for compiler */
  2694. double Ld;
  2695. if (is_numeric(L.v) && is_numeric(R.v)) {
  2696. Ld = getvar_i(L.v) - getvar_i(R.v);
  2697. } else {
  2698. const char *l = getvar_s(L.v);
  2699. const char *r = getvar_s(R.v);
  2700. Ld = icase ? strcasecmp(l, r) : strcmp(l, r);
  2701. }
  2702. switch (opn & 0xfe) {
  2703. case 0:
  2704. i = (Ld > 0);
  2705. break;
  2706. case 2:
  2707. i = (Ld >= 0);
  2708. break;
  2709. case 4:
  2710. i = (Ld == 0);
  2711. break;
  2712. }
  2713. setvar_i(res, (i == 0) ^ (opn & 1));
  2714. break;
  2715. }
  2716. default:
  2717. syntax_error(EMSG_POSSIBLE_ERROR);
  2718. } /* switch */
  2719. next:
  2720. if ((opinfo & OPCLSMASK) <= SHIFT_TIL_THIS)
  2721. op = op->a.n;
  2722. if ((opinfo & OPCLSMASK) >= RECUR_FROM_THIS)
  2723. break;
  2724. if (nextrec)
  2725. break;
  2726. } /* while (op) */
  2727. nvfree(v1);
  2728. debug_printf_eval("returning from %s(): %p\n", __func__, res);
  2729. return res;
  2730. #undef fnargs
  2731. #undef seed
  2732. #undef sreg
  2733. }
  2734. /* -------- main & co. -------- */
  2735. static int awk_exit(int r)
  2736. {
  2737. var tv;
  2738. unsigned i;
  2739. hash_item *hi;
  2740. zero_out_var(&tv);
  2741. if (!exiting) {
  2742. exiting = TRUE;
  2743. nextrec = FALSE;
  2744. evaluate(endseq.first, &tv);
  2745. }
  2746. /* waiting for children */
  2747. for (i = 0; i < fdhash->csize; i++) {
  2748. hi = fdhash->items[i];
  2749. while (hi) {
  2750. if (hi->data.rs.F && hi->data.rs.is_pipe)
  2751. pclose(hi->data.rs.F);
  2752. hi = hi->next;
  2753. }
  2754. }
  2755. exit(r);
  2756. }
  2757. /* if expr looks like "var=value", perform assignment and return 1,
  2758. * otherwise return 0 */
  2759. static int is_assignment(const char *expr)
  2760. {
  2761. char *exprc, *val;
  2762. if (!isalnum_(*expr) || (val = strchr(expr, '=')) == NULL) {
  2763. return FALSE;
  2764. }
  2765. exprc = xstrdup(expr);
  2766. val = exprc + (val - expr);
  2767. *val++ = '\0';
  2768. unescape_string_in_place(val);
  2769. setvar_u(newvar(exprc), val);
  2770. free(exprc);
  2771. return TRUE;
  2772. }
  2773. /* switch to next input file */
  2774. static rstream *next_input_file(void)
  2775. {
  2776. #define rsm (G.next_input_file__rsm)
  2777. #define files_happen (G.next_input_file__files_happen)
  2778. FILE *F;
  2779. const char *fname, *ind;
  2780. if (rsm.F)
  2781. fclose(rsm.F);
  2782. rsm.F = NULL;
  2783. rsm.pos = rsm.adv = 0;
  2784. for (;;) {
  2785. if (getvar_i(intvar[ARGIND])+1 >= getvar_i(intvar[ARGC])) {
  2786. if (files_happen)
  2787. return NULL;
  2788. fname = "-";
  2789. F = stdin;
  2790. break;
  2791. }
  2792. ind = getvar_s(incvar(intvar[ARGIND]));
  2793. fname = getvar_s(findvar(iamarray(intvar[ARGV]), ind));
  2794. if (fname && *fname && !is_assignment(fname)) {
  2795. F = xfopen_stdin(fname);
  2796. break;
  2797. }
  2798. }
  2799. files_happen = TRUE;
  2800. setvar_s(intvar[FILENAME], fname);
  2801. rsm.F = F;
  2802. return &rsm;
  2803. #undef rsm
  2804. #undef files_happen
  2805. }
  2806. int awk_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  2807. int awk_main(int argc UNUSED_PARAM, char **argv)
  2808. {
  2809. unsigned opt;
  2810. char *opt_F;
  2811. llist_t *list_v = NULL;
  2812. llist_t *list_f = NULL;
  2813. #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  2814. llist_t *list_e = NULL;
  2815. #endif
  2816. int i, j;
  2817. var *v;
  2818. var tv;
  2819. char **envp;
  2820. char *vnames = (char *)vNames; /* cheat */
  2821. char *vvalues = (char *)vValues;
  2822. INIT_G();
  2823. /* Undo busybox.c, or else strtod may eat ','! This breaks parsing:
  2824. * $1,$2 == '$1,' '$2', NOT '$1' ',' '$2' */
  2825. if (ENABLE_LOCALE_SUPPORT)
  2826. setlocale(LC_NUMERIC, "C");
  2827. zero_out_var(&tv);
  2828. /* allocate global buffer */
  2829. g_buf = xmalloc(MAXVARFMT + 1);
  2830. vhash = hash_init();
  2831. ahash = hash_init();
  2832. fdhash = hash_init();
  2833. fnhash = hash_init();
  2834. /* initialize variables */
  2835. for (i = 0; *vnames; i++) {
  2836. intvar[i] = v = newvar(nextword(&vnames));
  2837. if (*vvalues != '\377')
  2838. setvar_s(v, nextword(&vvalues));
  2839. else
  2840. setvar_i(v, 0);
  2841. if (*vnames == '*') {
  2842. v->type |= VF_SPECIAL;
  2843. vnames++;
  2844. }
  2845. }
  2846. handle_special(intvar[FS]);
  2847. handle_special(intvar[RS]);
  2848. newfile("/dev/stdin")->F = stdin;
  2849. newfile("/dev/stdout")->F = stdout;
  2850. newfile("/dev/stderr")->F = stderr;
  2851. /* Huh, people report that sometimes environ is NULL. Oh well. */
  2852. if (environ) for (envp = environ; *envp; envp++) {
  2853. /* environ is writable, thus we don't strdup it needlessly */
  2854. char *s = *envp;
  2855. char *s1 = strchr(s, '=');
  2856. if (s1) {
  2857. *s1 = '\0';
  2858. /* Both findvar and setvar_u take const char*
  2859. * as 2nd arg -> environment is not trashed */
  2860. setvar_u(findvar(iamarray(intvar[ENVIRON]), s), s1 + 1);
  2861. *s1 = '=';
  2862. }
  2863. }
  2864. opt = getopt32(argv, OPTSTR_AWK, &opt_F, &list_v, &list_f, IF_FEATURE_AWK_GNU_EXTENSIONS(&list_e,) NULL);
  2865. argv += optind;
  2866. //argc -= optind;
  2867. if (opt & OPT_W)
  2868. bb_simple_error_msg("warning: option -W is ignored");
  2869. if (opt & OPT_F) {
  2870. unescape_string_in_place(opt_F);
  2871. setvar_s(intvar[FS], opt_F);
  2872. }
  2873. while (list_v) {
  2874. if (!is_assignment(llist_pop(&list_v)))
  2875. bb_show_usage();
  2876. }
  2877. while (list_f) {
  2878. char *s = NULL;
  2879. FILE *from_file;
  2880. g_progname = llist_pop(&list_f);
  2881. from_file = xfopen_stdin(g_progname);
  2882. /* one byte is reserved for some trick in next_token */
  2883. for (i = j = 1; j > 0; i += j) {
  2884. s = xrealloc(s, i + 4096);
  2885. j = fread(s + i, 1, 4094, from_file);
  2886. }
  2887. s[i] = '\0';
  2888. fclose(from_file);
  2889. parse_program(s + 1);
  2890. free(s);
  2891. }
  2892. g_progname = "cmd. line";
  2893. #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  2894. while (list_e) {
  2895. parse_program(llist_pop(&list_e));
  2896. }
  2897. #endif
  2898. if (!(opt & (OPT_f | OPT_e))) {
  2899. if (!*argv)
  2900. bb_show_usage();
  2901. parse_program(*argv++);
  2902. }
  2903. /* fill in ARGV array */
  2904. setari_u(intvar[ARGV], 0, "awk");
  2905. i = 0;
  2906. while (*argv)
  2907. setari_u(intvar[ARGV], ++i, *argv++);
  2908. setvar_i(intvar[ARGC], i + 1);
  2909. evaluate(beginseq.first, &tv);
  2910. if (!mainseq.first && !endseq.first)
  2911. awk_exit(EXIT_SUCCESS);
  2912. /* input file could already be opened in BEGIN block */
  2913. if (!iF)
  2914. iF = next_input_file();
  2915. /* passing through input files */
  2916. while (iF) {
  2917. nextfile = FALSE;
  2918. setvar_i(intvar[FNR], 0);
  2919. while ((i = awk_getline(iF, intvar[F0])) > 0) {
  2920. nextrec = FALSE;
  2921. incvar(intvar[NR]);
  2922. incvar(intvar[FNR]);
  2923. evaluate(mainseq.first, &tv);
  2924. if (nextfile)
  2925. break;
  2926. }
  2927. if (i < 0)
  2928. syntax_error(strerror(errno));
  2929. iF = next_input_file();
  2930. }
  2931. awk_exit(EXIT_SUCCESS);
  2932. /*return 0;*/
  2933. }