awk.c 76 KB

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