awk.c 79 KB

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