3
0

awk.c 92 KB

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