3
0

awk.c 64 KB

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