3
0

awk.c 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730
  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. again:
  759. c = *(*s)++;
  760. pps = *s;
  761. if (c == '\\')
  762. c = bb_process_escape_sequence((const char**)s);
  763. /* Example awk statement:
  764. * s = "abc\"def"
  765. * we must treat \" as "
  766. */
  767. if (c == '\\' && *s == pps) { /* unrecognized \z? */
  768. c = *(*s); /* yes, fetch z */
  769. if (c) { /* advance unless z = NUL */
  770. (*s)++;
  771. if (c == '\n') /* \<newline>? eat it */
  772. goto again;
  773. }
  774. }
  775. return c;
  776. }
  777. /* TODO: merge with strcpy_and_process_escape_sequences()?
  778. */
  779. static void unescape_string_in_place(char *s1)
  780. {
  781. char *s = s1;
  782. while ((*s1 = nextchar(&s)) != '\0')
  783. s1++;
  784. }
  785. static ALWAYS_INLINE int isalnum_(int c)
  786. {
  787. return (isalnum(c) || c == '_');
  788. }
  789. static double my_strtod(char **pp)
  790. {
  791. char *cp = *pp;
  792. return strtod(cp, pp);
  793. }
  794. #if ENABLE_DESKTOP
  795. static double my_strtod_or_hexoct(char **pp)
  796. {
  797. char *cp = *pp;
  798. if (cp[0] == '0') {
  799. /* Might be hex or octal integer: 0x123abc or 07777 */
  800. char c = (cp[1] | 0x20);
  801. if (c == 'x' || isdigit(cp[1])) {
  802. unsigned long long ull = strtoull(cp, pp, 0);
  803. if (c == 'x')
  804. return ull;
  805. c = **pp;
  806. if (!isdigit(c) && c != '.')
  807. return ull;
  808. /* else: it may be a floating number. Examples:
  809. * 009.123 (*pp points to '9')
  810. * 000.123 (*pp points to '.')
  811. * fall through to strtod.
  812. */
  813. }
  814. }
  815. return strtod(cp, pp);
  816. }
  817. #else
  818. # define my_strtod_or_hexoct(p) my_strtod(p)
  819. #endif
  820. /* -------- working with variables (set/get/copy/etc) -------- */
  821. static void fmt_num(const char *format, double n)
  822. {
  823. if (n == (long long)n) {
  824. snprintf(g_buf, MAXVARFMT, "%lld", (long long)n);
  825. } else {
  826. const char *s = format;
  827. char c;
  828. do { c = *s; } while (c && *++s);
  829. if (strchr("diouxX", c)) {
  830. snprintf(g_buf, MAXVARFMT, format, (int)n);
  831. } else if (strchr("eEfFgGaA", c)) {
  832. snprintf(g_buf, MAXVARFMT, format, n);
  833. } else {
  834. syntax_error(EMSG_INV_FMT);
  835. }
  836. }
  837. }
  838. static xhash *iamarray(var *a)
  839. {
  840. while (a->type & VF_CHILD)
  841. a = a->x.parent;
  842. if (!(a->type & VF_ARRAY)) {
  843. a->type |= VF_ARRAY;
  844. a->x.array = hash_init();
  845. }
  846. return a->x.array;
  847. }
  848. #define clear_array(array) hash_clear(array)
  849. /* clear a variable */
  850. static var *clrvar(var *v)
  851. {
  852. if (!(v->type & VF_FSTR))
  853. free(v->string);
  854. v->type &= VF_DONTTOUCH;
  855. v->type |= VF_DIRTY;
  856. v->string = NULL;
  857. return v;
  858. }
  859. static void handle_special(var *);
  860. /* assign string value to variable */
  861. static var *setvar_p(var *v, char *value)
  862. {
  863. clrvar(v);
  864. v->string = value;
  865. handle_special(v);
  866. return v;
  867. }
  868. /* same as setvar_p but make a copy of string */
  869. static var *setvar_s(var *v, const char *value)
  870. {
  871. return setvar_p(v, (value && *value) ? xstrdup(value) : NULL);
  872. }
  873. /* same as setvar_s but sets USER flag */
  874. static var *setvar_u(var *v, const char *value)
  875. {
  876. v = setvar_s(v, value);
  877. v->type |= VF_USER;
  878. return v;
  879. }
  880. /* set array element to user string */
  881. static void setari_u(var *a, int idx, const char *s)
  882. {
  883. var *v;
  884. v = findvar(iamarray(a), itoa(idx));
  885. setvar_u(v, s);
  886. }
  887. /* assign numeric value to variable */
  888. static var *setvar_i(var *v, double value)
  889. {
  890. clrvar(v);
  891. v->type |= VF_NUMBER;
  892. v->number = value;
  893. handle_special(v);
  894. return v;
  895. }
  896. static const char *getvar_s(var *v)
  897. {
  898. /* if v is numeric and has no cached string, convert it to string */
  899. if ((v->type & (VF_NUMBER | VF_CACHED)) == VF_NUMBER) {
  900. fmt_num(getvar_s(intvar[CONVFMT]), v->number);
  901. v->string = xstrdup(g_buf);
  902. v->type |= VF_CACHED;
  903. }
  904. return (v->string == NULL) ? "" : v->string;
  905. }
  906. static double getvar_i(var *v)
  907. {
  908. char *s;
  909. if ((v->type & (VF_NUMBER | VF_CACHED)) == 0) {
  910. v->number = 0;
  911. s = v->string;
  912. if (s && *s) {
  913. debug_printf_eval("getvar_i: '%s'->", s);
  914. v->number = my_strtod(&s);
  915. /* ^^^ hex/oct NOT allowed here! */
  916. debug_printf_eval("%f (s:'%s')\n", v->number, s);
  917. if (v->type & VF_USER) {
  918. //TODO: skip_spaces() also skips backslash+newline, is it intended here?
  919. s = skip_spaces(s);
  920. if (*s != '\0')
  921. v->type &= ~VF_USER;
  922. }
  923. } else {
  924. debug_printf_eval("getvar_i: '%s'->zero\n", s);
  925. v->type &= ~VF_USER;
  926. }
  927. v->type |= VF_CACHED;
  928. }
  929. debug_printf_eval("getvar_i: %f\n", v->number);
  930. return v->number;
  931. }
  932. /* Used for operands of bitwise ops */
  933. static unsigned long getvar_i_int(var *v)
  934. {
  935. double d = getvar_i(v);
  936. /* Casting doubles to longs is undefined for values outside
  937. * of target type range. Try to widen it as much as possible */
  938. if (d >= 0)
  939. return (unsigned long)d;
  940. /* Why? Think about d == -4294967295.0 (assuming 32bit longs) */
  941. return - (long) (unsigned long) (-d);
  942. }
  943. static var *copyvar(var *dest, const var *src)
  944. {
  945. if (dest != src) {
  946. clrvar(dest);
  947. dest->type |= (src->type & ~(VF_DONTTOUCH | VF_FSTR));
  948. debug_printf_eval("copyvar: number:%f string:'%s'\n", src->number, src->string);
  949. dest->number = src->number;
  950. if (src->string)
  951. dest->string = xstrdup(src->string);
  952. }
  953. handle_special(dest);
  954. return dest;
  955. }
  956. static var *incvar(var *v)
  957. {
  958. return setvar_i(v, getvar_i(v) + 1.0);
  959. }
  960. /* return true if v is number or numeric string */
  961. static int is_numeric(var *v)
  962. {
  963. getvar_i(v);
  964. return ((v->type ^ VF_DIRTY) & (VF_NUMBER | VF_USER | VF_DIRTY));
  965. }
  966. /* return 1 when value of v corresponds to true, 0 otherwise */
  967. static int istrue(var *v)
  968. {
  969. if (is_numeric(v))
  970. return (v->number != 0);
  971. return (v->string && v->string[0]);
  972. }
  973. /* ------- awk program text parsing ------- */
  974. /* Parse next token pointed by global pos, place results into global t_XYZ variables.
  975. * If token isn't expected, print error message and die.
  976. * Return token class (also store it in t_tclass).
  977. */
  978. static uint32_t next_token(uint32_t expected)
  979. {
  980. #define concat_inserted (G1.next_token__concat_inserted)
  981. #define save_tclass (G1.next_token__save_tclass)
  982. #define save_info (G1.next_token__save_info)
  983. char *p;
  984. const char *tl;
  985. const uint32_t *ti;
  986. uint32_t tc, last_token_class;
  987. last_token_class = t_tclass; /* t_tclass is initialized to TC_NEWLINE */
  988. debug_printf_parse("%s() expected(%x):", __func__, expected);
  989. debug_parse_print_tc(expected);
  990. debug_printf_parse("\n");
  991. if (t_rollback) {
  992. debug_printf_parse("%s: using rolled-back token\n", __func__);
  993. t_rollback = FALSE;
  994. } else if (concat_inserted) {
  995. debug_printf_parse("%s: using concat-inserted token\n", __func__);
  996. concat_inserted = FALSE;
  997. t_tclass = save_tclass;
  998. t_info = save_info;
  999. } else {
  1000. p = g_pos;
  1001. if (g_saved_ch != '\0') {
  1002. *p = g_saved_ch;
  1003. g_saved_ch = '\0';
  1004. }
  1005. readnext:
  1006. p = skip_spaces(p);
  1007. g_lineno = t_lineno;
  1008. if (*p == '#')
  1009. while (*p != '\n' && *p != '\0')
  1010. p++;
  1011. if (*p == '\0') {
  1012. tc = TC_EOF;
  1013. debug_printf_parse("%s: token found: TC_EOF\n", __func__);
  1014. } else if (*p == '"') {
  1015. /* it's a string */
  1016. char *s = t_string = ++p;
  1017. while (*p != '"') {
  1018. char *pp;
  1019. if (*p == '\0' || *p == '\n')
  1020. syntax_error(EMSG_UNEXP_EOS);
  1021. pp = p;
  1022. *s++ = nextchar(&pp);
  1023. p = pp;
  1024. }
  1025. p++;
  1026. *s = '\0';
  1027. tc = TC_STRING;
  1028. debug_printf_parse("%s: token found:'%s' TC_STRING\n", __func__, t_string);
  1029. } else if ((expected & TC_REGEXP) && *p == '/') {
  1030. /* it's regexp */
  1031. char *s = t_string = ++p;
  1032. while (*p != '/') {
  1033. if (*p == '\0' || *p == '\n')
  1034. syntax_error(EMSG_UNEXP_EOS);
  1035. *s = *p++;
  1036. if (*s++ == '\\') {
  1037. char *pp = p;
  1038. s[-1] = bb_process_escape_sequence((const char **)&pp);
  1039. if (*p == '\\')
  1040. *s++ = '\\';
  1041. if (pp == p)
  1042. *s++ = *p++;
  1043. else
  1044. p = pp;
  1045. }
  1046. }
  1047. p++;
  1048. *s = '\0';
  1049. tc = TC_REGEXP;
  1050. debug_printf_parse("%s: token found:'%s' TC_REGEXP\n", __func__, t_string);
  1051. } else if (*p == '.' || isdigit(*p)) {
  1052. /* it's a number */
  1053. char *pp = p;
  1054. t_double = my_strtod_or_hexoct(&pp);
  1055. /* ^^^ awk only allows hex/oct consts in _program_, not in _input_ */
  1056. p = pp;
  1057. if (*p == '.')
  1058. syntax_error(EMSG_UNEXP_TOKEN);
  1059. tc = TC_NUMBER;
  1060. debug_printf_parse("%s: token found:%f TC_NUMBER\n", __func__, t_double);
  1061. } else {
  1062. char *end_of_name;
  1063. if (*p == '\n')
  1064. t_lineno++;
  1065. /* search for something known */
  1066. tl = tokenlist;
  1067. tc = 0x00000001;
  1068. ti = tokeninfo;
  1069. while (*tl) {
  1070. int l = (unsigned char) *tl++;
  1071. if (l == (unsigned char) NTCC) {
  1072. tc <<= 1;
  1073. continue;
  1074. }
  1075. /* if token class is expected,
  1076. * token matches,
  1077. * and it's not a longer word,
  1078. */
  1079. if ((tc & (expected | TS_WORD | TC_NEWLINE))
  1080. && strncmp(p, tl, l) == 0
  1081. && !((tc & TS_WORD) && isalnum_(p[l]))
  1082. ) {
  1083. /* then this is what we are looking for */
  1084. t_info = *ti;
  1085. debug_printf_parse("%s: token found:'%.*s' t_info:%x\n", __func__, l, p, t_info);
  1086. p += l;
  1087. goto token_found;
  1088. }
  1089. ti++;
  1090. tl += l;
  1091. }
  1092. /* not a known token */
  1093. /* is it a name? (var/array/function) */
  1094. if (!isalnum_(*p))
  1095. syntax_error(EMSG_UNEXP_TOKEN); /* no */
  1096. /* yes */
  1097. t_string = p;
  1098. while (isalnum_(*p))
  1099. p++;
  1100. end_of_name = p;
  1101. if (last_token_class == TC_FUNCDECL)
  1102. /* eat space in "function FUNC (...) {...}" declaration */
  1103. p = skip_spaces(p);
  1104. else if (expected & TC_ARRAY) {
  1105. /* eat space between array name and [ */
  1106. char *s = skip_spaces(p);
  1107. if (*s == '[') /* array ref, not just a name? */
  1108. p = s;
  1109. }
  1110. /* else: do NOT consume whitespace after variable name!
  1111. * gawk allows definition "function FUNC (p) {...}" - note space,
  1112. * but disallows the call "FUNC (p)" because it isn't one -
  1113. * expression "v (a)" should NOT be parsed as TC_FUNCTION:
  1114. * it is a valid concatenation if "v" is a variable,
  1115. * not a function name (and type of name is not known at parse time).
  1116. */
  1117. if (*p == '(') {
  1118. p++;
  1119. tc = TC_FUNCTION;
  1120. debug_printf_parse("%s: token found:'%s' TC_FUNCTION\n", __func__, t_string);
  1121. } else if (*p == '[') {
  1122. p++;
  1123. tc = TC_ARRAY;
  1124. debug_printf_parse("%s: token found:'%s' TC_ARRAY\n", __func__, t_string);
  1125. } else {
  1126. tc = TC_VARIABLE;
  1127. debug_printf_parse("%s: token found:'%s' TC_VARIABLE\n", __func__, t_string);
  1128. if (end_of_name == p) {
  1129. /* there is no space for trailing NUL in t_string!
  1130. * We need to save the char we are going to NUL.
  1131. * (we'll use it in future call to next_token())
  1132. */
  1133. g_saved_ch = *end_of_name;
  1134. // especially pathological example is V="abc"; V.2 - it's V concatenated to .2
  1135. // (it evaluates to "abc0.2"). Because of this case, we can't simply cache
  1136. // '.' and analyze it later: we also have to *store it back* in next
  1137. // next_token(), in order to give my_strtod() the undamaged ".2" string.
  1138. }
  1139. }
  1140. *end_of_name = '\0'; /* terminate t_string */
  1141. }
  1142. token_found:
  1143. g_pos = p;
  1144. /* skipping newlines in some cases */
  1145. if ((last_token_class & TS_NOTERM) && (tc & TC_NEWLINE))
  1146. goto readnext;
  1147. /* insert concatenation operator when needed */
  1148. debug_printf_parse("%s: concat_inserted if all nonzero: %x %x %x %x\n", __func__,
  1149. (last_token_class & TS_CONCAT_L), (tc & TS_CONCAT_R), (expected & TS_BINOP),
  1150. !(last_token_class == TC_LENGTH && tc == TC_LPAREN));
  1151. if ((last_token_class & TS_CONCAT_L) && (tc & TS_CONCAT_R) && (expected & TS_BINOP)
  1152. && !(last_token_class == TC_LENGTH && tc == TC_LPAREN) /* but not for "length(..." */
  1153. ) {
  1154. concat_inserted = TRUE;
  1155. save_tclass = tc;
  1156. save_info = t_info;
  1157. tc = TC_BINOPX;
  1158. t_info = OC_CONCAT | SS | P(35);
  1159. }
  1160. t_tclass = tc;
  1161. debug_printf_parse("%s: t_tclass=tc=%x\n", __func__, tc);
  1162. }
  1163. /* Are we ready for this? */
  1164. if (!(t_tclass & expected)) {
  1165. syntax_error((last_token_class & (TC_NEWLINE | TC_EOF)) ?
  1166. EMSG_UNEXP_EOS : EMSG_UNEXP_TOKEN);
  1167. }
  1168. debug_printf_parse("%s: returning, t_double:%f t_tclass:", __func__, t_double);
  1169. debug_parse_print_tc(t_tclass);
  1170. debug_printf_parse("\n");
  1171. return t_tclass;
  1172. #undef concat_inserted
  1173. #undef save_tclass
  1174. #undef save_info
  1175. }
  1176. static ALWAYS_INLINE void rollback_token(void)
  1177. {
  1178. t_rollback = TRUE;
  1179. }
  1180. static node *new_node(uint32_t info)
  1181. {
  1182. node *n;
  1183. n = xzalloc(sizeof(node));
  1184. n->info = info;
  1185. n->lineno = g_lineno;
  1186. return n;
  1187. }
  1188. static void mk_re_node(const char *s, node *n, regex_t *re)
  1189. {
  1190. n->info = TI_REGEXP;
  1191. n->l.re = re;
  1192. n->r.ire = re + 1;
  1193. xregcomp(re, s, REG_EXTENDED);
  1194. xregcomp(re + 1, s, REG_EXTENDED | REG_ICASE);
  1195. }
  1196. static node *parse_expr(uint32_t);
  1197. static node *parse_lrparen_list(void)
  1198. {
  1199. next_token(TC_LPAREN);
  1200. return parse_expr(TC_RPAREN);
  1201. }
  1202. /* parse expression terminated by given argument, return ptr
  1203. * to built subtree. Terminator is eaten by parse_expr */
  1204. static node *parse_expr(uint32_t term_tc)
  1205. {
  1206. node sn;
  1207. node *cn = &sn;
  1208. node *vn, *glptr;
  1209. uint32_t tc, expected_tc;
  1210. var *v;
  1211. debug_printf_parse("%s() term_tc(%x):", __func__, term_tc);
  1212. debug_parse_print_tc(term_tc);
  1213. debug_printf_parse("\n");
  1214. sn.info = PRIMASK;
  1215. sn.r.n = sn.a.n = glptr = NULL;
  1216. expected_tc = TS_OPERAND | TS_UOPPRE | TC_REGEXP | term_tc;
  1217. while (!((tc = next_token(expected_tc)) & term_tc)) {
  1218. if (glptr && (t_info == TI_LESS)) {
  1219. /* input redirection (<) attached to glptr node */
  1220. debug_printf_parse("%s: input redir\n", __func__);
  1221. cn = glptr->l.n = new_node(OC_CONCAT | SS | P(37));
  1222. cn->a.n = glptr;
  1223. expected_tc = TS_OPERAND | TS_UOPPRE;
  1224. glptr = NULL;
  1225. continue;
  1226. }
  1227. if (tc & (TS_BINOP | TC_UOPPOST)) {
  1228. debug_printf_parse("%s: TS_BINOP | TC_UOPPOST tc:%x\n", __func__, tc);
  1229. /* for binary and postfix-unary operators, jump back over
  1230. * previous operators with higher priority */
  1231. vn = cn;
  1232. while (((t_info & PRIMASK) > (vn->a.n->info & PRIMASK2))
  1233. || ((t_info == vn->info) && t_info == TI_COLON)
  1234. ) {
  1235. vn = vn->a.n;
  1236. if (!vn->a.n) syntax_error(EMSG_UNEXP_TOKEN);
  1237. }
  1238. if (t_info == TI_TERNARY)
  1239. //TODO: why?
  1240. t_info += P(6);
  1241. cn = vn->a.n->r.n = new_node(t_info);
  1242. cn->a.n = vn->a.n;
  1243. if (tc & TS_BINOP) {
  1244. cn->l.n = vn;
  1245. //FIXME: this is the place to detect and reject assignments to non-lvalues.
  1246. //Currently we allow "assignments" to consts and temporaries, nonsense like this:
  1247. // awk 'BEGIN { "qwe" = 1 }'
  1248. // awk 'BEGIN { 7 *= 7 }'
  1249. // awk 'BEGIN { length("qwe") = 1 }'
  1250. // awk 'BEGIN { (1+1) += 3 }'
  1251. expected_tc = TS_OPERAND | TS_UOPPRE | TC_REGEXP;
  1252. if (t_info == TI_PGETLINE) {
  1253. /* it's a pipe */
  1254. next_token(TC_GETLINE);
  1255. /* give maximum priority to this pipe */
  1256. cn->info &= ~PRIMASK;
  1257. expected_tc = TS_OPERAND | TS_UOPPRE | TS_BINOP | term_tc;
  1258. }
  1259. } else {
  1260. cn->r.n = vn;
  1261. expected_tc = TS_OPERAND | TS_UOPPRE | TS_BINOP | term_tc;
  1262. }
  1263. vn->a.n = cn;
  1264. continue;
  1265. }
  1266. debug_printf_parse("%s: other, t_info:%x\n", __func__, t_info);
  1267. /* for operands and prefix-unary operators, attach them
  1268. * to last node */
  1269. vn = cn;
  1270. cn = vn->r.n = new_node(t_info);
  1271. cn->a.n = vn;
  1272. expected_tc = TS_OPERAND | TS_UOPPRE | TC_REGEXP;
  1273. if (t_info == TI_PREINC || t_info == TI_PREDEC)
  1274. expected_tc = TS_LVALUE | TC_UOPPRE1;
  1275. if (!(tc & (TS_OPERAND | TC_REGEXP)))
  1276. continue;
  1277. debug_printf_parse("%s: TS_OPERAND | TC_REGEXP\n", __func__);
  1278. expected_tc = TS_UOPPRE | TC_UOPPOST | TS_BINOP | TS_OPERAND | term_tc;
  1279. /* one should be very careful with switch on tclass -
  1280. * only simple tclasses should be used (TC_xyz, not TS_xyz) */
  1281. switch (tc) {
  1282. case TC_VARIABLE:
  1283. case TC_ARRAY:
  1284. debug_printf_parse("%s: TC_VARIABLE | TC_ARRAY\n", __func__);
  1285. cn->info = OC_VAR;
  1286. v = hash_search(ahash, t_string);
  1287. if (v != NULL) {
  1288. cn->info = OC_FNARG;
  1289. cn->l.aidx = v->x.aidx;
  1290. } else {
  1291. cn->l.v = newvar(t_string);
  1292. }
  1293. if (tc & TC_ARRAY) {
  1294. cn->info |= xS;
  1295. cn->r.n = parse_expr(TC_ARRTERM);
  1296. }
  1297. break;
  1298. case TC_NUMBER:
  1299. case TC_STRING:
  1300. debug_printf_parse("%s: TC_NUMBER | TC_STRING\n", __func__);
  1301. cn->info = OC_VAR;
  1302. v = cn->l.v = xzalloc(sizeof(var));
  1303. if (tc & TC_NUMBER)
  1304. setvar_i(v, t_double);
  1305. else {
  1306. setvar_s(v, t_string);
  1307. expected_tc &= ~TC_UOPPOST; /* "str"++ is not allowed */
  1308. }
  1309. break;
  1310. case TC_REGEXP:
  1311. debug_printf_parse("%s: TC_REGEXP\n", __func__);
  1312. mk_re_node(t_string, cn, xzalloc(sizeof(regex_t)*2));
  1313. break;
  1314. case TC_FUNCTION:
  1315. debug_printf_parse("%s: TC_FUNCTION\n", __func__);
  1316. cn->info = OC_FUNC;
  1317. cn->r.f = newfunc(t_string);
  1318. cn->l.n = parse_expr(TC_RPAREN);
  1319. break;
  1320. case TC_LPAREN:
  1321. debug_printf_parse("%s: TC_LPAREN\n", __func__);
  1322. cn = vn->r.n = parse_expr(TC_RPAREN);
  1323. if (!cn)
  1324. syntax_error("Empty sequence");
  1325. cn->a.n = vn;
  1326. break;
  1327. case TC_GETLINE:
  1328. debug_printf_parse("%s: TC_GETLINE\n", __func__);
  1329. glptr = cn;
  1330. expected_tc = TS_OPERAND | TS_UOPPRE | TS_BINOP | term_tc;
  1331. break;
  1332. case TC_BUILTIN:
  1333. debug_printf_parse("%s: TC_BUILTIN\n", __func__);
  1334. cn->l.n = parse_lrparen_list();
  1335. break;
  1336. case TC_LENGTH:
  1337. debug_printf_parse("%s: TC_LENGTH\n", __func__);
  1338. tc = next_token(TC_LPAREN /* length(...) */
  1339. | TC_SEMICOL /* length; */
  1340. | TC_NEWLINE /* length<newline> */
  1341. | TC_RBRACE /* length } */
  1342. | TC_BINOPX /* length <op> NUM */
  1343. | TC_COMMA /* print length, 1 */
  1344. );
  1345. if (tc != TC_LPAREN)
  1346. rollback_token();
  1347. else {
  1348. /* It was a "(" token. Handle just like TC_BUILTIN */
  1349. cn->l.n = parse_expr(TC_RPAREN);
  1350. }
  1351. break;
  1352. }
  1353. } /* while() */
  1354. debug_printf_parse("%s() returns %p\n", __func__, sn.r.n);
  1355. return sn.r.n;
  1356. }
  1357. /* add node to chain. Return ptr to alloc'd node */
  1358. static node *chain_node(uint32_t info)
  1359. {
  1360. node *n;
  1361. if (!seq->first)
  1362. seq->first = seq->last = new_node(0);
  1363. if (seq->programname != g_progname) {
  1364. seq->programname = g_progname;
  1365. n = chain_node(OC_NEWSOURCE);
  1366. n->l.new_progname = g_progname;
  1367. }
  1368. n = seq->last;
  1369. n->info = info;
  1370. seq->last = n->a.n = new_node(OC_DONE);
  1371. return n;
  1372. }
  1373. static void chain_expr(uint32_t info)
  1374. {
  1375. node *n;
  1376. n = chain_node(info);
  1377. n->l.n = parse_expr(TC_SEMICOL | TC_NEWLINE | TC_RBRACE);
  1378. if ((info & OF_REQUIRED) && !n->l.n)
  1379. syntax_error(EMSG_TOO_FEW_ARGS);
  1380. if (t_tclass & TC_RBRACE)
  1381. rollback_token();
  1382. }
  1383. static void chain_group(void);
  1384. static node *chain_loop(node *nn)
  1385. {
  1386. node *n, *n2, *save_brk, *save_cont;
  1387. save_brk = break_ptr;
  1388. save_cont = continue_ptr;
  1389. n = chain_node(OC_BR | Vx);
  1390. continue_ptr = new_node(OC_EXEC);
  1391. break_ptr = new_node(OC_EXEC);
  1392. chain_group();
  1393. n2 = chain_node(OC_EXEC | Vx);
  1394. n2->l.n = nn;
  1395. n2->a.n = n;
  1396. continue_ptr->a.n = n2;
  1397. break_ptr->a.n = n->r.n = seq->last;
  1398. continue_ptr = save_cont;
  1399. break_ptr = save_brk;
  1400. return n;
  1401. }
  1402. static void chain_until_rbrace(void)
  1403. {
  1404. uint32_t tc;
  1405. while ((tc = next_token(TS_GRPSEQ | TC_RBRACE)) != TC_RBRACE) {
  1406. debug_printf_parse("%s: !TC_RBRACE\n", __func__);
  1407. if (tc == TC_NEWLINE)
  1408. continue;
  1409. rollback_token();
  1410. chain_group();
  1411. }
  1412. debug_printf_parse("%s: TC_RBRACE\n", __func__);
  1413. }
  1414. /* parse group and attach it to chain */
  1415. static void chain_group(void)
  1416. {
  1417. uint32_t tc;
  1418. node *n, *n2, *n3;
  1419. do {
  1420. tc = next_token(TS_GRPSEQ);
  1421. } while (tc == TC_NEWLINE);
  1422. if (tc == TC_LBRACE) {
  1423. debug_printf_parse("%s: TC_LBRACE\n", __func__);
  1424. chain_until_rbrace();
  1425. return;
  1426. }
  1427. if (tc & (TS_OPSEQ | TC_SEMICOL)) {
  1428. debug_printf_parse("%s: TS_OPSEQ | TC_SEMICOL\n", __func__);
  1429. rollback_token();
  1430. chain_expr(OC_EXEC | Vx);
  1431. return;
  1432. }
  1433. /* TS_STATEMNT */
  1434. debug_printf_parse("%s: TS_STATEMNT(?)\n", __func__);
  1435. switch (t_info & OPCLSMASK) {
  1436. case ST_IF:
  1437. debug_printf_parse("%s: ST_IF\n", __func__);
  1438. n = chain_node(OC_BR | Vx);
  1439. n->l.n = parse_lrparen_list();
  1440. chain_group();
  1441. n2 = chain_node(OC_EXEC);
  1442. n->r.n = seq->last;
  1443. if (next_token(TS_GRPSEQ | TC_RBRACE | TC_ELSE) == TC_ELSE) {
  1444. chain_group();
  1445. n2->a.n = seq->last;
  1446. } else {
  1447. rollback_token();
  1448. }
  1449. break;
  1450. case ST_WHILE:
  1451. debug_printf_parse("%s: ST_WHILE\n", __func__);
  1452. n2 = parse_lrparen_list();
  1453. n = chain_loop(NULL);
  1454. n->l.n = n2;
  1455. break;
  1456. case ST_DO:
  1457. debug_printf_parse("%s: ST_DO\n", __func__);
  1458. n2 = chain_node(OC_EXEC);
  1459. n = chain_loop(NULL);
  1460. n2->a.n = n->a.n;
  1461. next_token(TC_WHILE);
  1462. n->l.n = parse_lrparen_list();
  1463. break;
  1464. case ST_FOR:
  1465. debug_printf_parse("%s: ST_FOR\n", __func__);
  1466. next_token(TC_LPAREN);
  1467. n2 = parse_expr(TC_SEMICOL | TC_RPAREN);
  1468. if (t_tclass & TC_RPAREN) { /* for (I in ARRAY) */
  1469. if (!n2 || n2->info != TI_IN)
  1470. syntax_error(EMSG_UNEXP_TOKEN);
  1471. n = chain_node(OC_WALKINIT | VV);
  1472. n->l.n = n2->l.n;
  1473. n->r.n = n2->r.n;
  1474. n = chain_loop(NULL);
  1475. n->info = OC_WALKNEXT | Vx;
  1476. n->l.n = n2->l.n;
  1477. } else { /* for (;;) */
  1478. n = chain_node(OC_EXEC | Vx);
  1479. n->l.n = n2;
  1480. n2 = parse_expr(TC_SEMICOL);
  1481. n3 = parse_expr(TC_RPAREN);
  1482. n = chain_loop(n3);
  1483. n->l.n = n2;
  1484. if (!n2)
  1485. n->info = OC_EXEC;
  1486. }
  1487. break;
  1488. case OC_PRINT:
  1489. case OC_PRINTF:
  1490. debug_printf_parse("%s: OC_PRINT[F]\n", __func__);
  1491. n = chain_node(t_info);
  1492. n->l.n = parse_expr(TC_SEMICOL | TC_NEWLINE | TC_OUTRDR | TC_RBRACE);
  1493. if (t_tclass & TC_OUTRDR) {
  1494. n->info |= t_info;
  1495. n->r.n = parse_expr(TC_SEMICOL | TC_NEWLINE | TC_RBRACE);
  1496. }
  1497. if (t_tclass & TC_RBRACE)
  1498. rollback_token();
  1499. break;
  1500. case OC_BREAK:
  1501. debug_printf_parse("%s: OC_BREAK\n", __func__);
  1502. n = chain_node(OC_EXEC);
  1503. if (!break_ptr)
  1504. syntax_error("'break' not in a loop");
  1505. n->a.n = break_ptr;
  1506. chain_expr(t_info);
  1507. break;
  1508. case OC_CONTINUE:
  1509. debug_printf_parse("%s: OC_CONTINUE\n", __func__);
  1510. n = chain_node(OC_EXEC);
  1511. if (!continue_ptr)
  1512. syntax_error("'continue' not in a loop");
  1513. n->a.n = continue_ptr;
  1514. chain_expr(t_info);
  1515. break;
  1516. /* delete, next, nextfile, return, exit */
  1517. default:
  1518. debug_printf_parse("%s: default\n", __func__);
  1519. chain_expr(t_info);
  1520. }
  1521. }
  1522. static void parse_program(char *p)
  1523. {
  1524. debug_printf_parse("%s()\n", __func__);
  1525. g_pos = p;
  1526. t_lineno = 1;
  1527. for (;;) {
  1528. uint32_t tclass;
  1529. tclass = next_token(TS_OPSEQ | TC_LBRACE | TC_BEGIN | TC_END | TC_FUNCDECL
  1530. | TC_EOF | TC_NEWLINE /* but not TC_SEMICOL */);
  1531. got_tok:
  1532. if (tclass == TC_EOF) {
  1533. debug_printf_parse("%s: TC_EOF\n", __func__);
  1534. break;
  1535. }
  1536. if (tclass == TC_NEWLINE) {
  1537. debug_printf_parse("%s: TC_NEWLINE\n", __func__);
  1538. continue;
  1539. }
  1540. if (tclass == TC_BEGIN) {
  1541. debug_printf_parse("%s: TC_BEGIN\n", __func__);
  1542. seq = &beginseq;
  1543. /* ensure there is no newline between BEGIN and { */
  1544. next_token(TC_LBRACE);
  1545. chain_until_rbrace();
  1546. goto next_tok;
  1547. }
  1548. if (tclass == TC_END) {
  1549. debug_printf_parse("%s: TC_END\n", __func__);
  1550. seq = &endseq;
  1551. /* ensure there is no newline between END and { */
  1552. next_token(TC_LBRACE);
  1553. chain_until_rbrace();
  1554. goto next_tok;
  1555. }
  1556. if (tclass == TC_FUNCDECL) {
  1557. func *f;
  1558. debug_printf_parse("%s: TC_FUNCDECL\n", __func__);
  1559. next_token(TC_FUNCTION);
  1560. f = newfunc(t_string);
  1561. if (f->defined)
  1562. syntax_error("Duplicate function");
  1563. f->defined = 1;
  1564. //f->body.first = NULL; - already is
  1565. //f->nargs = 0; - already is
  1566. /* func arg list: comma sep list of args, and a close paren */
  1567. for (;;) {
  1568. var *v;
  1569. if (next_token(TC_VARIABLE | TC_RPAREN) == TC_RPAREN) {
  1570. if (f->nargs == 0)
  1571. break; /* func() is ok */
  1572. /* func(a,) is not ok */
  1573. syntax_error(EMSG_UNEXP_TOKEN);
  1574. }
  1575. v = findvar(ahash, t_string);
  1576. v->x.aidx = f->nargs++;
  1577. /* Arg followed either by end of arg list or 1 comma */
  1578. if (next_token(TC_COMMA | TC_RPAREN) == TC_RPAREN)
  1579. break;
  1580. /* it was a comma, we ate it */
  1581. }
  1582. seq = &f->body;
  1583. /* ensure there is { after "func F(...)" - but newlines are allowed */
  1584. while (next_token(TC_LBRACE | TC_NEWLINE) == TC_NEWLINE)
  1585. continue;
  1586. chain_until_rbrace();
  1587. hash_clear(ahash);
  1588. goto next_tok;
  1589. }
  1590. seq = &mainseq;
  1591. if (tclass & TS_OPSEQ) {
  1592. node *cn;
  1593. debug_printf_parse("%s: TS_OPSEQ\n", __func__);
  1594. rollback_token();
  1595. cn = chain_node(OC_TEST);
  1596. cn->l.n = parse_expr(TC_SEMICOL | TC_NEWLINE | TC_EOF | TC_LBRACE);
  1597. if (t_tclass == TC_LBRACE) {
  1598. debug_printf_parse("%s: TC_LBRACE\n", __func__);
  1599. chain_until_rbrace();
  1600. } else {
  1601. /* no action, assume default "{ print }" */
  1602. debug_printf_parse("%s: !TC_LBRACE\n", __func__);
  1603. chain_node(OC_PRINT);
  1604. }
  1605. cn->r.n = mainseq.last;
  1606. goto next_tok;
  1607. }
  1608. /* tclass == TC_LBRACE */
  1609. debug_printf_parse("%s: TC_LBRACE(?)\n", __func__);
  1610. chain_until_rbrace();
  1611. next_tok:
  1612. /* Same as next_token() at the top of the loop, + TC_SEMICOL */
  1613. tclass = next_token(TS_OPSEQ | TC_LBRACE | TC_BEGIN | TC_END | TC_FUNCDECL
  1614. | TC_EOF | TC_NEWLINE | TC_SEMICOL);
  1615. /* gawk allows many newlines, but does not allow more than one semicolon:
  1616. * BEGIN {...}<newline>;<newline>;
  1617. * would complain "each rule must have a pattern or an action part".
  1618. * Same message for
  1619. * ; BEGIN {...}
  1620. */
  1621. if (tclass != TC_SEMICOL)
  1622. goto got_tok; /* use this token */
  1623. /* else: loop back - ate the semicolon, get and use _next_ token */
  1624. } /* for (;;) */
  1625. }
  1626. /* -------- program execution part -------- */
  1627. /* temporary variables allocator */
  1628. static var *nvalloc(int sz)
  1629. {
  1630. return xzalloc(sz * sizeof(var));
  1631. }
  1632. static void nvfree(var *v, int sz)
  1633. {
  1634. var *p = v;
  1635. while (--sz >= 0) {
  1636. if ((p->type & (VF_ARRAY | VF_CHILD)) == VF_ARRAY) {
  1637. clear_array(iamarray(p));
  1638. free(p->x.array->items);
  1639. free(p->x.array);
  1640. }
  1641. if (p->type & VF_WALK) {
  1642. walker_list *n;
  1643. walker_list *w = p->x.walker;
  1644. debug_printf_walker("nvfree: freeing walker @%p\n", &p->x.walker);
  1645. p->x.walker = NULL;
  1646. while (w) {
  1647. n = w->prev;
  1648. debug_printf_walker(" free(%p)\n", w);
  1649. free(w);
  1650. w = n;
  1651. }
  1652. }
  1653. clrvar(p);
  1654. p++;
  1655. }
  1656. free(v);
  1657. }
  1658. static node *mk_splitter(const char *s, tsplitter *spl)
  1659. {
  1660. regex_t *re, *ire;
  1661. node *n;
  1662. re = &spl->re[0];
  1663. ire = &spl->re[1];
  1664. n = &spl->n;
  1665. if (n->info == TI_REGEXP) {
  1666. regfree(re);
  1667. regfree(ire); // TODO: nuke ire, use re+1?
  1668. }
  1669. if (s[0] && s[1]) { /* strlen(s) > 1 */
  1670. mk_re_node(s, n, re);
  1671. } else {
  1672. n->info = (uint32_t) s[0];
  1673. }
  1674. return n;
  1675. }
  1676. static var *evaluate(node *, var *);
  1677. /* Use node as a regular expression. Supplied with node ptr and regex_t
  1678. * storage space. Return ptr to regex (if result points to preg, it should
  1679. * be later regfree'd manually).
  1680. */
  1681. static regex_t *as_regex(node *op, regex_t *preg)
  1682. {
  1683. int cflags;
  1684. const char *s;
  1685. if (op->info == TI_REGEXP) {
  1686. return icase ? op->r.ire : op->l.re;
  1687. }
  1688. //tmpvar = nvalloc(1);
  1689. #define TMPVAR (&G.as_regex__tmpvar)
  1690. // We use a single "static" tmpvar (instead of on-stack or malloced one)
  1691. // to decrease memory consumption in deeply-recursive awk programs.
  1692. // The rule to work safely is to never call evaluate() while our static
  1693. // TMPVAR's value is still needed.
  1694. s = getvar_s(evaluate(op, TMPVAR));
  1695. cflags = icase ? REG_EXTENDED | REG_ICASE : REG_EXTENDED;
  1696. /* Testcase where REG_EXTENDED fails (unpaired '{'):
  1697. * echo Hi | awk 'gsub("@(samp|code|file)\{","");'
  1698. * gawk 3.1.5 eats this. We revert to ~REG_EXTENDED
  1699. * (maybe gsub is not supposed to use REG_EXTENDED?).
  1700. */
  1701. if (regcomp(preg, s, cflags)) {
  1702. cflags &= ~REG_EXTENDED;
  1703. xregcomp(preg, s, cflags);
  1704. }
  1705. //nvfree(tmpvar, 1);
  1706. #undef TMPVAR
  1707. return preg;
  1708. }
  1709. /* gradually increasing buffer.
  1710. * note that we reallocate even if n == old_size,
  1711. * and thus there is at least one extra allocated byte.
  1712. */
  1713. static char* qrealloc(char *b, int n, int *size)
  1714. {
  1715. if (!b || n >= *size) {
  1716. *size = n + (n>>1) + 80;
  1717. b = xrealloc(b, *size);
  1718. }
  1719. return b;
  1720. }
  1721. /* resize field storage space */
  1722. static void fsrealloc(int size)
  1723. {
  1724. int i, newsize;
  1725. if (size >= maxfields) {
  1726. /* Sanity cap, easier than catering for overflows */
  1727. if (size > 0xffffff)
  1728. bb_die_memory_exhausted();
  1729. i = maxfields;
  1730. maxfields = size + 16;
  1731. newsize = maxfields * sizeof(Fields[0]);
  1732. debug_printf_eval("fsrealloc: xrealloc(%p, %u)\n", Fields, newsize);
  1733. Fields = xrealloc(Fields, newsize);
  1734. debug_printf_eval("fsrealloc: Fields=%p..%p\n", Fields, (char*)Fields + newsize - 1);
  1735. /* ^^^ did Fields[] move? debug aid for L.v getting "upstaged" by R.v in evaluate() */
  1736. for (; i < maxfields; i++) {
  1737. Fields[i].type = VF_SPECIAL;
  1738. Fields[i].string = NULL;
  1739. }
  1740. }
  1741. /* if size < nfields, clear extra field variables */
  1742. for (i = size; i < nfields; i++) {
  1743. clrvar(Fields + i);
  1744. }
  1745. nfields = size;
  1746. }
  1747. static int regexec1_nonempty(const regex_t *preg, const char *s, regmatch_t pmatch[])
  1748. {
  1749. int r = regexec(preg, s, 1, pmatch, 0);
  1750. if (r == 0 && pmatch[0].rm_eo == 0) {
  1751. /* For example, happens when FS can match
  1752. * an empty string (awk -F ' *'). Logically,
  1753. * this should split into one-char fields.
  1754. * However, gawk 5.0.1 searches for first
  1755. * _non-empty_ separator string match:
  1756. */
  1757. size_t ofs = 0;
  1758. do {
  1759. ofs++;
  1760. if (!s[ofs])
  1761. return REG_NOMATCH;
  1762. regexec(preg, s + ofs, 1, pmatch, 0);
  1763. } while (pmatch[0].rm_eo == 0);
  1764. pmatch[0].rm_so += ofs;
  1765. pmatch[0].rm_eo += ofs;
  1766. }
  1767. return r;
  1768. }
  1769. static int awk_split(const char *s, node *spl, char **slist)
  1770. {
  1771. int n;
  1772. char c[4];
  1773. char *s1;
  1774. /* in worst case, each char would be a separate field */
  1775. *slist = s1 = xzalloc(strlen(s) * 2 + 3);
  1776. strcpy(s1, s);
  1777. c[0] = c[1] = (char)spl->info;
  1778. c[2] = c[3] = '\0';
  1779. if (*getvar_s(intvar[RS]) == '\0')
  1780. c[2] = '\n';
  1781. n = 0;
  1782. if (spl->info == TI_REGEXP) { /* regex split */
  1783. if (!*s)
  1784. return n; /* "": zero fields */
  1785. n++; /* at least one field will be there */
  1786. do {
  1787. int l;
  1788. regmatch_t pmatch[1];
  1789. l = strcspn(s, c+2); /* len till next NUL or \n */
  1790. if (regexec1_nonempty(icase ? spl->r.ire : spl->l.re, s, pmatch) == 0
  1791. && pmatch[0].rm_so <= l
  1792. ) {
  1793. /* if (pmatch[0].rm_eo == 0) ... - impossible */
  1794. l = pmatch[0].rm_so;
  1795. n++; /* we saw yet another delimiter */
  1796. } else {
  1797. pmatch[0].rm_eo = l;
  1798. if (s[l])
  1799. pmatch[0].rm_eo++;
  1800. }
  1801. s1 = mempcpy(s1, s, l);
  1802. *s1++ = '\0';
  1803. s += pmatch[0].rm_eo;
  1804. } while (*s);
  1805. /* echo a-- | awk -F-- '{ print NF, length($NF), $NF }'
  1806. * should print "2 0 ":
  1807. */
  1808. *s1 = '\0';
  1809. return n;
  1810. }
  1811. if (c[0] == '\0') { /* null split */
  1812. while (*s) {
  1813. *s1++ = *s++;
  1814. *s1++ = '\0';
  1815. n++;
  1816. }
  1817. return n;
  1818. }
  1819. if (c[0] != ' ') { /* single-character split */
  1820. if (icase) {
  1821. c[0] = toupper(c[0]);
  1822. c[1] = tolower(c[1]);
  1823. }
  1824. if (*s1)
  1825. n++;
  1826. while ((s1 = strpbrk(s1, c)) != NULL) {
  1827. *s1++ = '\0';
  1828. n++;
  1829. }
  1830. return n;
  1831. }
  1832. /* space split */
  1833. while (*s) {
  1834. s = skip_whitespace(s);
  1835. if (!*s)
  1836. break;
  1837. n++;
  1838. while (*s && !isspace(*s))
  1839. *s1++ = *s++;
  1840. *s1++ = '\0';
  1841. }
  1842. return n;
  1843. }
  1844. static void split_f0(void)
  1845. {
  1846. /* static char *fstrings; */
  1847. #define fstrings (G.split_f0__fstrings)
  1848. int i, n;
  1849. char *s;
  1850. if (is_f0_split)
  1851. return;
  1852. is_f0_split = TRUE;
  1853. free(fstrings);
  1854. fsrealloc(0);
  1855. n = awk_split(getvar_s(intvar[F0]), &fsplitter.n, &fstrings);
  1856. fsrealloc(n);
  1857. s = fstrings;
  1858. for (i = 0; i < n; i++) {
  1859. Fields[i].string = nextword(&s);
  1860. Fields[i].type |= (VF_FSTR | VF_USER | VF_DIRTY);
  1861. }
  1862. /* set NF manually to avoid side effects */
  1863. clrvar(intvar[NF]);
  1864. intvar[NF]->type = VF_NUMBER | VF_SPECIAL;
  1865. intvar[NF]->number = nfields;
  1866. #undef fstrings
  1867. }
  1868. /* perform additional actions when some internal variables changed */
  1869. static void handle_special(var *v)
  1870. {
  1871. int n;
  1872. char *b;
  1873. const char *sep, *s;
  1874. int sl, l, len, i, bsize;
  1875. if (!(v->type & VF_SPECIAL))
  1876. return;
  1877. if (v == intvar[NF]) {
  1878. n = (int)getvar_i(v);
  1879. if (n < 0)
  1880. syntax_error("NF set to negative value");
  1881. fsrealloc(n);
  1882. /* recalculate $0 */
  1883. sep = getvar_s(intvar[OFS]);
  1884. sl = strlen(sep);
  1885. b = NULL;
  1886. len = 0;
  1887. for (i = 0; i < n; i++) {
  1888. s = getvar_s(&Fields[i]);
  1889. l = strlen(s);
  1890. if (b) {
  1891. memcpy(b+len, sep, sl);
  1892. len += sl;
  1893. }
  1894. b = qrealloc(b, len+l+sl, &bsize);
  1895. memcpy(b+len, s, l);
  1896. len += l;
  1897. }
  1898. if (b)
  1899. b[len] = '\0';
  1900. setvar_p(intvar[F0], b);
  1901. is_f0_split = TRUE;
  1902. } else if (v == intvar[F0]) {
  1903. is_f0_split = FALSE;
  1904. } else if (v == intvar[FS]) {
  1905. /*
  1906. * The POSIX-2008 standard says that changing FS should have no effect on the
  1907. * current input line, but only on the next one. The language is:
  1908. *
  1909. * > Before the first reference to a field in the record is evaluated, the record
  1910. * > shall be split into fields, according to the rules in Regular Expressions,
  1911. * > using the value of FS that was current at the time the record was read.
  1912. *
  1913. * So, split up current line before assignment to FS:
  1914. */
  1915. split_f0();
  1916. mk_splitter(getvar_s(v), &fsplitter);
  1917. } else if (v == intvar[RS]) {
  1918. mk_splitter(getvar_s(v), &rsplitter);
  1919. } else if (v == intvar[IGNORECASE]) {
  1920. icase = istrue(v);
  1921. } else { /* $n */
  1922. n = getvar_i(intvar[NF]);
  1923. setvar_i(intvar[NF], n > v-Fields ? n : v-Fields+1);
  1924. /* right here v is invalid. Just to note... */
  1925. }
  1926. }
  1927. /* step through func/builtin/etc arguments */
  1928. static node *nextarg(node **pn)
  1929. {
  1930. node *n;
  1931. n = *pn;
  1932. if (n && n->info == TI_COMMA) {
  1933. *pn = n->r.n;
  1934. n = n->l.n;
  1935. } else {
  1936. *pn = NULL;
  1937. }
  1938. return n;
  1939. }
  1940. static void hashwalk_init(var *v, xhash *array)
  1941. {
  1942. hash_item *hi;
  1943. unsigned i;
  1944. walker_list *w;
  1945. walker_list *prev_walker;
  1946. if (v->type & VF_WALK) {
  1947. prev_walker = v->x.walker;
  1948. } else {
  1949. v->type |= VF_WALK;
  1950. prev_walker = NULL;
  1951. }
  1952. debug_printf_walker("hashwalk_init: prev_walker:%p\n", prev_walker);
  1953. w = v->x.walker = xzalloc(sizeof(*w) + array->glen + 1); /* why + 1? */
  1954. debug_printf_walker(" walker@%p=%p\n", &v->x.walker, w);
  1955. w->cur = w->end = w->wbuf;
  1956. w->prev = prev_walker;
  1957. for (i = 0; i < array->csize; i++) {
  1958. hi = array->items[i];
  1959. while (hi) {
  1960. w->end = stpcpy(w->end, hi->name) + 1;
  1961. hi = hi->next;
  1962. }
  1963. }
  1964. }
  1965. static int hashwalk_next(var *v)
  1966. {
  1967. walker_list *w = v->x.walker;
  1968. if (w->cur >= w->end) {
  1969. walker_list *prev_walker = w->prev;
  1970. debug_printf_walker("end of iteration, free(walker@%p:%p), prev_walker:%p\n", &v->x.walker, w, prev_walker);
  1971. free(w);
  1972. v->x.walker = prev_walker;
  1973. return FALSE;
  1974. }
  1975. setvar_s(v, nextword(&w->cur));
  1976. return TRUE;
  1977. }
  1978. /* evaluate node, return 1 when result is true, 0 otherwise */
  1979. static int ptest(node *pattern)
  1980. {
  1981. // We use a single "static" tmpvar (instead of on-stack or malloced one)
  1982. // to decrease memory consumption in deeply-recursive awk programs.
  1983. // The rule to work safely is to never call evaluate() while our static
  1984. // TMPVAR's value is still needed.
  1985. return istrue(evaluate(pattern, &G.ptest__tmpvar));
  1986. }
  1987. /* read next record from stream rsm into a variable v */
  1988. static int awk_getline(rstream *rsm, var *v)
  1989. {
  1990. char *b;
  1991. regmatch_t pmatch[1];
  1992. int size, a, p, pp = 0;
  1993. int fd, so, eo, r, rp;
  1994. char c, *m, *s;
  1995. debug_printf_eval("entered %s()\n", __func__);
  1996. /* we're using our own buffer since we need access to accumulating
  1997. * characters
  1998. */
  1999. fd = fileno(rsm->F);
  2000. m = rsm->buffer;
  2001. a = rsm->adv;
  2002. p = rsm->pos;
  2003. size = rsm->size;
  2004. c = (char) rsplitter.n.info;
  2005. rp = 0;
  2006. if (!m)
  2007. m = qrealloc(m, 256, &size);
  2008. do {
  2009. b = m + a;
  2010. so = eo = p;
  2011. r = 1;
  2012. if (p > 0) {
  2013. if (rsplitter.n.info == TI_REGEXP) {
  2014. if (regexec(icase ? rsplitter.n.r.ire : rsplitter.n.l.re,
  2015. b, 1, pmatch, 0) == 0) {
  2016. so = pmatch[0].rm_so;
  2017. eo = pmatch[0].rm_eo;
  2018. if (b[eo] != '\0')
  2019. break;
  2020. }
  2021. } else if (c != '\0') {
  2022. s = strchr(b+pp, c);
  2023. if (!s)
  2024. s = memchr(b+pp, '\0', p - pp);
  2025. if (s) {
  2026. so = eo = s-b;
  2027. eo++;
  2028. break;
  2029. }
  2030. } else {
  2031. while (b[rp] == '\n')
  2032. rp++;
  2033. s = strstr(b+rp, "\n\n");
  2034. if (s) {
  2035. so = eo = s-b;
  2036. while (b[eo] == '\n')
  2037. eo++;
  2038. if (b[eo] != '\0')
  2039. break;
  2040. }
  2041. }
  2042. }
  2043. if (a > 0) {
  2044. memmove(m, m+a, p+1);
  2045. b = m;
  2046. a = 0;
  2047. }
  2048. m = qrealloc(m, a+p+128, &size);
  2049. b = m + a;
  2050. pp = p;
  2051. p += safe_read(fd, b+p, size-p-1);
  2052. if (p < pp) {
  2053. p = 0;
  2054. r = 0;
  2055. setvar_i(intvar[ERRNO], errno);
  2056. }
  2057. b[p] = '\0';
  2058. } while (p > pp);
  2059. if (p == 0) {
  2060. r--;
  2061. } else {
  2062. c = b[so]; b[so] = '\0';
  2063. setvar_s(v, b+rp);
  2064. v->type |= VF_USER;
  2065. b[so] = c;
  2066. c = b[eo]; b[eo] = '\0';
  2067. setvar_s(intvar[RT], b+so);
  2068. b[eo] = c;
  2069. }
  2070. rsm->buffer = m;
  2071. rsm->adv = a + eo;
  2072. rsm->pos = p - eo;
  2073. rsm->size = size;
  2074. debug_printf_eval("returning from %s(): %d\n", __func__, r);
  2075. return r;
  2076. }
  2077. /* formatted output into an allocated buffer, return ptr to buffer */
  2078. #if !ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  2079. # define awk_printf(a, b) awk_printf(a)
  2080. #endif
  2081. static char *awk_printf(node *n, size_t *len)
  2082. {
  2083. char *b;
  2084. char *fmt, *f;
  2085. size_t i;
  2086. //tmpvar = nvalloc(1);
  2087. #define TMPVAR (&G.awk_printf__tmpvar)
  2088. // We use a single "static" tmpvar (instead of on-stack or malloced one)
  2089. // to decrease memory consumption in deeply-recursive awk programs.
  2090. // The rule to work safely is to never call evaluate() while our static
  2091. // TMPVAR's value is still needed.
  2092. fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), TMPVAR)));
  2093. // ^^^^^^^^^ here we immediately strdup() the value, so the later call
  2094. // to evaluate() potentially recursing into another awk_printf() can't
  2095. // mangle the value.
  2096. b = NULL;
  2097. i = 0;
  2098. while (1) { /* "print one format spec" loop */
  2099. char *s;
  2100. char c;
  2101. char sv;
  2102. var *arg;
  2103. size_t slen;
  2104. /* Find end of the next format spec, or end of line */
  2105. s = f;
  2106. while (1) {
  2107. c = *f;
  2108. if (!c) /* no percent chars found at all */
  2109. goto nul;
  2110. f++;
  2111. if (c == '%')
  2112. break;
  2113. }
  2114. /* we are past % in "....%..." */
  2115. c = *f;
  2116. if (!c) /* "....%" */
  2117. goto nul;
  2118. if (c == '%') { /* "....%%...." */
  2119. slen = f - s;
  2120. s = xstrndup(s, slen);
  2121. f++;
  2122. goto append; /* print "....%" part verbatim */
  2123. }
  2124. while (1) {
  2125. if (isalpha(c))
  2126. break;
  2127. if (c == '*')
  2128. syntax_error("%*x formats are not supported");
  2129. c = *++f;
  2130. if (!c) { /* "....%...." and no letter found after % */
  2131. /* Example: awk 'BEGIN { printf "^^^%^^^\n"; }' */
  2132. nul:
  2133. slen = f - s;
  2134. goto tail; /* print remaining string, exit loop */
  2135. }
  2136. }
  2137. /* we are at A in "....%...A..." */
  2138. arg = evaluate(nextarg(&n), TMPVAR);
  2139. /* Result can be arbitrarily long. Example:
  2140. * printf "%99999s", "BOOM"
  2141. */
  2142. sv = *++f;
  2143. *f = '\0';
  2144. if (c == 'c') {
  2145. char cc = is_numeric(arg) ? getvar_i(arg) : *getvar_s(arg);
  2146. char *r = xasprintf(s, cc ? cc : '^' /* else strlen will be wrong */);
  2147. slen = strlen(r);
  2148. if (cc == '\0') /* if cc is NUL, re-format the string with it */
  2149. sprintf(r, s, cc);
  2150. s = r;
  2151. } else {
  2152. if (c == 's') {
  2153. s = xasprintf(s, getvar_s(arg));
  2154. } else {
  2155. double d = getvar_i(arg);
  2156. if (strchr("diouxX", c)) {
  2157. //TODO: make it wider here (%x -> %llx etc)?
  2158. s = xasprintf(s, (int)d);
  2159. } else if (strchr("eEfFgGaA", c)) {
  2160. s = xasprintf(s, d);
  2161. } else {
  2162. //TODO: GNU Awk 5.0.1: printf "%W" prints "%W", does not error out
  2163. syntax_error(EMSG_INV_FMT);
  2164. }
  2165. }
  2166. slen = strlen(s);
  2167. }
  2168. *f = sv;
  2169. append:
  2170. if (i == 0) {
  2171. b = s;
  2172. i = slen;
  2173. continue;
  2174. }
  2175. tail:
  2176. b = xrealloc(b, i + slen + 1);
  2177. strcpy(b + i, s);
  2178. i += slen;
  2179. if (!c) /* s is NOT allocated and this is the last part of string? */
  2180. break;
  2181. free(s);
  2182. }
  2183. free(fmt);
  2184. //nvfree(tmpvar, 1);
  2185. #undef TMPVAR
  2186. #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  2187. if (len)
  2188. *len = i;
  2189. #endif
  2190. return b;
  2191. }
  2192. /* Common substitution routine.
  2193. * Replace (nm)'th substring of (src) that matches (rn) with (repl),
  2194. * store result into (dest), return number of substitutions.
  2195. * If nm = 0, replace all matches.
  2196. * If src or dst is NULL, use $0.
  2197. * If subexp != 0, enable subexpression matching (\1-\9).
  2198. */
  2199. static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest, int subexp)
  2200. {
  2201. char *resbuf;
  2202. const char *sp;
  2203. int match_no, residx, replen, resbufsize;
  2204. int regexec_flags;
  2205. regmatch_t pmatch[10];
  2206. regex_t sreg, *regex;
  2207. resbuf = NULL;
  2208. residx = 0;
  2209. match_no = 0;
  2210. regexec_flags = 0;
  2211. regex = as_regex(rn, &sreg);
  2212. sp = getvar_s(src ? src : intvar[F0]);
  2213. replen = strlen(repl);
  2214. while (regexec(regex, sp, 10, pmatch, regexec_flags) == 0) {
  2215. int so = pmatch[0].rm_so;
  2216. int eo = pmatch[0].rm_eo;
  2217. //bb_error_msg("match %u: [%u,%u] '%s'%p", match_no+1, so, eo, sp,sp);
  2218. resbuf = qrealloc(resbuf, residx + eo + replen, &resbufsize);
  2219. memcpy(resbuf + residx, sp, eo);
  2220. residx += eo;
  2221. if (++match_no >= nm) {
  2222. const char *s;
  2223. int nbs;
  2224. /* replace */
  2225. residx -= (eo - so);
  2226. nbs = 0;
  2227. for (s = repl; *s; s++) {
  2228. char c = resbuf[residx++] = *s;
  2229. if (c == '\\') {
  2230. nbs++;
  2231. continue;
  2232. }
  2233. if (c == '&' || (subexp && c >= '0' && c <= '9')) {
  2234. int j;
  2235. residx -= ((nbs + 3) >> 1);
  2236. j = 0;
  2237. if (c != '&') {
  2238. j = c - '0';
  2239. nbs++;
  2240. }
  2241. if (nbs % 2) {
  2242. resbuf[residx++] = c;
  2243. } else {
  2244. int n = pmatch[j].rm_eo - pmatch[j].rm_so;
  2245. resbuf = qrealloc(resbuf, residx + replen + n, &resbufsize);
  2246. memcpy(resbuf + residx, sp + pmatch[j].rm_so, n);
  2247. residx += n;
  2248. }
  2249. }
  2250. nbs = 0;
  2251. }
  2252. }
  2253. regexec_flags = REG_NOTBOL;
  2254. sp += eo;
  2255. if (match_no == nm)
  2256. break;
  2257. if (eo == so) {
  2258. /* Empty match (e.g. "b*" will match anywhere).
  2259. * Advance by one char. */
  2260. //BUG (bug 1333):
  2261. //gsub(/\<b*/,"") on "abc" will reach this point, advance to "bc"
  2262. //... and will erroneously match "b" even though it is NOT at the word start.
  2263. //we need REG_NOTBOW but it does not exist...
  2264. //TODO: if EXTRA_COMPAT=y, use GNU matching and re_search,
  2265. //it should be able to do it correctly.
  2266. /* Subtle: this is safe only because
  2267. * qrealloc allocated at least one extra byte */
  2268. resbuf[residx] = *sp;
  2269. if (*sp == '\0')
  2270. goto ret;
  2271. sp++;
  2272. residx++;
  2273. }
  2274. }
  2275. resbuf = qrealloc(resbuf, residx + strlen(sp), &resbufsize);
  2276. strcpy(resbuf + residx, sp);
  2277. ret:
  2278. //bb_error_msg("end sp:'%s'%p", sp,sp);
  2279. setvar_p(dest ? dest : intvar[F0], resbuf);
  2280. if (regex == &sreg)
  2281. regfree(regex);
  2282. return match_no;
  2283. }
  2284. static NOINLINE int do_mktime(const char *ds)
  2285. {
  2286. struct tm then;
  2287. int count;
  2288. /*memset(&then, 0, sizeof(then)); - not needed */
  2289. then.tm_isdst = -1; /* default is unknown */
  2290. /* manpage of mktime says these fields are ints,
  2291. * so we can sscanf stuff directly into them */
  2292. count = sscanf(ds, "%u %u %u %u %u %u %d",
  2293. &then.tm_year, &then.tm_mon, &then.tm_mday,
  2294. &then.tm_hour, &then.tm_min, &then.tm_sec,
  2295. &then.tm_isdst);
  2296. if (count < 6
  2297. || (unsigned)then.tm_mon < 1
  2298. || (unsigned)then.tm_year < 1900
  2299. ) {
  2300. return -1;
  2301. }
  2302. then.tm_mon -= 1;
  2303. then.tm_year -= 1900;
  2304. return mktime(&then);
  2305. }
  2306. /* Reduce stack usage in exec_builtin() by keeping match() code separate */
  2307. static NOINLINE var *do_match(node *an1, const char *as0)
  2308. {
  2309. regmatch_t pmatch[1];
  2310. regex_t sreg, *re;
  2311. int n, start, len;
  2312. re = as_regex(an1, &sreg);
  2313. n = regexec(re, as0, 1, pmatch, 0);
  2314. if (re == &sreg)
  2315. regfree(re);
  2316. start = 0;
  2317. len = -1;
  2318. if (n == 0) {
  2319. start = pmatch[0].rm_so + 1;
  2320. len = pmatch[0].rm_eo - pmatch[0].rm_so;
  2321. }
  2322. setvar_i(newvar("RLENGTH"), len);
  2323. return setvar_i(newvar("RSTART"), start);
  2324. }
  2325. /* Reduce stack usage in evaluate() by keeping builtins' code separate */
  2326. static NOINLINE var *exec_builtin(node *op, var *res)
  2327. {
  2328. #define tspl (G.exec_builtin__tspl)
  2329. var *tmpvars;
  2330. node *an[4];
  2331. var *av[4];
  2332. const char *as[4];
  2333. node *spl;
  2334. uint32_t isr, info;
  2335. int nargs;
  2336. time_t tt;
  2337. int i, l, ll, n;
  2338. tmpvars = nvalloc(4);
  2339. #define TMPVAR0 (tmpvars)
  2340. #define TMPVAR1 (tmpvars + 1)
  2341. #define TMPVAR2 (tmpvars + 2)
  2342. #define TMPVAR3 (tmpvars + 3)
  2343. #define TMPVAR(i) (tmpvars + (i))
  2344. isr = info = op->info;
  2345. op = op->l.n;
  2346. av[2] = av[3] = NULL;
  2347. for (i = 0; i < 4 && op; i++) {
  2348. an[i] = nextarg(&op);
  2349. if (isr & 0x09000000) {
  2350. av[i] = evaluate(an[i], TMPVAR(i));
  2351. if (isr & 0x08000000)
  2352. as[i] = getvar_s(av[i]);
  2353. }
  2354. isr >>= 1;
  2355. }
  2356. nargs = i;
  2357. if ((uint32_t)nargs < (info >> 30))
  2358. syntax_error(EMSG_TOO_FEW_ARGS);
  2359. info &= OPNMASK;
  2360. switch (info) {
  2361. case B_a2:
  2362. if (ENABLE_FEATURE_AWK_LIBM)
  2363. setvar_i(res, atan2(getvar_i(av[0]), getvar_i(av[1])));
  2364. else
  2365. syntax_error(EMSG_NO_MATH);
  2366. break;
  2367. case B_sp: {
  2368. char *s, *s1;
  2369. if (nargs > 2) {
  2370. spl = (an[2]->info == TI_REGEXP) ? an[2]
  2371. : mk_splitter(getvar_s(evaluate(an[2], TMPVAR2)), &tspl);
  2372. } else {
  2373. spl = &fsplitter.n;
  2374. }
  2375. n = awk_split(as[0], spl, &s);
  2376. s1 = s;
  2377. clear_array(iamarray(av[1]));
  2378. for (i = 1; i <= n; i++)
  2379. setari_u(av[1], i, nextword(&s));
  2380. free(s1);
  2381. setvar_i(res, n);
  2382. break;
  2383. }
  2384. case B_ss: {
  2385. char *s;
  2386. l = strlen(as[0]);
  2387. i = getvar_i(av[1]) - 1;
  2388. if (i > l)
  2389. i = l;
  2390. if (i < 0)
  2391. i = 0;
  2392. n = (nargs > 2) ? getvar_i(av[2]) : l-i;
  2393. if (n < 0)
  2394. n = 0;
  2395. s = xstrndup(as[0]+i, n);
  2396. setvar_p(res, s);
  2397. break;
  2398. }
  2399. /* Bitwise ops must assume that operands are unsigned. GNU Awk 3.1.5:
  2400. * awk '{ print or(-1,1) }' gives "4.29497e+09", not "-2.xxxe+09" */
  2401. case B_an:
  2402. setvar_i(res, getvar_i_int(av[0]) & getvar_i_int(av[1]));
  2403. break;
  2404. case B_co:
  2405. setvar_i(res, ~getvar_i_int(av[0]));
  2406. break;
  2407. case B_ls:
  2408. setvar_i(res, getvar_i_int(av[0]) << getvar_i_int(av[1]));
  2409. break;
  2410. case B_or:
  2411. setvar_i(res, getvar_i_int(av[0]) | getvar_i_int(av[1]));
  2412. break;
  2413. case B_rs:
  2414. setvar_i(res, getvar_i_int(av[0]) >> getvar_i_int(av[1]));
  2415. break;
  2416. case B_xo:
  2417. setvar_i(res, getvar_i_int(av[0]) ^ getvar_i_int(av[1]));
  2418. break;
  2419. case B_lo:
  2420. case B_up: {
  2421. char *s, *s1;
  2422. s1 = s = xstrdup(as[0]);
  2423. while (*s1) {
  2424. //*s1 = (info == B_up) ? toupper(*s1) : tolower(*s1);
  2425. if ((unsigned char)((*s1 | 0x20) - 'a') <= ('z' - 'a'))
  2426. *s1 = (info == B_up) ? (*s1 & 0xdf) : (*s1 | 0x20);
  2427. s1++;
  2428. }
  2429. setvar_p(res, s);
  2430. break;
  2431. }
  2432. case B_ix:
  2433. n = 0;
  2434. ll = strlen(as[1]);
  2435. l = strlen(as[0]) - ll;
  2436. if (ll > 0 && l >= 0) {
  2437. if (!icase) {
  2438. char *s = strstr(as[0], as[1]);
  2439. if (s)
  2440. n = (s - as[0]) + 1;
  2441. } else {
  2442. /* this piece of code is terribly slow and
  2443. * really should be rewritten
  2444. */
  2445. for (i = 0; i <= l; i++) {
  2446. if (strncasecmp(as[0]+i, as[1], ll) == 0) {
  2447. n = i+1;
  2448. break;
  2449. }
  2450. }
  2451. }
  2452. }
  2453. setvar_i(res, n);
  2454. break;
  2455. case B_ti:
  2456. if (nargs > 1)
  2457. tt = getvar_i(av[1]);
  2458. else
  2459. time(&tt);
  2460. //s = (nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y";
  2461. i = strftime(g_buf, MAXVARFMT,
  2462. ((nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y"),
  2463. localtime(&tt));
  2464. g_buf[i] = '\0';
  2465. setvar_s(res, g_buf);
  2466. break;
  2467. case B_mt:
  2468. setvar_i(res, do_mktime(as[0]));
  2469. break;
  2470. case B_ma:
  2471. res = do_match(an[1], as[0]);
  2472. break;
  2473. case B_ge:
  2474. awk_sub(an[0], as[1], getvar_i(av[2]), av[3], res, TRUE);
  2475. break;
  2476. case B_gs:
  2477. setvar_i(res, awk_sub(an[0], as[1], 0, av[2], av[2], FALSE));
  2478. break;
  2479. case B_su:
  2480. setvar_i(res, awk_sub(an[0], as[1], 1, av[2], av[2], FALSE));
  2481. break;
  2482. }
  2483. nvfree(tmpvars, 4);
  2484. #undef TMPVAR0
  2485. #undef TMPVAR1
  2486. #undef TMPVAR2
  2487. #undef TMPVAR3
  2488. #undef TMPVAR
  2489. return res;
  2490. #undef tspl
  2491. }
  2492. /* if expr looks like "var=value", perform assignment and return 1,
  2493. * otherwise return 0 */
  2494. static int is_assignment(const char *expr)
  2495. {
  2496. char *exprc, *val;
  2497. val = (char*)endofname(expr);
  2498. if (val == (char*)expr || *val != '=') {
  2499. return FALSE;
  2500. }
  2501. exprc = xstrdup(expr);
  2502. val = exprc + (val - expr);
  2503. *val++ = '\0';
  2504. unescape_string_in_place(val);
  2505. setvar_u(newvar(exprc), val);
  2506. free(exprc);
  2507. return TRUE;
  2508. }
  2509. /* switch to next input file */
  2510. static rstream *next_input_file(void)
  2511. {
  2512. #define rsm (G.next_input_file__rsm)
  2513. #define files_happen (G.next_input_file__files_happen)
  2514. const char *fname, *ind;
  2515. if (rsm.F)
  2516. fclose(rsm.F);
  2517. rsm.F = NULL;
  2518. rsm.pos = rsm.adv = 0;
  2519. for (;;) {
  2520. if (getvar_i(intvar[ARGIND])+1 >= getvar_i(intvar[ARGC])) {
  2521. if (files_happen)
  2522. return NULL;
  2523. fname = "-";
  2524. rsm.F = stdin;
  2525. break;
  2526. }
  2527. ind = getvar_s(incvar(intvar[ARGIND]));
  2528. fname = getvar_s(findvar(iamarray(intvar[ARGV]), ind));
  2529. if (fname && *fname && !is_assignment(fname)) {
  2530. rsm.F = xfopen_stdin(fname);
  2531. break;
  2532. }
  2533. }
  2534. files_happen = TRUE;
  2535. setvar_s(intvar[FILENAME], fname);
  2536. return &rsm;
  2537. #undef rsm
  2538. #undef files_happen
  2539. }
  2540. /*
  2541. * Evaluate node - the heart of the program. Supplied with subtree
  2542. * and "res" variable to assign the result to if we evaluate an expression.
  2543. * If node refers to e.g. a variable or a field, no assignment happens.
  2544. * Return ptr to the result (which may or may not be the "res" variable!)
  2545. */
  2546. #define XC(n) ((n) >> 8)
  2547. static var *evaluate(node *op, var *res)
  2548. {
  2549. /* This procedure is recursive so we should count every byte */
  2550. #define fnargs (G.evaluate__fnargs)
  2551. /* seed is initialized to 1 */
  2552. #define seed (G.evaluate__seed)
  2553. #define sreg (G.evaluate__sreg)
  2554. var *tmpvars;
  2555. if (!op)
  2556. return setvar_s(res, NULL);
  2557. debug_printf_eval("entered %s()\n", __func__);
  2558. tmpvars = nvalloc(2);
  2559. #define TMPVAR0 (tmpvars)
  2560. #define TMPVAR1 (tmpvars + 1)
  2561. while (op) {
  2562. struct {
  2563. var *v;
  2564. const char *s;
  2565. } L = L; /* for compiler */
  2566. struct {
  2567. var *v;
  2568. const char *s;
  2569. } R = R;
  2570. double L_d = L_d;
  2571. uint32_t opinfo;
  2572. int opn;
  2573. node *op1;
  2574. opinfo = op->info;
  2575. opn = (opinfo & OPNMASK);
  2576. g_lineno = op->lineno;
  2577. op1 = op->l.n;
  2578. debug_printf_eval("opinfo:%08x opn:%08x\n", opinfo, opn);
  2579. /* execute inevitable things */
  2580. if (opinfo & OF_RES1) {
  2581. if ((opinfo & OF_REQUIRED) && !op1)
  2582. syntax_error(EMSG_TOO_FEW_ARGS);
  2583. L.v = evaluate(op1, TMPVAR0);
  2584. if (opinfo & OF_STR1) {
  2585. L.s = getvar_s(L.v);
  2586. debug_printf_eval("L.s:'%s'\n", L.s);
  2587. }
  2588. if (opinfo & OF_NUM1) {
  2589. L_d = getvar_i(L.v);
  2590. debug_printf_eval("L_d:%f\n", L_d);
  2591. }
  2592. }
  2593. /* NB: Must get string/numeric values of L (done above)
  2594. * _before_ evaluate()'ing R.v: if both L and R are $NNNs,
  2595. * and right one is large, then L.v points to Fields[NNN1],
  2596. * second evaluate() reallocates and moves (!) Fields[],
  2597. * R.v points to Fields[NNN2] but L.v now points to freed mem!
  2598. * (Seen trying to evaluate "$444 $44444")
  2599. */
  2600. if (opinfo & OF_RES2) {
  2601. R.v = evaluate(op->r.n, TMPVAR1);
  2602. //TODO: L.v may be invalid now, set L.v to NULL to catch bugs?
  2603. //L.v = NULL;
  2604. if (opinfo & OF_STR2) {
  2605. R.s = getvar_s(R.v);
  2606. debug_printf_eval("R.s:'%s'\n", R.s);
  2607. }
  2608. }
  2609. debug_printf_eval("switch(0x%x)\n", XC(opinfo & OPCLSMASK));
  2610. switch (XC(opinfo & OPCLSMASK)) {
  2611. /* -- iterative node type -- */
  2612. /* test pattern */
  2613. case XC( OC_TEST ):
  2614. debug_printf_eval("TEST\n");
  2615. if (op1->info == TI_COMMA) {
  2616. /* it's range pattern */
  2617. if ((opinfo & OF_CHECKED) || ptest(op1->l.n)) {
  2618. op->info |= OF_CHECKED;
  2619. if (ptest(op1->r.n))
  2620. op->info &= ~OF_CHECKED;
  2621. op = op->a.n;
  2622. } else {
  2623. op = op->r.n;
  2624. }
  2625. } else {
  2626. op = ptest(op1) ? op->a.n : op->r.n;
  2627. }
  2628. break;
  2629. /* just evaluate an expression, also used as unconditional jump */
  2630. case XC( OC_EXEC ):
  2631. debug_printf_eval("EXEC\n");
  2632. break;
  2633. /* branch, used in if-else and various loops */
  2634. case XC( OC_BR ):
  2635. debug_printf_eval("BR\n");
  2636. op = istrue(L.v) ? op->a.n : op->r.n;
  2637. break;
  2638. /* initialize for-in loop */
  2639. case XC( OC_WALKINIT ):
  2640. debug_printf_eval("WALKINIT\n");
  2641. hashwalk_init(L.v, iamarray(R.v));
  2642. break;
  2643. /* get next array item */
  2644. case XC( OC_WALKNEXT ):
  2645. debug_printf_eval("WALKNEXT\n");
  2646. op = hashwalk_next(L.v) ? op->a.n : op->r.n;
  2647. break;
  2648. case XC( OC_PRINT ):
  2649. debug_printf_eval("PRINT /\n");
  2650. case XC( OC_PRINTF ):
  2651. debug_printf_eval("PRINTF\n");
  2652. {
  2653. FILE *F = stdout;
  2654. if (op->r.n) {
  2655. rstream *rsm = newfile(R.s);
  2656. if (!rsm->F) {
  2657. if (opn == '|') {
  2658. rsm->F = popen(R.s, "w");
  2659. if (rsm->F == NULL)
  2660. bb_simple_perror_msg_and_die("popen");
  2661. rsm->is_pipe = 1;
  2662. } else {
  2663. rsm->F = xfopen(R.s, opn=='w' ? "w" : "a");
  2664. }
  2665. }
  2666. F = rsm->F;
  2667. }
  2668. /* Can't just check 'opinfo == OC_PRINT' here, parser ORs
  2669. * additional bits to opinfos of print/printf with redirects
  2670. */
  2671. if ((opinfo & OPCLSMASK) == OC_PRINT) {
  2672. if (!op1) {
  2673. fputs(getvar_s(intvar[F0]), F);
  2674. } else {
  2675. for (;;) {
  2676. var *v = evaluate(nextarg(&op1), TMPVAR0);
  2677. if (v->type & VF_NUMBER) {
  2678. fmt_num(getvar_s(intvar[OFMT]),
  2679. getvar_i(v));
  2680. fputs(g_buf, F);
  2681. } else {
  2682. fputs(getvar_s(v), F);
  2683. }
  2684. if (!op1)
  2685. break;
  2686. fputs(getvar_s(intvar[OFS]), F);
  2687. }
  2688. }
  2689. fputs(getvar_s(intvar[ORS]), F);
  2690. } else { /* PRINTF */
  2691. IF_FEATURE_AWK_GNU_EXTENSIONS(size_t len;)
  2692. char *s = awk_printf(op1, &len);
  2693. #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  2694. fwrite(s, len, 1, F);
  2695. #else
  2696. fputs(s, F);
  2697. #endif
  2698. free(s);
  2699. }
  2700. fflush(F);
  2701. break;
  2702. }
  2703. case XC( OC_DELETE ):
  2704. debug_printf_eval("DELETE\n");
  2705. {
  2706. /* "delete" is special:
  2707. * "delete array[var--]" must evaluate index expr only once.
  2708. */
  2709. uint32_t info = op1->info & OPCLSMASK;
  2710. var *v;
  2711. if (info == OC_VAR) {
  2712. v = op1->l.v;
  2713. } else if (info == OC_FNARG) {
  2714. v = &fnargs[op1->l.aidx];
  2715. } else {
  2716. syntax_error(EMSG_NOT_ARRAY);
  2717. }
  2718. if (op1->r.n) { /* array ref? */
  2719. const char *s;
  2720. s = getvar_s(evaluate(op1->r.n, TMPVAR0));
  2721. hash_remove(iamarray(v), s);
  2722. } else {
  2723. clear_array(iamarray(v));
  2724. }
  2725. break;
  2726. }
  2727. case XC( OC_NEWSOURCE ):
  2728. debug_printf_eval("NEWSOURCE\n");
  2729. g_progname = op->l.new_progname;
  2730. break;
  2731. case XC( OC_RETURN ):
  2732. debug_printf_eval("RETURN\n");
  2733. copyvar(res, L.v);
  2734. break;
  2735. case XC( OC_NEXTFILE ):
  2736. debug_printf_eval("NEXTFILE\n");
  2737. nextfile = TRUE;
  2738. case XC( OC_NEXT ):
  2739. debug_printf_eval("NEXT\n");
  2740. nextrec = TRUE;
  2741. case XC( OC_DONE ):
  2742. debug_printf_eval("DONE\n");
  2743. clrvar(res);
  2744. break;
  2745. case XC( OC_EXIT ):
  2746. debug_printf_eval("EXIT\n");
  2747. if (op1)
  2748. G.exitcode = (int)L_d;
  2749. awk_exit();
  2750. /* -- recursive node type -- */
  2751. case XC( OC_VAR ):
  2752. debug_printf_eval("VAR\n");
  2753. L.v = op->l.v;
  2754. if (L.v == intvar[NF])
  2755. split_f0();
  2756. goto v_cont;
  2757. case XC( OC_FNARG ):
  2758. debug_printf_eval("FNARG[%d]\n", op->l.aidx);
  2759. L.v = &fnargs[op->l.aidx];
  2760. v_cont:
  2761. res = op->r.n ? findvar(iamarray(L.v), R.s) : L.v;
  2762. break;
  2763. case XC( OC_IN ):
  2764. debug_printf_eval("IN\n");
  2765. setvar_i(res, hash_search(iamarray(R.v), L.s) ? 1 : 0);
  2766. break;
  2767. case XC( OC_REGEXP ):
  2768. debug_printf_eval("REGEXP\n");
  2769. op1 = op;
  2770. L.s = getvar_s(intvar[F0]);
  2771. goto re_cont;
  2772. case XC( OC_MATCH ):
  2773. debug_printf_eval("MATCH\n");
  2774. op1 = op->r.n;
  2775. re_cont:
  2776. {
  2777. regex_t *re = as_regex(op1, &sreg);
  2778. int i = regexec(re, L.s, 0, NULL, 0);
  2779. if (re == &sreg)
  2780. regfree(re);
  2781. setvar_i(res, (i == 0) ^ (opn == '!'));
  2782. }
  2783. break;
  2784. case XC( OC_MOVE ):
  2785. debug_printf_eval("MOVE\n");
  2786. /* make sure that we never return a temp var */
  2787. if (L.v == TMPVAR0)
  2788. L.v = res;
  2789. /* if source is a temporary string, jusk relink it to dest */
  2790. if (R.v == TMPVAR1
  2791. && !(R.v->type & VF_NUMBER)
  2792. /* Why check !NUMBER? if R.v is a number but has cached R.v->string,
  2793. * L.v ends up a string, which is wrong */
  2794. /*&& R.v->string - always not NULL (right?) */
  2795. ) {
  2796. res = setvar_p(L.v, R.v->string); /* avoids strdup */
  2797. R.v->string = NULL;
  2798. } else {
  2799. res = copyvar(L.v, R.v);
  2800. }
  2801. break;
  2802. case XC( OC_TERNARY ):
  2803. debug_printf_eval("TERNARY\n");
  2804. if (op->r.n->info != TI_COLON)
  2805. syntax_error(EMSG_POSSIBLE_ERROR);
  2806. res = evaluate(istrue(L.v) ? op->r.n->l.n : op->r.n->r.n, res);
  2807. break;
  2808. case XC( OC_FUNC ): {
  2809. var *argvars, *sv_fnargs;
  2810. const char *sv_progname;
  2811. int nargs, i;
  2812. debug_printf_eval("FUNC\n");
  2813. if (!op->r.f->defined)
  2814. syntax_error(EMSG_UNDEF_FUNC);
  2815. /* The body might be empty, still has to eval the args */
  2816. nargs = op->r.f->nargs;
  2817. argvars = nvalloc(nargs);
  2818. i = 0;
  2819. while (op1) {
  2820. var *arg = evaluate(nextarg(&op1), TMPVAR0);
  2821. if (i == nargs) {
  2822. /* call with more arguments than function takes.
  2823. * (gawk warns: "warning: function 'f' called with more arguments than declared").
  2824. * They are still evaluated, but discarded: */
  2825. clrvar(arg);
  2826. continue;
  2827. }
  2828. copyvar(&argvars[i], arg);
  2829. argvars[i].type |= VF_CHILD;
  2830. argvars[i].x.parent = arg;
  2831. i++;
  2832. }
  2833. sv_fnargs = fnargs;
  2834. sv_progname = g_progname;
  2835. fnargs = argvars;
  2836. res = evaluate(op->r.f->body.first, res);
  2837. nvfree(argvars, nargs);
  2838. g_progname = sv_progname;
  2839. fnargs = sv_fnargs;
  2840. break;
  2841. }
  2842. case XC( OC_GETLINE ):
  2843. debug_printf_eval("GETLINE /\n");
  2844. case XC( OC_PGETLINE ):
  2845. debug_printf_eval("PGETLINE\n");
  2846. {
  2847. rstream *rsm;
  2848. int i;
  2849. if (op1) {
  2850. rsm = newfile(L.s);
  2851. if (!rsm->F) {
  2852. /* NB: can't use "opinfo == TI_PGETLINE", would break "cmd" | getline */
  2853. if ((opinfo & OPCLSMASK) == OC_PGETLINE) {
  2854. rsm->F = popen(L.s, "r");
  2855. rsm->is_pipe = TRUE;
  2856. } else {
  2857. rsm->F = fopen_for_read(L.s); /* not xfopen! */
  2858. }
  2859. }
  2860. } else {
  2861. if (!iF)
  2862. iF = next_input_file();
  2863. rsm = iF;
  2864. }
  2865. if (!rsm || !rsm->F) {
  2866. setvar_i(intvar[ERRNO], errno);
  2867. setvar_i(res, -1);
  2868. break;
  2869. }
  2870. if (!op->r.n)
  2871. R.v = intvar[F0];
  2872. i = awk_getline(rsm, R.v);
  2873. if (i > 0 && !op1) {
  2874. incvar(intvar[FNR]);
  2875. incvar(intvar[NR]);
  2876. }
  2877. setvar_i(res, i);
  2878. break;
  2879. }
  2880. /* simple builtins */
  2881. case XC( OC_FBLTIN ): {
  2882. double R_d = R_d; /* for compiler */
  2883. debug_printf_eval("FBLTIN\n");
  2884. if (op1 && op1->info == TI_COMMA)
  2885. /* Simple builtins take one arg maximum */
  2886. syntax_error("Too many arguments");
  2887. switch (opn) {
  2888. case F_in:
  2889. R_d = (long long)L_d;
  2890. break;
  2891. case F_rn: /*rand*/
  2892. if (op1)
  2893. syntax_error("Too many arguments");
  2894. {
  2895. #if RAND_MAX >= 0x7fffffff
  2896. uint32_t u = ((uint32_t)rand() << 16) ^ rand();
  2897. uint64_t v = ((uint64_t)rand() << 32) | u;
  2898. /* the above shift+or is optimized out on 32-bit arches */
  2899. # if RAND_MAX > 0x7fffffff
  2900. v &= 0x7fffffffffffffffULL;
  2901. # endif
  2902. R_d = (double)v / 0x8000000000000000ULL;
  2903. #else
  2904. # error Not implemented for this value of RAND_MAX
  2905. #endif
  2906. break;
  2907. }
  2908. case F_co:
  2909. if (ENABLE_FEATURE_AWK_LIBM) {
  2910. R_d = cos(L_d);
  2911. break;
  2912. }
  2913. case F_ex:
  2914. if (ENABLE_FEATURE_AWK_LIBM) {
  2915. R_d = exp(L_d);
  2916. break;
  2917. }
  2918. case F_lg:
  2919. if (ENABLE_FEATURE_AWK_LIBM) {
  2920. R_d = log(L_d);
  2921. break;
  2922. }
  2923. case F_si:
  2924. if (ENABLE_FEATURE_AWK_LIBM) {
  2925. R_d = sin(L_d);
  2926. break;
  2927. }
  2928. case F_sq:
  2929. if (ENABLE_FEATURE_AWK_LIBM) {
  2930. R_d = sqrt(L_d);
  2931. break;
  2932. }
  2933. syntax_error(EMSG_NO_MATH);
  2934. break;
  2935. case F_sr:
  2936. R_d = (double)seed;
  2937. seed = op1 ? (unsigned)L_d : (unsigned)time(NULL);
  2938. srand(seed);
  2939. break;
  2940. case F_ti: /*systime*/
  2941. if (op1)
  2942. syntax_error("Too many arguments");
  2943. R_d = time(NULL);
  2944. break;
  2945. case F_le:
  2946. debug_printf_eval("length: L.s:'%s'\n", L.s);
  2947. if (!op1) {
  2948. L.s = getvar_s(intvar[F0]);
  2949. debug_printf_eval("length: L.s='%s'\n", L.s);
  2950. }
  2951. else if (L.v->type & VF_ARRAY) {
  2952. R_d = L.v->x.array->nel;
  2953. debug_printf_eval("length: array_len:%d\n", L.v->x.array->nel);
  2954. break;
  2955. }
  2956. R_d = strlen(L.s);
  2957. break;
  2958. case F_sy:
  2959. fflush_all();
  2960. R_d = (ENABLE_FEATURE_ALLOW_EXEC && L.s && *L.s)
  2961. ? (system(L.s) >> 8) : 0;
  2962. break;
  2963. case F_ff:
  2964. if (!op1) {
  2965. fflush(stdout);
  2966. } else if (L.s && *L.s) {
  2967. rstream *rsm = newfile(L.s);
  2968. fflush(rsm->F);
  2969. } else {
  2970. fflush_all();
  2971. }
  2972. break;
  2973. case F_cl: {
  2974. rstream *rsm;
  2975. int err = 0;
  2976. rsm = (rstream *)hash_search(fdhash, L.s);
  2977. debug_printf_eval("OC_FBLTIN close: op1:%p s:'%s' rsm:%p\n", op1, L.s, rsm);
  2978. if (rsm) {
  2979. debug_printf_eval("OC_FBLTIN F_cl "
  2980. "rsm->is_pipe:%d, ->F:%p\n",
  2981. rsm->is_pipe, rsm->F);
  2982. /* Can be NULL if open failed. Example:
  2983. * getline line <"doesnt_exist";
  2984. * close("doesnt_exist"); <--- here rsm->F is NULL
  2985. */
  2986. if (rsm->F)
  2987. err = rsm->is_pipe ? pclose(rsm->F) : fclose(rsm->F);
  2988. //TODO: fix this case:
  2989. // $ awk 'BEGIN { print close(""); print ERRNO }'
  2990. // -1
  2991. // close of redirection that was never opened
  2992. // (we print 0, 0)
  2993. free(rsm->buffer);
  2994. hash_remove(fdhash, L.s);
  2995. }
  2996. if (err)
  2997. setvar_i(intvar[ERRNO], errno);
  2998. R_d = (double)err;
  2999. break;
  3000. }
  3001. } /* switch */
  3002. setvar_i(res, R_d);
  3003. break;
  3004. }
  3005. case XC( OC_BUILTIN ):
  3006. debug_printf_eval("BUILTIN\n");
  3007. res = exec_builtin(op, res);
  3008. break;
  3009. case XC( OC_SPRINTF ):
  3010. debug_printf_eval("SPRINTF\n");
  3011. setvar_p(res, awk_printf(op1, NULL));
  3012. break;
  3013. case XC( OC_UNARY ):
  3014. debug_printf_eval("UNARY\n");
  3015. {
  3016. double Ld, R_d;
  3017. Ld = R_d = getvar_i(R.v);
  3018. switch (opn) {
  3019. case 'P':
  3020. Ld = ++R_d;
  3021. goto r_op_change;
  3022. case 'p':
  3023. R_d++;
  3024. goto r_op_change;
  3025. case 'M':
  3026. Ld = --R_d;
  3027. goto r_op_change;
  3028. case 'm':
  3029. R_d--;
  3030. r_op_change:
  3031. setvar_i(R.v, R_d);
  3032. break;
  3033. case '!':
  3034. Ld = !istrue(R.v);
  3035. break;
  3036. case '-':
  3037. Ld = -R_d;
  3038. break;
  3039. }
  3040. setvar_i(res, Ld);
  3041. break;
  3042. }
  3043. case XC( OC_FIELD ):
  3044. debug_printf_eval("FIELD\n");
  3045. {
  3046. int i = (int)getvar_i(R.v);
  3047. if (i < 0)
  3048. syntax_error(EMSG_NEGATIVE_FIELD);
  3049. if (i == 0) {
  3050. res = intvar[F0];
  3051. } else {
  3052. split_f0();
  3053. if (i > nfields)
  3054. fsrealloc(i);
  3055. res = &Fields[i - 1];
  3056. }
  3057. break;
  3058. }
  3059. /* concatenation (" ") and index joining (",") */
  3060. case XC( OC_CONCAT ):
  3061. debug_printf_eval("CONCAT /\n");
  3062. case XC( OC_COMMA ): {
  3063. const char *sep = "";
  3064. debug_printf_eval("COMMA\n");
  3065. if (opinfo == TI_COMMA)
  3066. sep = getvar_s(intvar[SUBSEP]);
  3067. setvar_p(res, xasprintf("%s%s%s", L.s, sep, R.s));
  3068. break;
  3069. }
  3070. case XC( OC_LAND ):
  3071. debug_printf_eval("LAND\n");
  3072. setvar_i(res, istrue(L.v) ? ptest(op->r.n) : 0);
  3073. break;
  3074. case XC( OC_LOR ):
  3075. debug_printf_eval("LOR\n");
  3076. setvar_i(res, istrue(L.v) ? 1 : ptest(op->r.n));
  3077. break;
  3078. case XC( OC_BINARY ):
  3079. debug_printf_eval("BINARY /\n");
  3080. case XC( OC_REPLACE ):
  3081. debug_printf_eval("REPLACE\n");
  3082. {
  3083. double R_d = getvar_i(R.v);
  3084. debug_printf_eval("R_d:%f opn:%c\n", R_d, opn);
  3085. switch (opn) {
  3086. case '+':
  3087. L_d += R_d;
  3088. break;
  3089. case '-':
  3090. L_d -= R_d;
  3091. break;
  3092. case '*':
  3093. L_d *= R_d;
  3094. break;
  3095. case '/':
  3096. if (R_d == 0)
  3097. syntax_error(EMSG_DIV_BY_ZERO);
  3098. L_d /= R_d;
  3099. break;
  3100. case '&':
  3101. if (ENABLE_FEATURE_AWK_LIBM)
  3102. L_d = pow(L_d, R_d);
  3103. else
  3104. syntax_error(EMSG_NO_MATH);
  3105. break;
  3106. case '%':
  3107. if (R_d == 0)
  3108. syntax_error(EMSG_DIV_BY_ZERO);
  3109. L_d -= (long long)(L_d / R_d) * R_d;
  3110. break;
  3111. }
  3112. debug_printf_eval("BINARY/REPLACE result:%f\n", L_d);
  3113. res = setvar_i(((opinfo & OPCLSMASK) == OC_BINARY) ? res : L.v, L_d);
  3114. break;
  3115. }
  3116. case XC( OC_COMPARE ): {
  3117. int i = i; /* for compiler */
  3118. double Ld;
  3119. debug_printf_eval("COMPARE\n");
  3120. if (is_numeric(L.v) && is_numeric(R.v)) {
  3121. Ld = getvar_i(L.v) - getvar_i(R.v);
  3122. } else {
  3123. const char *l = getvar_s(L.v);
  3124. const char *r = getvar_s(R.v);
  3125. Ld = icase ? strcasecmp(l, r) : strcmp(l, r);
  3126. }
  3127. switch (opn & 0xfe) {
  3128. case 0:
  3129. i = (Ld > 0);
  3130. break;
  3131. case 2:
  3132. i = (Ld >= 0);
  3133. break;
  3134. case 4:
  3135. i = (Ld == 0);
  3136. break;
  3137. }
  3138. debug_printf_eval("COMPARE result: %d\n", (i == 0) ^ (opn & 1));
  3139. setvar_i(res, (i == 0) ^ (opn & 1));
  3140. break;
  3141. }
  3142. default:
  3143. syntax_error(EMSG_POSSIBLE_ERROR);
  3144. } /* switch */
  3145. if ((opinfo & OPCLSMASK) <= SHIFT_TIL_THIS)
  3146. op = op->a.n;
  3147. if ((opinfo & OPCLSMASK) >= RECUR_FROM_THIS)
  3148. break;
  3149. if (nextrec)
  3150. break;
  3151. } /* while (op) */
  3152. nvfree(tmpvars, 2);
  3153. #undef TMPVAR0
  3154. #undef TMPVAR1
  3155. debug_printf_eval("returning from %s(): %p\n", __func__, res);
  3156. return res;
  3157. #undef fnargs
  3158. #undef seed
  3159. #undef sreg
  3160. }
  3161. /* -------- main & co. -------- */
  3162. static int awk_exit(void)
  3163. {
  3164. unsigned i;
  3165. if (!exiting) {
  3166. exiting = TRUE;
  3167. nextrec = FALSE;
  3168. evaluate(endseq.first, &G.exit__tmpvar);
  3169. }
  3170. /* waiting for children */
  3171. for (i = 0; i < fdhash->csize; i++) {
  3172. hash_item *hi;
  3173. hi = fdhash->items[i];
  3174. while (hi) {
  3175. if (hi->data.rs.F && hi->data.rs.is_pipe)
  3176. pclose(hi->data.rs.F);
  3177. hi = hi->next;
  3178. }
  3179. }
  3180. exit(G.exitcode);
  3181. }
  3182. int awk_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  3183. int awk_main(int argc UNUSED_PARAM, char **argv)
  3184. {
  3185. unsigned opt;
  3186. char *opt_F;
  3187. llist_t *list_v = NULL;
  3188. llist_t *list_f = NULL;
  3189. #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  3190. llist_t *list_e = NULL;
  3191. #endif
  3192. int i;
  3193. INIT_G();
  3194. /* Undo busybox.c, or else strtod may eat ','! This breaks parsing:
  3195. * $1,$2 == '$1,' '$2', NOT '$1' ',' '$2' */
  3196. if (ENABLE_LOCALE_SUPPORT)
  3197. setlocale(LC_NUMERIC, "C");
  3198. /* initialize variables */
  3199. vhash = hash_init();
  3200. {
  3201. char *vnames = (char *)vNames; /* cheat */
  3202. char *vvalues = (char *)vValues;
  3203. for (i = 0; *vnames; i++) {
  3204. var *v;
  3205. intvar[i] = v = newvar(nextword(&vnames));
  3206. if (*vvalues != '\377')
  3207. setvar_s(v, nextword(&vvalues));
  3208. else
  3209. setvar_i(v, 0);
  3210. if (*vnames == '*') {
  3211. v->type |= VF_SPECIAL;
  3212. vnames++;
  3213. }
  3214. }
  3215. }
  3216. handle_special(intvar[FS]);
  3217. handle_special(intvar[RS]);
  3218. /* Huh, people report that sometimes environ is NULL. Oh well. */
  3219. if (environ) {
  3220. char **envp;
  3221. for (envp = environ; *envp; envp++) {
  3222. /* environ is writable, thus we don't strdup it needlessly */
  3223. char *s = *envp;
  3224. char *s1 = strchr(s, '=');
  3225. if (s1) {
  3226. *s1 = '\0';
  3227. /* Both findvar and setvar_u take const char*
  3228. * as 2nd arg -> environment is not trashed */
  3229. setvar_u(findvar(iamarray(intvar[ENVIRON]), s), s1 + 1);
  3230. *s1 = '=';
  3231. }
  3232. }
  3233. }
  3234. opt = getopt32(argv, OPTSTR_AWK, &opt_F, &list_v, &list_f, IF_FEATURE_AWK_GNU_EXTENSIONS(&list_e,) NULL);
  3235. argv += optind;
  3236. //argc -= optind;
  3237. if (opt & OPT_W)
  3238. bb_simple_error_msg("warning: option -W is ignored");
  3239. if (opt & OPT_F) {
  3240. unescape_string_in_place(opt_F);
  3241. setvar_s(intvar[FS], opt_F);
  3242. }
  3243. while (list_v) {
  3244. if (!is_assignment(llist_pop(&list_v)))
  3245. bb_show_usage();
  3246. }
  3247. /* Parse all supplied programs */
  3248. fnhash = hash_init();
  3249. ahash = hash_init();
  3250. while (list_f) {
  3251. int fd;
  3252. char *s;
  3253. g_progname = llist_pop(&list_f);
  3254. fd = xopen_stdin(g_progname);
  3255. s = xmalloc_read(fd, NULL); /* it's NUL-terminated */
  3256. close(fd);
  3257. parse_program(s);
  3258. free(s);
  3259. }
  3260. g_progname = "cmd. line";
  3261. #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  3262. while (list_e) {
  3263. parse_program(llist_pop(&list_e));
  3264. }
  3265. #endif
  3266. //FIXME: preserve order of -e and -f
  3267. //TODO: implement -i LIBRARY and -E FILE too, they are easy-ish
  3268. if (!(opt & (OPT_f | OPT_e))) {
  3269. if (!*argv)
  3270. bb_show_usage();
  3271. parse_program(*argv++);
  3272. }
  3273. /* Free unused parse structures */
  3274. //hash_free(fnhash); // ~250 bytes when empty, used only for function names
  3275. //^^^^^^^^^^^^^^^^^ does not work, hash_clear() inside SEGVs
  3276. // (IOW: hash_clear() assumes it's a hash of variables. fnhash is not).
  3277. free(fnhash->items);
  3278. free(fnhash);
  3279. fnhash = NULL; // debug
  3280. //hash_free(ahash); // empty after parsing, will reuse as fdhash instead of freeing
  3281. /* Parsing done, on to executing */
  3282. /* fill in ARGV array */
  3283. setari_u(intvar[ARGV], 0, "awk");
  3284. i = 0;
  3285. while (*argv)
  3286. setari_u(intvar[ARGV], ++i, *argv++);
  3287. setvar_i(intvar[ARGC], i + 1);
  3288. //fdhash = ahash; // done via define
  3289. newfile("/dev/stdin")->F = stdin;
  3290. newfile("/dev/stdout")->F = stdout;
  3291. newfile("/dev/stderr")->F = stderr;
  3292. evaluate(beginseq.first, &G.main__tmpvar);
  3293. if (!mainseq.first && !endseq.first)
  3294. awk_exit();
  3295. /* input file could already be opened in BEGIN block */
  3296. if (!iF)
  3297. iF = next_input_file();
  3298. /* passing through input files */
  3299. while (iF) {
  3300. nextfile = FALSE;
  3301. setvar_i(intvar[FNR], 0);
  3302. while ((i = awk_getline(iF, intvar[F0])) > 0) {
  3303. nextrec = FALSE;
  3304. incvar(intvar[NR]);
  3305. incvar(intvar[FNR]);
  3306. evaluate(mainseq.first, &G.main__tmpvar);
  3307. if (nextfile)
  3308. break;
  3309. }
  3310. if (i < 0)
  3311. syntax_error(strerror(errno));
  3312. iF = next_input_file();
  3313. }
  3314. awk_exit();
  3315. /*return 0;*/
  3316. }