awk.c 78 KB

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