awk.c 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340
  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[] = {
  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 awk_split(const char *s, node *spl, char **slist)
  1560. {
  1561. int l, n;
  1562. char c[4];
  1563. char *s1;
  1564. regmatch_t pmatch[2]; // TODO: why [2]? [1] is enough...
  1565. /* in worst case, each char would be a separate field */
  1566. *slist = s1 = xzalloc(strlen(s) * 2 + 3);
  1567. strcpy(s1, s);
  1568. c[0] = c[1] = (char)spl->info;
  1569. c[2] = c[3] = '\0';
  1570. if (*getvar_s(intvar[RS]) == '\0')
  1571. c[2] = '\n';
  1572. n = 0;
  1573. if ((spl->info & OPCLSMASK) == OC_REGEXP) { /* regex split */
  1574. if (!*s)
  1575. return n; /* "": zero fields */
  1576. n++; /* at least one field will be there */
  1577. do {
  1578. l = strcspn(s, c+2); /* len till next NUL or \n */
  1579. if (regexec(icase ? spl->r.ire : spl->l.re, s, 1, pmatch, 0) == 0
  1580. && pmatch[0].rm_so <= l
  1581. ) {
  1582. l = pmatch[0].rm_so;
  1583. if (pmatch[0].rm_eo == 0) {
  1584. l++;
  1585. pmatch[0].rm_eo++;
  1586. }
  1587. n++; /* we saw yet another delimiter */
  1588. } else {
  1589. pmatch[0].rm_eo = l;
  1590. if (s[l])
  1591. pmatch[0].rm_eo++;
  1592. }
  1593. memcpy(s1, s, l);
  1594. /* make sure we remove *all* of the separator chars */
  1595. do {
  1596. s1[l] = '\0';
  1597. } while (++l < pmatch[0].rm_eo);
  1598. nextword(&s1);
  1599. s += pmatch[0].rm_eo;
  1600. } while (*s);
  1601. return n;
  1602. }
  1603. if (c[0] == '\0') { /* null split */
  1604. while (*s) {
  1605. *s1++ = *s++;
  1606. *s1++ = '\0';
  1607. n++;
  1608. }
  1609. return n;
  1610. }
  1611. if (c[0] != ' ') { /* single-character split */
  1612. if (icase) {
  1613. c[0] = toupper(c[0]);
  1614. c[1] = tolower(c[1]);
  1615. }
  1616. if (*s1)
  1617. n++;
  1618. while ((s1 = strpbrk(s1, c)) != NULL) {
  1619. *s1++ = '\0';
  1620. n++;
  1621. }
  1622. return n;
  1623. }
  1624. /* space split */
  1625. while (*s) {
  1626. s = skip_whitespace(s);
  1627. if (!*s)
  1628. break;
  1629. n++;
  1630. while (*s && !isspace(*s))
  1631. *s1++ = *s++;
  1632. *s1++ = '\0';
  1633. }
  1634. return n;
  1635. }
  1636. static void split_f0(void)
  1637. {
  1638. /* static char *fstrings; */
  1639. #define fstrings (G.split_f0__fstrings)
  1640. int i, n;
  1641. char *s;
  1642. if (is_f0_split)
  1643. return;
  1644. is_f0_split = TRUE;
  1645. free(fstrings);
  1646. fsrealloc(0);
  1647. n = awk_split(getvar_s(intvar[F0]), &fsplitter.n, &fstrings);
  1648. fsrealloc(n);
  1649. s = fstrings;
  1650. for (i = 0; i < n; i++) {
  1651. Fields[i].string = nextword(&s);
  1652. Fields[i].type |= (VF_FSTR | VF_USER | VF_DIRTY);
  1653. }
  1654. /* set NF manually to avoid side effects */
  1655. clrvar(intvar[NF]);
  1656. intvar[NF]->type = VF_NUMBER | VF_SPECIAL;
  1657. intvar[NF]->number = nfields;
  1658. #undef fstrings
  1659. }
  1660. /* perform additional actions when some internal variables changed */
  1661. static void handle_special(var *v)
  1662. {
  1663. int n;
  1664. char *b;
  1665. const char *sep, *s;
  1666. int sl, l, len, i, bsize;
  1667. if (!(v->type & VF_SPECIAL))
  1668. return;
  1669. if (v == intvar[NF]) {
  1670. n = (int)getvar_i(v);
  1671. if (n < 0)
  1672. syntax_error("NF set to negative value");
  1673. fsrealloc(n);
  1674. /* recalculate $0 */
  1675. sep = getvar_s(intvar[OFS]);
  1676. sl = strlen(sep);
  1677. b = NULL;
  1678. len = 0;
  1679. for (i = 0; i < n; i++) {
  1680. s = getvar_s(&Fields[i]);
  1681. l = strlen(s);
  1682. if (b) {
  1683. memcpy(b+len, sep, sl);
  1684. len += sl;
  1685. }
  1686. b = qrealloc(b, len+l+sl, &bsize);
  1687. memcpy(b+len, s, l);
  1688. len += l;
  1689. }
  1690. if (b)
  1691. b[len] = '\0';
  1692. setvar_p(intvar[F0], b);
  1693. is_f0_split = TRUE;
  1694. } else if (v == intvar[F0]) {
  1695. is_f0_split = FALSE;
  1696. } else if (v == intvar[FS]) {
  1697. /*
  1698. * The POSIX-2008 standard says that changing FS should have no effect on the
  1699. * current input line, but only on the next one. The language is:
  1700. *
  1701. * > Before the first reference to a field in the record is evaluated, the record
  1702. * > shall be split into fields, according to the rules in Regular Expressions,
  1703. * > using the value of FS that was current at the time the record was read.
  1704. *
  1705. * So, split up current line before assignment to FS:
  1706. */
  1707. split_f0();
  1708. mk_splitter(getvar_s(v), &fsplitter);
  1709. } else if (v == intvar[RS]) {
  1710. mk_splitter(getvar_s(v), &rsplitter);
  1711. } else if (v == intvar[IGNORECASE]) {
  1712. icase = istrue(v);
  1713. } else { /* $n */
  1714. n = getvar_i(intvar[NF]);
  1715. setvar_i(intvar[NF], n > v-Fields ? n : v-Fields+1);
  1716. /* right here v is invalid. Just to note... */
  1717. }
  1718. }
  1719. /* step through func/builtin/etc arguments */
  1720. static node *nextarg(node **pn)
  1721. {
  1722. node *n;
  1723. n = *pn;
  1724. if (n && (n->info & OPCLSMASK) == OC_COMMA) {
  1725. *pn = n->r.n;
  1726. n = n->l.n;
  1727. } else {
  1728. *pn = NULL;
  1729. }
  1730. return n;
  1731. }
  1732. static void hashwalk_init(var *v, xhash *array)
  1733. {
  1734. hash_item *hi;
  1735. unsigned i;
  1736. walker_list *w;
  1737. walker_list *prev_walker;
  1738. if (v->type & VF_WALK) {
  1739. prev_walker = v->x.walker;
  1740. } else {
  1741. v->type |= VF_WALK;
  1742. prev_walker = NULL;
  1743. }
  1744. debug_printf_walker("hashwalk_init: prev_walker:%p\n", prev_walker);
  1745. w = v->x.walker = xzalloc(sizeof(*w) + array->glen + 1); /* why + 1? */
  1746. debug_printf_walker(" walker@%p=%p\n", &v->x.walker, w);
  1747. w->cur = w->end = w->wbuf;
  1748. w->prev = prev_walker;
  1749. for (i = 0; i < array->csize; i++) {
  1750. hi = array->items[i];
  1751. while (hi) {
  1752. strcpy(w->end, hi->name);
  1753. nextword(&w->end);
  1754. hi = hi->next;
  1755. }
  1756. }
  1757. }
  1758. static int hashwalk_next(var *v)
  1759. {
  1760. walker_list *w = v->x.walker;
  1761. if (w->cur >= w->end) {
  1762. walker_list *prev_walker = w->prev;
  1763. debug_printf_walker("end of iteration, free(walker@%p:%p), prev_walker:%p\n", &v->x.walker, w, prev_walker);
  1764. free(w);
  1765. v->x.walker = prev_walker;
  1766. return FALSE;
  1767. }
  1768. setvar_s(v, nextword(&w->cur));
  1769. return TRUE;
  1770. }
  1771. /* evaluate node, return 1 when result is true, 0 otherwise */
  1772. static int ptest(node *pattern)
  1773. {
  1774. /* ptest__v is "static": to save stack space? */
  1775. return istrue(evaluate(pattern, &G.ptest__v));
  1776. }
  1777. /* read next record from stream rsm into a variable v */
  1778. static int awk_getline(rstream *rsm, var *v)
  1779. {
  1780. char *b;
  1781. regmatch_t pmatch[2];
  1782. int size, a, p, pp = 0;
  1783. int fd, so, eo, r, rp;
  1784. char c, *m, *s;
  1785. debug_printf_eval("entered %s()\n", __func__);
  1786. /* we're using our own buffer since we need access to accumulating
  1787. * characters
  1788. */
  1789. fd = fileno(rsm->F);
  1790. m = rsm->buffer;
  1791. a = rsm->adv;
  1792. p = rsm->pos;
  1793. size = rsm->size;
  1794. c = (char) rsplitter.n.info;
  1795. rp = 0;
  1796. if (!m)
  1797. m = qrealloc(m, 256, &size);
  1798. do {
  1799. b = m + a;
  1800. so = eo = p;
  1801. r = 1;
  1802. if (p > 0) {
  1803. if ((rsplitter.n.info & OPCLSMASK) == OC_REGEXP) {
  1804. if (regexec(icase ? rsplitter.n.r.ire : rsplitter.n.l.re,
  1805. b, 1, pmatch, 0) == 0) {
  1806. so = pmatch[0].rm_so;
  1807. eo = pmatch[0].rm_eo;
  1808. if (b[eo] != '\0')
  1809. break;
  1810. }
  1811. } else if (c != '\0') {
  1812. s = strchr(b+pp, c);
  1813. if (!s)
  1814. s = memchr(b+pp, '\0', p - pp);
  1815. if (s) {
  1816. so = eo = s-b;
  1817. eo++;
  1818. break;
  1819. }
  1820. } else {
  1821. while (b[rp] == '\n')
  1822. rp++;
  1823. s = strstr(b+rp, "\n\n");
  1824. if (s) {
  1825. so = eo = s-b;
  1826. while (b[eo] == '\n')
  1827. eo++;
  1828. if (b[eo] != '\0')
  1829. break;
  1830. }
  1831. }
  1832. }
  1833. if (a > 0) {
  1834. memmove(m, m+a, p+1);
  1835. b = m;
  1836. a = 0;
  1837. }
  1838. m = qrealloc(m, a+p+128, &size);
  1839. b = m + a;
  1840. pp = p;
  1841. p += safe_read(fd, b+p, size-p-1);
  1842. if (p < pp) {
  1843. p = 0;
  1844. r = 0;
  1845. setvar_i(intvar[ERRNO], errno);
  1846. }
  1847. b[p] = '\0';
  1848. } while (p > pp);
  1849. if (p == 0) {
  1850. r--;
  1851. } else {
  1852. c = b[so]; b[so] = '\0';
  1853. setvar_s(v, b+rp);
  1854. v->type |= VF_USER;
  1855. b[so] = c;
  1856. c = b[eo]; b[eo] = '\0';
  1857. setvar_s(intvar[RT], b+so);
  1858. b[eo] = c;
  1859. }
  1860. rsm->buffer = m;
  1861. rsm->adv = a + eo;
  1862. rsm->pos = p - eo;
  1863. rsm->size = size;
  1864. debug_printf_eval("returning from %s(): %d\n", __func__, r);
  1865. return r;
  1866. }
  1867. static int fmt_num(char *b, int size, const char *format, double n, int int_as_int)
  1868. {
  1869. int r = 0;
  1870. char c;
  1871. const char *s = format;
  1872. if (int_as_int && n == (long long)n) {
  1873. r = snprintf(b, size, "%lld", (long long)n);
  1874. } else {
  1875. do { c = *s; } while (c && *++s);
  1876. if (strchr("diouxX", c)) {
  1877. r = snprintf(b, size, format, (int)n);
  1878. } else if (strchr("eEfgG", c)) {
  1879. r = snprintf(b, size, format, n);
  1880. } else {
  1881. syntax_error(EMSG_INV_FMT);
  1882. }
  1883. }
  1884. return r;
  1885. }
  1886. /* formatted output into an allocated buffer, return ptr to buffer */
  1887. static char *awk_printf(node *n)
  1888. {
  1889. char *b = NULL;
  1890. char *fmt, *s, *f;
  1891. const char *s1;
  1892. int i, j, incr, bsize;
  1893. char c, c1;
  1894. var *v, *arg;
  1895. v = nvalloc(1);
  1896. fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), v)));
  1897. i = 0;
  1898. while (*f) {
  1899. s = f;
  1900. while (*f && (*f != '%' || *++f == '%'))
  1901. f++;
  1902. while (*f && !isalpha(*f)) {
  1903. if (*f == '*')
  1904. syntax_error("%*x formats are not supported");
  1905. f++;
  1906. }
  1907. incr = (f - s) + MAXVARFMT;
  1908. b = qrealloc(b, incr + i, &bsize);
  1909. c = *f;
  1910. if (c != '\0')
  1911. f++;
  1912. c1 = *f;
  1913. *f = '\0';
  1914. arg = evaluate(nextarg(&n), v);
  1915. j = i;
  1916. if (c == 'c' || !c) {
  1917. i += sprintf(b+i, s, is_numeric(arg) ?
  1918. (char)getvar_i(arg) : *getvar_s(arg));
  1919. } else if (c == 's') {
  1920. s1 = getvar_s(arg);
  1921. b = qrealloc(b, incr+i+strlen(s1), &bsize);
  1922. i += sprintf(b+i, s, s1);
  1923. } else {
  1924. i += fmt_num(b+i, incr, s, getvar_i(arg), FALSE);
  1925. }
  1926. *f = c1;
  1927. /* if there was an error while sprintf, return value is negative */
  1928. if (i < j)
  1929. i = j;
  1930. }
  1931. free(fmt);
  1932. nvfree(v);
  1933. b = xrealloc(b, i + 1);
  1934. b[i] = '\0';
  1935. return b;
  1936. }
  1937. /* Common substitution routine.
  1938. * Replace (nm)'th substring of (src) that matches (rn) with (repl),
  1939. * store result into (dest), return number of substitutions.
  1940. * If nm = 0, replace all matches.
  1941. * If src or dst is NULL, use $0.
  1942. * If subexp != 0, enable subexpression matching (\1-\9).
  1943. */
  1944. static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest, int subexp)
  1945. {
  1946. char *resbuf;
  1947. const char *sp;
  1948. int match_no, residx, replen, resbufsize;
  1949. int regexec_flags;
  1950. regmatch_t pmatch[10];
  1951. regex_t sreg, *regex;
  1952. resbuf = NULL;
  1953. residx = 0;
  1954. match_no = 0;
  1955. regexec_flags = 0;
  1956. regex = as_regex(rn, &sreg);
  1957. sp = getvar_s(src ? src : intvar[F0]);
  1958. replen = strlen(repl);
  1959. while (regexec(regex, sp, 10, pmatch, regexec_flags) == 0) {
  1960. int so = pmatch[0].rm_so;
  1961. int eo = pmatch[0].rm_eo;
  1962. //bb_error_msg("match %u: [%u,%u] '%s'%p", match_no+1, so, eo, sp,sp);
  1963. resbuf = qrealloc(resbuf, residx + eo + replen, &resbufsize);
  1964. memcpy(resbuf + residx, sp, eo);
  1965. residx += eo;
  1966. if (++match_no >= nm) {
  1967. const char *s;
  1968. int nbs;
  1969. /* replace */
  1970. residx -= (eo - so);
  1971. nbs = 0;
  1972. for (s = repl; *s; s++) {
  1973. char c = resbuf[residx++] = *s;
  1974. if (c == '\\') {
  1975. nbs++;
  1976. continue;
  1977. }
  1978. if (c == '&' || (subexp && c >= '0' && c <= '9')) {
  1979. int j;
  1980. residx -= ((nbs + 3) >> 1);
  1981. j = 0;
  1982. if (c != '&') {
  1983. j = c - '0';
  1984. nbs++;
  1985. }
  1986. if (nbs % 2) {
  1987. resbuf[residx++] = c;
  1988. } else {
  1989. int n = pmatch[j].rm_eo - pmatch[j].rm_so;
  1990. resbuf = qrealloc(resbuf, residx + replen + n, &resbufsize);
  1991. memcpy(resbuf + residx, sp + pmatch[j].rm_so, n);
  1992. residx += n;
  1993. }
  1994. }
  1995. nbs = 0;
  1996. }
  1997. }
  1998. regexec_flags = REG_NOTBOL;
  1999. sp += eo;
  2000. if (match_no == nm)
  2001. break;
  2002. if (eo == so) {
  2003. /* Empty match (e.g. "b*" will match anywhere).
  2004. * Advance by one char. */
  2005. //BUG (bug 1333):
  2006. //gsub(/\<b*/,"") on "abc" will reach this point, advance to "bc"
  2007. //... and will erroneously match "b" even though it is NOT at the word start.
  2008. //we need REG_NOTBOW but it does not exist...
  2009. //TODO: if EXTRA_COMPAT=y, use GNU matching and re_search,
  2010. //it should be able to do it correctly.
  2011. /* Subtle: this is safe only because
  2012. * qrealloc allocated at least one extra byte */
  2013. resbuf[residx] = *sp;
  2014. if (*sp == '\0')
  2015. goto ret;
  2016. sp++;
  2017. residx++;
  2018. }
  2019. }
  2020. resbuf = qrealloc(resbuf, residx + strlen(sp), &resbufsize);
  2021. strcpy(resbuf + residx, sp);
  2022. ret:
  2023. //bb_error_msg("end sp:'%s'%p", sp,sp);
  2024. setvar_p(dest ? dest : intvar[F0], resbuf);
  2025. if (regex == &sreg)
  2026. regfree(regex);
  2027. return match_no;
  2028. }
  2029. static NOINLINE int do_mktime(const char *ds)
  2030. {
  2031. struct tm then;
  2032. int count;
  2033. /*memset(&then, 0, sizeof(then)); - not needed */
  2034. then.tm_isdst = -1; /* default is unknown */
  2035. /* manpage of mktime says these fields are ints,
  2036. * so we can sscanf stuff directly into them */
  2037. count = sscanf(ds, "%u %u %u %u %u %u %d",
  2038. &then.tm_year, &then.tm_mon, &then.tm_mday,
  2039. &then.tm_hour, &then.tm_min, &then.tm_sec,
  2040. &then.tm_isdst);
  2041. if (count < 6
  2042. || (unsigned)then.tm_mon < 1
  2043. || (unsigned)then.tm_year < 1900
  2044. ) {
  2045. return -1;
  2046. }
  2047. then.tm_mon -= 1;
  2048. then.tm_year -= 1900;
  2049. return mktime(&then);
  2050. }
  2051. static NOINLINE var *exec_builtin(node *op, var *res)
  2052. {
  2053. #define tspl (G.exec_builtin__tspl)
  2054. var *tv;
  2055. node *an[4];
  2056. var *av[4];
  2057. const char *as[4];
  2058. regmatch_t pmatch[2];
  2059. regex_t sreg, *re;
  2060. node *spl;
  2061. uint32_t isr, info;
  2062. int nargs;
  2063. time_t tt;
  2064. int i, l, ll, n;
  2065. tv = nvalloc(4);
  2066. isr = info = op->info;
  2067. op = op->l.n;
  2068. av[2] = av[3] = NULL;
  2069. for (i = 0; i < 4 && op; i++) {
  2070. an[i] = nextarg(&op);
  2071. if (isr & 0x09000000)
  2072. av[i] = evaluate(an[i], &tv[i]);
  2073. if (isr & 0x08000000)
  2074. as[i] = getvar_s(av[i]);
  2075. isr >>= 1;
  2076. }
  2077. nargs = i;
  2078. if ((uint32_t)nargs < (info >> 30))
  2079. syntax_error(EMSG_TOO_FEW_ARGS);
  2080. info &= OPNMASK;
  2081. switch (info) {
  2082. case B_a2:
  2083. if (ENABLE_FEATURE_AWK_LIBM)
  2084. setvar_i(res, atan2(getvar_i(av[0]), getvar_i(av[1])));
  2085. else
  2086. syntax_error(EMSG_NO_MATH);
  2087. break;
  2088. case B_sp: {
  2089. char *s, *s1;
  2090. if (nargs > 2) {
  2091. spl = (an[2]->info & OPCLSMASK) == OC_REGEXP ?
  2092. an[2] : mk_splitter(getvar_s(evaluate(an[2], &tv[2])), &tspl);
  2093. } else {
  2094. spl = &fsplitter.n;
  2095. }
  2096. n = awk_split(as[0], spl, &s);
  2097. s1 = s;
  2098. clear_array(iamarray(av[1]));
  2099. for (i = 1; i <= n; i++)
  2100. setari_u(av[1], i, nextword(&s));
  2101. free(s1);
  2102. setvar_i(res, n);
  2103. break;
  2104. }
  2105. case B_ss: {
  2106. char *s;
  2107. l = strlen(as[0]);
  2108. i = getvar_i(av[1]) - 1;
  2109. if (i > l)
  2110. i = l;
  2111. if (i < 0)
  2112. i = 0;
  2113. n = (nargs > 2) ? getvar_i(av[2]) : l-i;
  2114. if (n < 0)
  2115. n = 0;
  2116. s = xstrndup(as[0]+i, n);
  2117. setvar_p(res, s);
  2118. break;
  2119. }
  2120. /* Bitwise ops must assume that operands are unsigned. GNU Awk 3.1.5:
  2121. * awk '{ print or(-1,1) }' gives "4.29497e+09", not "-2.xxxe+09" */
  2122. case B_an:
  2123. setvar_i(res, getvar_i_int(av[0]) & getvar_i_int(av[1]));
  2124. break;
  2125. case B_co:
  2126. setvar_i(res, ~getvar_i_int(av[0]));
  2127. break;
  2128. case B_ls:
  2129. setvar_i(res, getvar_i_int(av[0]) << getvar_i_int(av[1]));
  2130. break;
  2131. case B_or:
  2132. setvar_i(res, getvar_i_int(av[0]) | getvar_i_int(av[1]));
  2133. break;
  2134. case B_rs:
  2135. setvar_i(res, getvar_i_int(av[0]) >> getvar_i_int(av[1]));
  2136. break;
  2137. case B_xo:
  2138. setvar_i(res, getvar_i_int(av[0]) ^ getvar_i_int(av[1]));
  2139. break;
  2140. case B_lo:
  2141. case B_up: {
  2142. char *s, *s1;
  2143. s1 = s = xstrdup(as[0]);
  2144. while (*s1) {
  2145. //*s1 = (info == B_up) ? toupper(*s1) : tolower(*s1);
  2146. if ((unsigned char)((*s1 | 0x20) - 'a') <= ('z' - 'a'))
  2147. *s1 = (info == B_up) ? (*s1 & 0xdf) : (*s1 | 0x20);
  2148. s1++;
  2149. }
  2150. setvar_p(res, s);
  2151. break;
  2152. }
  2153. case B_ix:
  2154. n = 0;
  2155. ll = strlen(as[1]);
  2156. l = strlen(as[0]) - ll;
  2157. if (ll > 0 && l >= 0) {
  2158. if (!icase) {
  2159. char *s = strstr(as[0], as[1]);
  2160. if (s)
  2161. n = (s - as[0]) + 1;
  2162. } else {
  2163. /* this piece of code is terribly slow and
  2164. * really should be rewritten
  2165. */
  2166. for (i = 0; i <= l; i++) {
  2167. if (strncasecmp(as[0]+i, as[1], ll) == 0) {
  2168. n = i+1;
  2169. break;
  2170. }
  2171. }
  2172. }
  2173. }
  2174. setvar_i(res, n);
  2175. break;
  2176. case B_ti:
  2177. if (nargs > 1)
  2178. tt = getvar_i(av[1]);
  2179. else
  2180. time(&tt);
  2181. //s = (nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y";
  2182. i = strftime(g_buf, MAXVARFMT,
  2183. ((nargs > 0) ? as[0] : "%a %b %d %H:%M:%S %Z %Y"),
  2184. localtime(&tt));
  2185. g_buf[i] = '\0';
  2186. setvar_s(res, g_buf);
  2187. break;
  2188. case B_mt:
  2189. setvar_i(res, do_mktime(as[0]));
  2190. break;
  2191. case B_ma:
  2192. re = as_regex(an[1], &sreg);
  2193. n = regexec(re, as[0], 1, pmatch, 0);
  2194. if (n == 0) {
  2195. pmatch[0].rm_so++;
  2196. pmatch[0].rm_eo++;
  2197. } else {
  2198. pmatch[0].rm_so = 0;
  2199. pmatch[0].rm_eo = -1;
  2200. }
  2201. setvar_i(newvar("RSTART"), pmatch[0].rm_so);
  2202. setvar_i(newvar("RLENGTH"), pmatch[0].rm_eo - pmatch[0].rm_so);
  2203. setvar_i(res, pmatch[0].rm_so);
  2204. if (re == &sreg)
  2205. regfree(re);
  2206. break;
  2207. case B_ge:
  2208. awk_sub(an[0], as[1], getvar_i(av[2]), av[3], res, TRUE);
  2209. break;
  2210. case B_gs:
  2211. setvar_i(res, awk_sub(an[0], as[1], 0, av[2], av[2], FALSE));
  2212. break;
  2213. case B_su:
  2214. setvar_i(res, awk_sub(an[0], as[1], 1, av[2], av[2], FALSE));
  2215. break;
  2216. }
  2217. nvfree(tv);
  2218. return res;
  2219. #undef tspl
  2220. }
  2221. /*
  2222. * Evaluate node - the heart of the program. Supplied with subtree
  2223. * and place where to store result. returns ptr to result.
  2224. */
  2225. #define XC(n) ((n) >> 8)
  2226. static var *evaluate(node *op, var *res)
  2227. {
  2228. /* This procedure is recursive so we should count every byte */
  2229. #define fnargs (G.evaluate__fnargs)
  2230. /* seed is initialized to 1 */
  2231. #define seed (G.evaluate__seed)
  2232. #define sreg (G.evaluate__sreg)
  2233. var *v1;
  2234. if (!op)
  2235. return setvar_s(res, NULL);
  2236. debug_printf_eval("entered %s()\n", __func__);
  2237. v1 = nvalloc(2);
  2238. while (op) {
  2239. struct {
  2240. var *v;
  2241. const char *s;
  2242. } L = L; /* for compiler */
  2243. struct {
  2244. var *v;
  2245. const char *s;
  2246. } R = R;
  2247. double L_d = L_d;
  2248. uint32_t opinfo;
  2249. int opn;
  2250. node *op1;
  2251. opinfo = op->info;
  2252. opn = (opinfo & OPNMASK);
  2253. g_lineno = op->lineno;
  2254. op1 = op->l.n;
  2255. debug_printf_eval("opinfo:%08x opn:%08x\n", opinfo, opn);
  2256. /* "delete" is special:
  2257. * "delete array[var--]" must evaluate index expr only once,
  2258. * must not evaluate it in "execute inevitable things" part.
  2259. */
  2260. if (XC(opinfo & OPCLSMASK) == XC(OC_DELETE)) {
  2261. uint32_t info = op1->info & OPCLSMASK;
  2262. var *v;
  2263. debug_printf_eval("DELETE\n");
  2264. if (info == OC_VAR) {
  2265. v = op1->l.v;
  2266. } else if (info == OC_FNARG) {
  2267. v = &fnargs[op1->l.aidx];
  2268. } else {
  2269. syntax_error(EMSG_NOT_ARRAY);
  2270. }
  2271. if (op1->r.n) { /* array ref? */
  2272. const char *s;
  2273. s = getvar_s(evaluate(op1->r.n, v1));
  2274. hash_remove(iamarray(v), s);
  2275. } else {
  2276. clear_array(iamarray(v));
  2277. }
  2278. goto next;
  2279. }
  2280. /* execute inevitable things */
  2281. if (opinfo & OF_RES1)
  2282. L.v = evaluate(op1, v1);
  2283. if (opinfo & OF_RES2)
  2284. R.v = evaluate(op->r.n, v1+1);
  2285. if (opinfo & OF_STR1) {
  2286. L.s = getvar_s(L.v);
  2287. debug_printf_eval("L.s:'%s'\n", L.s);
  2288. }
  2289. if (opinfo & OF_STR2) {
  2290. R.s = getvar_s(R.v);
  2291. debug_printf_eval("R.s:'%s'\n", R.s);
  2292. }
  2293. if (opinfo & OF_NUM1) {
  2294. L_d = getvar_i(L.v);
  2295. debug_printf_eval("L_d:%f\n", L_d);
  2296. }
  2297. debug_printf_eval("switch(0x%x)\n", XC(opinfo & OPCLSMASK));
  2298. switch (XC(opinfo & OPCLSMASK)) {
  2299. /* -- iterative node type -- */
  2300. /* test pattern */
  2301. case XC( OC_TEST ):
  2302. if ((op1->info & OPCLSMASK) == OC_COMMA) {
  2303. /* it's range pattern */
  2304. if ((opinfo & OF_CHECKED) || ptest(op1->l.n)) {
  2305. op->info |= OF_CHECKED;
  2306. if (ptest(op1->r.n))
  2307. op->info &= ~OF_CHECKED;
  2308. op = op->a.n;
  2309. } else {
  2310. op = op->r.n;
  2311. }
  2312. } else {
  2313. op = ptest(op1) ? op->a.n : op->r.n;
  2314. }
  2315. break;
  2316. /* just evaluate an expression, also used as unconditional jump */
  2317. case XC( OC_EXEC ):
  2318. break;
  2319. /* branch, used in if-else and various loops */
  2320. case XC( OC_BR ):
  2321. op = istrue(L.v) ? op->a.n : op->r.n;
  2322. break;
  2323. /* initialize for-in loop */
  2324. case XC( OC_WALKINIT ):
  2325. hashwalk_init(L.v, iamarray(R.v));
  2326. break;
  2327. /* get next array item */
  2328. case XC( OC_WALKNEXT ):
  2329. op = hashwalk_next(L.v) ? op->a.n : op->r.n;
  2330. break;
  2331. case XC( OC_PRINT ):
  2332. case XC( OC_PRINTF ): {
  2333. FILE *F = stdout;
  2334. if (op->r.n) {
  2335. rstream *rsm = newfile(R.s);
  2336. if (!rsm->F) {
  2337. if (opn == '|') {
  2338. rsm->F = popen(R.s, "w");
  2339. if (rsm->F == NULL)
  2340. bb_simple_perror_msg_and_die("popen");
  2341. rsm->is_pipe = 1;
  2342. } else {
  2343. rsm->F = xfopen(R.s, opn=='w' ? "w" : "a");
  2344. }
  2345. }
  2346. F = rsm->F;
  2347. }
  2348. if ((opinfo & OPCLSMASK) == OC_PRINT) {
  2349. if (!op1) {
  2350. fputs(getvar_s(intvar[F0]), F);
  2351. } else {
  2352. while (op1) {
  2353. var *v = evaluate(nextarg(&op1), v1);
  2354. if (v->type & VF_NUMBER) {
  2355. fmt_num(g_buf, MAXVARFMT, getvar_s(intvar[OFMT]),
  2356. getvar_i(v), TRUE);
  2357. fputs(g_buf, F);
  2358. } else {
  2359. fputs(getvar_s(v), F);
  2360. }
  2361. if (op1)
  2362. fputs(getvar_s(intvar[OFS]), F);
  2363. }
  2364. }
  2365. fputs(getvar_s(intvar[ORS]), F);
  2366. } else { /* OC_PRINTF */
  2367. char *s = awk_printf(op1);
  2368. fputs(s, F);
  2369. free(s);
  2370. }
  2371. fflush(F);
  2372. break;
  2373. }
  2374. /* case XC( OC_DELETE ): - moved to happen before arg evaluation */
  2375. case XC( OC_NEWSOURCE ):
  2376. g_progname = op->l.new_progname;
  2377. break;
  2378. case XC( OC_RETURN ):
  2379. copyvar(res, L.v);
  2380. break;
  2381. case XC( OC_NEXTFILE ):
  2382. nextfile = TRUE;
  2383. case XC( OC_NEXT ):
  2384. nextrec = TRUE;
  2385. case XC( OC_DONE ):
  2386. clrvar(res);
  2387. break;
  2388. case XC( OC_EXIT ):
  2389. awk_exit(L_d);
  2390. /* -- recursive node type -- */
  2391. case XC( OC_VAR ):
  2392. debug_printf_eval("VAR\n");
  2393. L.v = op->l.v;
  2394. if (L.v == intvar[NF])
  2395. split_f0();
  2396. goto v_cont;
  2397. case XC( OC_FNARG ):
  2398. debug_printf_eval("FNARG[%d]\n", op->l.aidx);
  2399. L.v = &fnargs[op->l.aidx];
  2400. v_cont:
  2401. res = op->r.n ? findvar(iamarray(L.v), R.s) : L.v;
  2402. break;
  2403. case XC( OC_IN ):
  2404. setvar_i(res, hash_search(iamarray(R.v), L.s) ? 1 : 0);
  2405. break;
  2406. case XC( OC_REGEXP ):
  2407. op1 = op;
  2408. L.s = getvar_s(intvar[F0]);
  2409. goto re_cont;
  2410. case XC( OC_MATCH ):
  2411. op1 = op->r.n;
  2412. re_cont:
  2413. {
  2414. regex_t *re = as_regex(op1, &sreg);
  2415. int i = regexec(re, L.s, 0, NULL, 0);
  2416. if (re == &sreg)
  2417. regfree(re);
  2418. setvar_i(res, (i == 0) ^ (opn == '!'));
  2419. }
  2420. break;
  2421. case XC( OC_MOVE ):
  2422. debug_printf_eval("MOVE\n");
  2423. /* if source is a temporary string, jusk relink it to dest */
  2424. //Disabled: if R.v is numeric but happens to have cached R.v->string,
  2425. //then L.v ends up being a string, which is wrong
  2426. // if (R.v == v1+1 && R.v->string) {
  2427. // res = setvar_p(L.v, R.v->string);
  2428. // R.v->string = NULL;
  2429. // } else {
  2430. res = copyvar(L.v, R.v);
  2431. // }
  2432. break;
  2433. case XC( OC_TERNARY ):
  2434. if ((op->r.n->info & OPCLSMASK) != OC_COLON)
  2435. syntax_error(EMSG_POSSIBLE_ERROR);
  2436. res = evaluate(istrue(L.v) ? op->r.n->l.n : op->r.n->r.n, res);
  2437. break;
  2438. case XC( OC_FUNC ): {
  2439. var *vbeg, *v;
  2440. const char *sv_progname;
  2441. /* The body might be empty, still has to eval the args */
  2442. if (!op->r.n->info && !op->r.f->body.first)
  2443. syntax_error(EMSG_UNDEF_FUNC);
  2444. vbeg = v = nvalloc(op->r.f->nargs + 1);
  2445. while (op1) {
  2446. var *arg = evaluate(nextarg(&op1), v1);
  2447. copyvar(v, arg);
  2448. v->type |= VF_CHILD;
  2449. v->x.parent = arg;
  2450. if (++v - vbeg >= op->r.f->nargs)
  2451. break;
  2452. }
  2453. v = fnargs;
  2454. fnargs = vbeg;
  2455. sv_progname = g_progname;
  2456. res = evaluate(op->r.f->body.first, res);
  2457. g_progname = sv_progname;
  2458. nvfree(fnargs);
  2459. fnargs = v;
  2460. break;
  2461. }
  2462. case XC( OC_GETLINE ):
  2463. case XC( OC_PGETLINE ): {
  2464. rstream *rsm;
  2465. int i;
  2466. if (op1) {
  2467. rsm = newfile(L.s);
  2468. if (!rsm->F) {
  2469. if ((opinfo & OPCLSMASK) == OC_PGETLINE) {
  2470. rsm->F = popen(L.s, "r");
  2471. rsm->is_pipe = TRUE;
  2472. } else {
  2473. rsm->F = fopen_for_read(L.s); /* not xfopen! */
  2474. }
  2475. }
  2476. } else {
  2477. if (!iF)
  2478. iF = next_input_file();
  2479. rsm = iF;
  2480. }
  2481. if (!rsm || !rsm->F) {
  2482. setvar_i(intvar[ERRNO], errno);
  2483. setvar_i(res, -1);
  2484. break;
  2485. }
  2486. if (!op->r.n)
  2487. R.v = intvar[F0];
  2488. i = awk_getline(rsm, R.v);
  2489. if (i > 0 && !op1) {
  2490. incvar(intvar[FNR]);
  2491. incvar(intvar[NR]);
  2492. }
  2493. setvar_i(res, i);
  2494. break;
  2495. }
  2496. /* simple builtins */
  2497. case XC( OC_FBLTIN ): {
  2498. double R_d = R_d; /* for compiler */
  2499. switch (opn) {
  2500. case F_in:
  2501. R_d = (long long)L_d;
  2502. break;
  2503. case F_rn:
  2504. R_d = (double)rand() / (double)RAND_MAX;
  2505. break;
  2506. case F_co:
  2507. if (ENABLE_FEATURE_AWK_LIBM) {
  2508. R_d = cos(L_d);
  2509. break;
  2510. }
  2511. case F_ex:
  2512. if (ENABLE_FEATURE_AWK_LIBM) {
  2513. R_d = exp(L_d);
  2514. break;
  2515. }
  2516. case F_lg:
  2517. if (ENABLE_FEATURE_AWK_LIBM) {
  2518. R_d = log(L_d);
  2519. break;
  2520. }
  2521. case F_si:
  2522. if (ENABLE_FEATURE_AWK_LIBM) {
  2523. R_d = sin(L_d);
  2524. break;
  2525. }
  2526. case F_sq:
  2527. if (ENABLE_FEATURE_AWK_LIBM) {
  2528. R_d = sqrt(L_d);
  2529. break;
  2530. }
  2531. syntax_error(EMSG_NO_MATH);
  2532. break;
  2533. case F_sr:
  2534. R_d = (double)seed;
  2535. seed = op1 ? (unsigned)L_d : (unsigned)time(NULL);
  2536. srand(seed);
  2537. break;
  2538. case F_ti:
  2539. R_d = time(NULL);
  2540. break;
  2541. case F_le:
  2542. debug_printf_eval("length: L.s:'%s'\n", L.s);
  2543. if (!op1) {
  2544. L.s = getvar_s(intvar[F0]);
  2545. debug_printf_eval("length: L.s='%s'\n", L.s);
  2546. }
  2547. else if (L.v->type & VF_ARRAY) {
  2548. R_d = L.v->x.array->nel;
  2549. debug_printf_eval("length: array_len:%d\n", L.v->x.array->nel);
  2550. break;
  2551. }
  2552. R_d = strlen(L.s);
  2553. break;
  2554. case F_sy:
  2555. fflush_all();
  2556. R_d = (ENABLE_FEATURE_ALLOW_EXEC && L.s && *L.s)
  2557. ? (system(L.s) >> 8) : 0;
  2558. break;
  2559. case F_ff:
  2560. if (!op1) {
  2561. fflush(stdout);
  2562. } else if (L.s && *L.s) {
  2563. rstream *rsm = newfile(L.s);
  2564. fflush(rsm->F);
  2565. } else {
  2566. fflush_all();
  2567. }
  2568. break;
  2569. case F_cl: {
  2570. rstream *rsm;
  2571. int err = 0;
  2572. rsm = (rstream *)hash_search(fdhash, L.s);
  2573. debug_printf_eval("OC_FBLTIN F_cl rsm:%p\n", rsm);
  2574. if (rsm) {
  2575. debug_printf_eval("OC_FBLTIN F_cl "
  2576. "rsm->is_pipe:%d, ->F:%p\n",
  2577. rsm->is_pipe, rsm->F);
  2578. /* Can be NULL if open failed. Example:
  2579. * getline line <"doesnt_exist";
  2580. * close("doesnt_exist"); <--- here rsm->F is NULL
  2581. */
  2582. if (rsm->F)
  2583. err = rsm->is_pipe ? pclose(rsm->F) : fclose(rsm->F);
  2584. free(rsm->buffer);
  2585. hash_remove(fdhash, L.s);
  2586. }
  2587. if (err)
  2588. setvar_i(intvar[ERRNO], errno);
  2589. R_d = (double)err;
  2590. break;
  2591. }
  2592. } /* switch */
  2593. setvar_i(res, R_d);
  2594. break;
  2595. }
  2596. case XC( OC_BUILTIN ):
  2597. res = exec_builtin(op, res);
  2598. break;
  2599. case XC( OC_SPRINTF ):
  2600. setvar_p(res, awk_printf(op1));
  2601. break;
  2602. case XC( OC_UNARY ): {
  2603. double Ld, R_d;
  2604. Ld = R_d = getvar_i(R.v);
  2605. switch (opn) {
  2606. case 'P':
  2607. Ld = ++R_d;
  2608. goto r_op_change;
  2609. case 'p':
  2610. R_d++;
  2611. goto r_op_change;
  2612. case 'M':
  2613. Ld = --R_d;
  2614. goto r_op_change;
  2615. case 'm':
  2616. R_d--;
  2617. r_op_change:
  2618. setvar_i(R.v, R_d);
  2619. break;
  2620. case '!':
  2621. Ld = !istrue(R.v);
  2622. break;
  2623. case '-':
  2624. Ld = -R_d;
  2625. break;
  2626. }
  2627. setvar_i(res, Ld);
  2628. break;
  2629. }
  2630. case XC( OC_FIELD ): {
  2631. int i = (int)getvar_i(R.v);
  2632. if (i < 0)
  2633. syntax_error(EMSG_NEGATIVE_FIELD);
  2634. if (i == 0) {
  2635. res = intvar[F0];
  2636. } else {
  2637. split_f0();
  2638. if (i > nfields)
  2639. fsrealloc(i);
  2640. res = &Fields[i - 1];
  2641. }
  2642. break;
  2643. }
  2644. /* concatenation (" ") and index joining (",") */
  2645. case XC( OC_CONCAT ):
  2646. case XC( OC_COMMA ): {
  2647. const char *sep = "";
  2648. if ((opinfo & OPCLSMASK) == OC_COMMA)
  2649. sep = getvar_s(intvar[SUBSEP]);
  2650. setvar_p(res, xasprintf("%s%s%s", L.s, sep, R.s));
  2651. break;
  2652. }
  2653. case XC( OC_LAND ):
  2654. setvar_i(res, istrue(L.v) ? ptest(op->r.n) : 0);
  2655. break;
  2656. case XC( OC_LOR ):
  2657. setvar_i(res, istrue(L.v) ? 1 : ptest(op->r.n));
  2658. break;
  2659. case XC( OC_BINARY ):
  2660. case XC( OC_REPLACE ): {
  2661. double R_d = getvar_i(R.v);
  2662. debug_printf_eval("BINARY/REPLACE: R_d:%f opn:%c\n", R_d, opn);
  2663. switch (opn) {
  2664. case '+':
  2665. L_d += R_d;
  2666. break;
  2667. case '-':
  2668. L_d -= R_d;
  2669. break;
  2670. case '*':
  2671. L_d *= R_d;
  2672. break;
  2673. case '/':
  2674. if (R_d == 0)
  2675. syntax_error(EMSG_DIV_BY_ZERO);
  2676. L_d /= R_d;
  2677. break;
  2678. case '&':
  2679. if (ENABLE_FEATURE_AWK_LIBM)
  2680. L_d = pow(L_d, R_d);
  2681. else
  2682. syntax_error(EMSG_NO_MATH);
  2683. break;
  2684. case '%':
  2685. if (R_d == 0)
  2686. syntax_error(EMSG_DIV_BY_ZERO);
  2687. L_d -= (long long)(L_d / R_d) * R_d;
  2688. break;
  2689. }
  2690. debug_printf_eval("BINARY/REPLACE result:%f\n", L_d);
  2691. res = setvar_i(((opinfo & OPCLSMASK) == OC_BINARY) ? res : L.v, L_d);
  2692. break;
  2693. }
  2694. case XC( OC_COMPARE ): {
  2695. int i = i; /* for compiler */
  2696. double Ld;
  2697. if (is_numeric(L.v) && is_numeric(R.v)) {
  2698. Ld = getvar_i(L.v) - getvar_i(R.v);
  2699. } else {
  2700. const char *l = getvar_s(L.v);
  2701. const char *r = getvar_s(R.v);
  2702. Ld = icase ? strcasecmp(l, r) : strcmp(l, r);
  2703. }
  2704. switch (opn & 0xfe) {
  2705. case 0:
  2706. i = (Ld > 0);
  2707. break;
  2708. case 2:
  2709. i = (Ld >= 0);
  2710. break;
  2711. case 4:
  2712. i = (Ld == 0);
  2713. break;
  2714. }
  2715. setvar_i(res, (i == 0) ^ (opn & 1));
  2716. break;
  2717. }
  2718. default:
  2719. syntax_error(EMSG_POSSIBLE_ERROR);
  2720. } /* switch */
  2721. next:
  2722. if ((opinfo & OPCLSMASK) <= SHIFT_TIL_THIS)
  2723. op = op->a.n;
  2724. if ((opinfo & OPCLSMASK) >= RECUR_FROM_THIS)
  2725. break;
  2726. if (nextrec)
  2727. break;
  2728. } /* while (op) */
  2729. nvfree(v1);
  2730. debug_printf_eval("returning from %s(): %p\n", __func__, res);
  2731. return res;
  2732. #undef fnargs
  2733. #undef seed
  2734. #undef sreg
  2735. }
  2736. /* -------- main & co. -------- */
  2737. static int awk_exit(int r)
  2738. {
  2739. var tv;
  2740. unsigned i;
  2741. hash_item *hi;
  2742. zero_out_var(&tv);
  2743. if (!exiting) {
  2744. exiting = TRUE;
  2745. nextrec = FALSE;
  2746. evaluate(endseq.first, &tv);
  2747. }
  2748. /* waiting for children */
  2749. for (i = 0; i < fdhash->csize; i++) {
  2750. hi = fdhash->items[i];
  2751. while (hi) {
  2752. if (hi->data.rs.F && hi->data.rs.is_pipe)
  2753. pclose(hi->data.rs.F);
  2754. hi = hi->next;
  2755. }
  2756. }
  2757. exit(r);
  2758. }
  2759. /* if expr looks like "var=value", perform assignment and return 1,
  2760. * otherwise return 0 */
  2761. static int is_assignment(const char *expr)
  2762. {
  2763. char *exprc, *val;
  2764. if (!isalnum_(*expr) || (val = strchr(expr, '=')) == NULL) {
  2765. return FALSE;
  2766. }
  2767. exprc = xstrdup(expr);
  2768. val = exprc + (val - expr);
  2769. *val++ = '\0';
  2770. unescape_string_in_place(val);
  2771. setvar_u(newvar(exprc), val);
  2772. free(exprc);
  2773. return TRUE;
  2774. }
  2775. /* switch to next input file */
  2776. static rstream *next_input_file(void)
  2777. {
  2778. #define rsm (G.next_input_file__rsm)
  2779. #define files_happen (G.next_input_file__files_happen)
  2780. FILE *F;
  2781. const char *fname, *ind;
  2782. if (rsm.F)
  2783. fclose(rsm.F);
  2784. rsm.F = NULL;
  2785. rsm.pos = rsm.adv = 0;
  2786. for (;;) {
  2787. if (getvar_i(intvar[ARGIND])+1 >= getvar_i(intvar[ARGC])) {
  2788. if (files_happen)
  2789. return NULL;
  2790. fname = "-";
  2791. F = stdin;
  2792. break;
  2793. }
  2794. ind = getvar_s(incvar(intvar[ARGIND]));
  2795. fname = getvar_s(findvar(iamarray(intvar[ARGV]), ind));
  2796. if (fname && *fname && !is_assignment(fname)) {
  2797. F = xfopen_stdin(fname);
  2798. break;
  2799. }
  2800. }
  2801. files_happen = TRUE;
  2802. setvar_s(intvar[FILENAME], fname);
  2803. rsm.F = F;
  2804. return &rsm;
  2805. #undef rsm
  2806. #undef files_happen
  2807. }
  2808. int awk_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  2809. int awk_main(int argc UNUSED_PARAM, char **argv)
  2810. {
  2811. unsigned opt;
  2812. char *opt_F;
  2813. llist_t *list_v = NULL;
  2814. llist_t *list_f = NULL;
  2815. #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  2816. llist_t *list_e = NULL;
  2817. #endif
  2818. int i, j;
  2819. var *v;
  2820. var tv;
  2821. char **envp;
  2822. char *vnames = (char *)vNames; /* cheat */
  2823. char *vvalues = (char *)vValues;
  2824. INIT_G();
  2825. /* Undo busybox.c, or else strtod may eat ','! This breaks parsing:
  2826. * $1,$2 == '$1,' '$2', NOT '$1' ',' '$2' */
  2827. if (ENABLE_LOCALE_SUPPORT)
  2828. setlocale(LC_NUMERIC, "C");
  2829. zero_out_var(&tv);
  2830. /* allocate global buffer */
  2831. g_buf = xmalloc(MAXVARFMT + 1);
  2832. vhash = hash_init();
  2833. ahash = hash_init();
  2834. fdhash = hash_init();
  2835. fnhash = hash_init();
  2836. /* initialize variables */
  2837. for (i = 0; *vnames; i++) {
  2838. intvar[i] = v = newvar(nextword(&vnames));
  2839. if (*vvalues != '\377')
  2840. setvar_s(v, nextword(&vvalues));
  2841. else
  2842. setvar_i(v, 0);
  2843. if (*vnames == '*') {
  2844. v->type |= VF_SPECIAL;
  2845. vnames++;
  2846. }
  2847. }
  2848. handle_special(intvar[FS]);
  2849. handle_special(intvar[RS]);
  2850. newfile("/dev/stdin")->F = stdin;
  2851. newfile("/dev/stdout")->F = stdout;
  2852. newfile("/dev/stderr")->F = stderr;
  2853. /* Huh, people report that sometimes environ is NULL. Oh well. */
  2854. if (environ) for (envp = environ; *envp; envp++) {
  2855. /* environ is writable, thus we don't strdup it needlessly */
  2856. char *s = *envp;
  2857. char *s1 = strchr(s, '=');
  2858. if (s1) {
  2859. *s1 = '\0';
  2860. /* Both findvar and setvar_u take const char*
  2861. * as 2nd arg -> environment is not trashed */
  2862. setvar_u(findvar(iamarray(intvar[ENVIRON]), s), s1 + 1);
  2863. *s1 = '=';
  2864. }
  2865. }
  2866. opt = getopt32(argv, OPTSTR_AWK, &opt_F, &list_v, &list_f, IF_FEATURE_AWK_GNU_EXTENSIONS(&list_e,) NULL);
  2867. argv += optind;
  2868. //argc -= optind;
  2869. if (opt & OPT_W)
  2870. bb_simple_error_msg("warning: option -W is ignored");
  2871. if (opt & OPT_F) {
  2872. unescape_string_in_place(opt_F);
  2873. setvar_s(intvar[FS], opt_F);
  2874. }
  2875. while (list_v) {
  2876. if (!is_assignment(llist_pop(&list_v)))
  2877. bb_show_usage();
  2878. }
  2879. while (list_f) {
  2880. char *s = NULL;
  2881. FILE *from_file;
  2882. g_progname = llist_pop(&list_f);
  2883. from_file = xfopen_stdin(g_progname);
  2884. /* one byte is reserved for some trick in next_token */
  2885. for (i = j = 1; j > 0; i += j) {
  2886. s = xrealloc(s, i + 4096);
  2887. j = fread(s + i, 1, 4094, from_file);
  2888. }
  2889. s[i] = '\0';
  2890. fclose(from_file);
  2891. parse_program(s + 1);
  2892. free(s);
  2893. }
  2894. g_progname = "cmd. line";
  2895. #if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
  2896. while (list_e) {
  2897. parse_program(llist_pop(&list_e));
  2898. }
  2899. #endif
  2900. if (!(opt & (OPT_f | OPT_e))) {
  2901. if (!*argv)
  2902. bb_show_usage();
  2903. parse_program(*argv++);
  2904. }
  2905. /* fill in ARGV array */
  2906. setari_u(intvar[ARGV], 0, "awk");
  2907. i = 0;
  2908. while (*argv)
  2909. setari_u(intvar[ARGV], ++i, *argv++);
  2910. setvar_i(intvar[ARGC], i + 1);
  2911. evaluate(beginseq.first, &tv);
  2912. if (!mainseq.first && !endseq.first)
  2913. awk_exit(EXIT_SUCCESS);
  2914. /* input file could already be opened in BEGIN block */
  2915. if (!iF)
  2916. iF = next_input_file();
  2917. /* passing through input files */
  2918. while (iF) {
  2919. nextfile = FALSE;
  2920. setvar_i(intvar[FNR], 0);
  2921. while ((i = awk_getline(iF, intvar[F0])) > 0) {
  2922. nextrec = FALSE;
  2923. incvar(intvar[NR]);
  2924. incvar(intvar[FNR]);
  2925. evaluate(mainseq.first, &tv);
  2926. if (nextfile)
  2927. break;
  2928. }
  2929. if (i < 0)
  2930. syntax_error(strerror(errno));
  2931. iF = next_input_file();
  2932. }
  2933. awk_exit(EXIT_SUCCESS);
  2934. /*return 0;*/
  2935. }