awk.c 77 KB

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