awk.c 75 KB

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