awk.c 69 KB

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