awk.c 67 KB

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