cli_hush.c 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * sh.c -- a prototype Bourne shell grammar parser
  4. * Intended to follow the original Thompson and Ritchie
  5. * "small and simple is beautiful" philosophy, which
  6. * incidentally is a good match to today's BusyBox.
  7. *
  8. * Copyright (C) 2000,2001 Larry Doolittle <larry@doolittle.boa.org>
  9. *
  10. * Credits:
  11. * The parser routines proper are all original material, first
  12. * written Dec 2000 and Jan 2001 by Larry Doolittle.
  13. * The execution engine, the builtins, and much of the underlying
  14. * support has been adapted from busybox-0.49pre's lash,
  15. * which is Copyright (C) 2000 by Lineo, Inc., and
  16. * written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>.
  17. * That, in turn, is based in part on ladsh.c, by Michael K. Johnson and
  18. * Erik W. Troan, which they placed in the public domain. I don't know
  19. * how much of the Johnson/Troan code has survived the repeated rewrites.
  20. * Other credits:
  21. * b_addchr() derived from similar w_addchar function in glibc-2.2
  22. * setup_redirect(), redirect_opt_num(), and big chunks of main()
  23. * and many builtins derived from contributions by Erik Andersen
  24. * miscellaneous bugfixes from Matt Kraai
  25. *
  26. * There are two big (and related) architecture differences between
  27. * this parser and the lash parser. One is that this version is
  28. * actually designed from the ground up to understand nearly all
  29. * of the Bourne grammar. The second, consequential change is that
  30. * the parser and input reader have been turned inside out. Now,
  31. * the parser is in control, and asks for input as needed. The old
  32. * way had the input reader in control, and it asked for parsing to
  33. * take place as needed. The new way makes it much easier to properly
  34. * handle the recursion implicit in the various substitutions, especially
  35. * across continuation lines.
  36. *
  37. * Bash grammar not implemented: (how many of these were in original sh?)
  38. * $@ (those sure look like weird quoting rules)
  39. * $_
  40. * ! negation operator for pipes
  41. * &> and >& redirection of stdout+stderr
  42. * Brace Expansion
  43. * Tilde Expansion
  44. * fancy forms of Parameter Expansion
  45. * aliases
  46. * Arithmetic Expansion
  47. * <(list) and >(list) Process Substitution
  48. * reserved words: case, esac, select, function
  49. * Here Documents ( << word )
  50. * Functions
  51. * Major bugs:
  52. * job handling woefully incomplete and buggy
  53. * reserved word execution woefully incomplete and buggy
  54. * to-do:
  55. * port selected bugfixes from post-0.49 busybox lash - done?
  56. * finish implementing reserved words: for, while, until, do, done
  57. * change { and } from special chars to reserved words
  58. * builtins: break, continue, eval, return, set, trap, ulimit
  59. * test magic exec
  60. * handle children going into background
  61. * clean up recognition of null pipes
  62. * check setting of global_argc and global_argv
  63. * control-C handling, probably with longjmp
  64. * follow IFS rules more precisely, including update semantics
  65. * figure out what to do with backslash-newline
  66. * explain why we use signal instead of sigaction
  67. * propagate syntax errors, die on resource errors?
  68. * continuation lines, both explicit and implicit - done?
  69. * memory leak finding and plugging - done?
  70. * more testing, especially quoting rules and redirection
  71. * document how quoting rules not precisely followed for variable assignments
  72. * maybe change map[] to use 2-bit entries
  73. * (eventually) remove all the printf's
  74. */
  75. #define __U_BOOT__
  76. #ifdef __U_BOOT__
  77. #include <common.h> /* readline */
  78. #include <env.h>
  79. #include <malloc.h> /* malloc, free, realloc*/
  80. #include <linux/ctype.h> /* isalpha, isdigit */
  81. #include <console.h>
  82. #include <bootretry.h>
  83. #include <cli.h>
  84. #include <cli_hush.h>
  85. #include <command.h> /* find_cmd */
  86. #include <asm/global_data.h>
  87. #endif
  88. #ifndef __U_BOOT__
  89. #include <ctype.h> /* isalpha, isdigit */
  90. #include <unistd.h> /* getpid */
  91. #include <stdlib.h> /* getenv, atoi */
  92. #include <string.h> /* strchr */
  93. #include <stdio.h> /* popen etc. */
  94. #include <glob.h> /* glob, of course */
  95. #include <stdarg.h> /* va_list */
  96. #include <errno.h>
  97. #include <fcntl.h>
  98. #include <getopt.h> /* should be pretty obvious */
  99. #include <sys/stat.h> /* ulimit */
  100. #include <sys/types.h>
  101. #include <sys/wait.h>
  102. #include <signal.h>
  103. /* #include <dmalloc.h> */
  104. #if 1
  105. #include "busybox.h"
  106. #include "cmdedit.h"
  107. #else
  108. #define applet_name "hush"
  109. #include "standalone.h"
  110. #define hush_main main
  111. #undef CONFIG_FEATURE_SH_FANCY_PROMPT
  112. #define BB_BANNER
  113. #endif
  114. #endif
  115. #define SPECIAL_VAR_SYMBOL 03
  116. #define SUBSTED_VAR_SYMBOL 04
  117. #ifndef __U_BOOT__
  118. #define FLAG_EXIT_FROM_LOOP 1
  119. #define FLAG_PARSE_SEMICOLON (1 << 1) /* symbol ';' is special for parser */
  120. #define FLAG_REPARSING (1 << 2) /* >= 2nd pass */
  121. #endif
  122. #ifdef __U_BOOT__
  123. DECLARE_GLOBAL_DATA_PTR;
  124. #define EXIT_SUCCESS 0
  125. #define EOF -1
  126. #define syntax() syntax_err()
  127. #define xstrdup strdup
  128. #define error_msg printf
  129. #else
  130. typedef enum {
  131. REDIRECT_INPUT = 1,
  132. REDIRECT_OVERWRITE = 2,
  133. REDIRECT_APPEND = 3,
  134. REDIRECT_HEREIS = 4,
  135. REDIRECT_IO = 5
  136. } redir_type;
  137. /* The descrip member of this structure is only used to make debugging
  138. * output pretty */
  139. struct {int mode; int default_fd; char *descrip;} redir_table[] = {
  140. { 0, 0, "()" },
  141. { O_RDONLY, 0, "<" },
  142. { O_CREAT|O_TRUNC|O_WRONLY, 1, ">" },
  143. { O_CREAT|O_APPEND|O_WRONLY, 1, ">>" },
  144. { O_RDONLY, -1, "<<" },
  145. { O_RDWR, 1, "<>" }
  146. };
  147. #endif
  148. typedef enum {
  149. PIPE_SEQ = 1,
  150. PIPE_AND = 2,
  151. PIPE_OR = 3,
  152. PIPE_BG = 4,
  153. } pipe_style;
  154. /* might eventually control execution */
  155. typedef enum {
  156. RES_NONE = 0,
  157. RES_IF = 1,
  158. RES_THEN = 2,
  159. RES_ELIF = 3,
  160. RES_ELSE = 4,
  161. RES_FI = 5,
  162. RES_FOR = 6,
  163. RES_WHILE = 7,
  164. RES_UNTIL = 8,
  165. RES_DO = 9,
  166. RES_DONE = 10,
  167. RES_XXXX = 11,
  168. RES_IN = 12,
  169. RES_SNTX = 13
  170. } reserved_style;
  171. #define FLAG_END (1<<RES_NONE)
  172. #define FLAG_IF (1<<RES_IF)
  173. #define FLAG_THEN (1<<RES_THEN)
  174. #define FLAG_ELIF (1<<RES_ELIF)
  175. #define FLAG_ELSE (1<<RES_ELSE)
  176. #define FLAG_FI (1<<RES_FI)
  177. #define FLAG_FOR (1<<RES_FOR)
  178. #define FLAG_WHILE (1<<RES_WHILE)
  179. #define FLAG_UNTIL (1<<RES_UNTIL)
  180. #define FLAG_DO (1<<RES_DO)
  181. #define FLAG_DONE (1<<RES_DONE)
  182. #define FLAG_IN (1<<RES_IN)
  183. #define FLAG_START (1<<RES_XXXX)
  184. /* This holds pointers to the various results of parsing */
  185. struct p_context {
  186. struct child_prog *child;
  187. struct pipe *list_head;
  188. struct pipe *pipe;
  189. #ifndef __U_BOOT__
  190. struct redir_struct *pending_redirect;
  191. #endif
  192. reserved_style w;
  193. int old_flag; /* for figuring out valid reserved words */
  194. struct p_context *stack;
  195. int type; /* define type of parser : ";$" common or special symbol */
  196. /* How about quoting status? */
  197. };
  198. #ifndef __U_BOOT__
  199. struct redir_struct {
  200. redir_type type; /* type of redirection */
  201. int fd; /* file descriptor being redirected */
  202. int dup; /* -1, or file descriptor being duplicated */
  203. struct redir_struct *next; /* pointer to the next redirect in the list */
  204. glob_t word; /* *word.gl_pathv is the filename */
  205. };
  206. #endif
  207. struct child_prog {
  208. #ifndef __U_BOOT__
  209. pid_t pid; /* 0 if exited */
  210. #endif
  211. char **argv; /* program name and arguments */
  212. /* was quoted when parsed; copy of struct o_string.nonnull field */
  213. int *argv_nonnull;
  214. #ifdef __U_BOOT__
  215. int argc; /* number of program arguments */
  216. #endif
  217. struct pipe *group; /* if non-NULL, first in group or subshell */
  218. #ifndef __U_BOOT__
  219. int subshell; /* flag, non-zero if group must be forked */
  220. struct redir_struct *redirects; /* I/O redirections */
  221. glob_t glob_result; /* result of parameter globbing */
  222. int is_stopped; /* is the program currently running? */
  223. struct pipe *family; /* pointer back to the child's parent pipe */
  224. #endif
  225. int sp; /* number of SPECIAL_VAR_SYMBOL */
  226. int type;
  227. };
  228. struct pipe {
  229. #ifndef __U_BOOT__
  230. int jobid; /* job number */
  231. #endif
  232. int num_progs; /* total number of programs in job */
  233. #ifndef __U_BOOT__
  234. int running_progs; /* number of programs running */
  235. char *text; /* name of job */
  236. char *cmdbuf; /* buffer various argv's point into */
  237. pid_t pgrp; /* process group ID for the job */
  238. #endif
  239. struct child_prog *progs; /* array of commands in pipe */
  240. struct pipe *next; /* to track background commands */
  241. #ifndef __U_BOOT__
  242. int stopped_progs; /* number of programs alive, but stopped */
  243. int job_context; /* bitmask defining current context */
  244. #endif
  245. pipe_style followup; /* PIPE_BG, PIPE_SEQ, PIPE_OR, PIPE_AND */
  246. reserved_style r_mode; /* supports if, for, while, until */
  247. };
  248. #ifndef __U_BOOT__
  249. struct close_me {
  250. int fd;
  251. struct close_me *next;
  252. };
  253. #endif
  254. struct variables {
  255. char *name;
  256. char *value;
  257. int flg_export;
  258. int flg_read_only;
  259. struct variables *next;
  260. };
  261. /* globals, connect us to the outside world
  262. * the first three support $?, $#, and $1 */
  263. #ifndef __U_BOOT__
  264. char **global_argv;
  265. unsigned int global_argc;
  266. #endif
  267. static unsigned int last_return_code;
  268. #ifndef __U_BOOT__
  269. extern char **environ; /* This is in <unistd.h>, but protected with __USE_GNU */
  270. #endif
  271. /* "globals" within this file */
  272. static uchar *ifs;
  273. static char map[256];
  274. #ifndef __U_BOOT__
  275. static int fake_mode;
  276. static int interactive;
  277. static struct close_me *close_me_head;
  278. static const char *cwd;
  279. static struct pipe *job_list;
  280. static unsigned int last_bg_pid;
  281. static unsigned int last_jobid;
  282. static unsigned int shell_terminal;
  283. static char *PS1;
  284. static char *PS2;
  285. struct variables shell_ver = { "HUSH_VERSION", "0.01", 1, 1, 0 };
  286. struct variables *top_vars = &shell_ver;
  287. #else
  288. static int flag_repeat = 0;
  289. static int do_repeat = 0;
  290. static struct variables *top_vars = NULL ;
  291. #endif /*__U_BOOT__ */
  292. #define B_CHUNK (100)
  293. #define B_NOSPAC 1
  294. typedef struct {
  295. char *data;
  296. int length;
  297. int maxlen;
  298. int quote;
  299. int nonnull;
  300. } o_string;
  301. #define NULL_O_STRING {NULL,0,0,0,0}
  302. /* used for initialization:
  303. o_string foo = NULL_O_STRING; */
  304. /* I can almost use ordinary FILE *. Is open_memstream() universally
  305. * available? Where is it documented? */
  306. struct in_str {
  307. const char *p;
  308. #ifndef __U_BOOT__
  309. char peek_buf[2];
  310. #endif
  311. int __promptme;
  312. int promptmode;
  313. #ifndef __U_BOOT__
  314. FILE *file;
  315. #endif
  316. int (*get) (struct in_str *);
  317. int (*peek) (struct in_str *);
  318. };
  319. #define b_getch(input) ((input)->get(input))
  320. #define b_peek(input) ((input)->peek(input))
  321. #ifndef __U_BOOT__
  322. #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
  323. struct built_in_command {
  324. char *cmd; /* name */
  325. char *descr; /* description */
  326. int (*function) (struct child_prog *); /* function ptr */
  327. };
  328. #endif
  329. /* define DEBUG_SHELL for debugging output (obviously ;-)) */
  330. #if 0
  331. #define DEBUG_SHELL
  332. #endif
  333. /* This should be in utility.c */
  334. #ifdef DEBUG_SHELL
  335. #ifndef __U_BOOT__
  336. static void debug_printf(const char *format, ...)
  337. {
  338. va_list args;
  339. va_start(args, format);
  340. vfprintf(stderr, format, args);
  341. va_end(args);
  342. }
  343. #else
  344. #define debug_printf(fmt,args...) printf (fmt ,##args)
  345. #endif
  346. #else
  347. static inline void debug_printf(const char *format, ...) { }
  348. #endif
  349. #define final_printf debug_printf
  350. #ifdef __U_BOOT__
  351. static void syntax_err(void) {
  352. printf("syntax error\n");
  353. }
  354. #else
  355. static void __syntax(char *file, int line) {
  356. error_msg("syntax error %s:%d", file, line);
  357. }
  358. #define syntax() __syntax(__FILE__, __LINE__)
  359. #endif
  360. #ifdef __U_BOOT__
  361. static void *xmalloc(size_t size);
  362. static void *xrealloc(void *ptr, size_t size);
  363. #else
  364. /* Index of subroutines: */
  365. /* function prototypes for builtins */
  366. static int builtin_cd(struct child_prog *child);
  367. static int builtin_env(struct child_prog *child);
  368. static int builtin_eval(struct child_prog *child);
  369. static int builtin_exec(struct child_prog *child);
  370. static int builtin_exit(struct child_prog *child);
  371. static int builtin_export(struct child_prog *child);
  372. static int builtin_fg_bg(struct child_prog *child);
  373. static int builtin_help(struct child_prog *child);
  374. static int builtin_jobs(struct child_prog *child);
  375. static int builtin_pwd(struct child_prog *child);
  376. static int builtin_read(struct child_prog *child);
  377. static int builtin_set(struct child_prog *child);
  378. static int builtin_shift(struct child_prog *child);
  379. static int builtin_source(struct child_prog *child);
  380. static int builtin_umask(struct child_prog *child);
  381. static int builtin_unset(struct child_prog *child);
  382. static int builtin_not_written(struct child_prog *child);
  383. #endif
  384. /* o_string manipulation: */
  385. static int b_check_space(o_string *o, int len);
  386. static int b_addchr(o_string *o, int ch);
  387. static void b_reset(o_string *o);
  388. static int b_addqchr(o_string *o, int ch, int quote);
  389. #ifndef __U_BOOT__
  390. static int b_adduint(o_string *o, unsigned int i);
  391. #endif
  392. /* in_str manipulations: */
  393. static int static_get(struct in_str *i);
  394. static int static_peek(struct in_str *i);
  395. static int file_get(struct in_str *i);
  396. static int file_peek(struct in_str *i);
  397. #ifndef __U_BOOT__
  398. static void setup_file_in_str(struct in_str *i, FILE *f);
  399. #else
  400. static void setup_file_in_str(struct in_str *i);
  401. #endif
  402. static void setup_string_in_str(struct in_str *i, const char *s);
  403. #ifndef __U_BOOT__
  404. /* close_me manipulations: */
  405. static void mark_open(int fd);
  406. static void mark_closed(int fd);
  407. static void close_all(void);
  408. #endif
  409. /* "run" the final data structures: */
  410. static char *indenter(int i);
  411. static int free_pipe_list(struct pipe *head, int indent);
  412. static int free_pipe(struct pipe *pi, int indent);
  413. /* really run the final data structures: */
  414. #ifndef __U_BOOT__
  415. static int setup_redirects(struct child_prog *prog, int squirrel[]);
  416. #endif
  417. static int run_list_real(struct pipe *pi);
  418. #ifndef __U_BOOT__
  419. static void pseudo_exec(struct child_prog *child) __attribute__ ((noreturn));
  420. #endif
  421. static int run_pipe_real(struct pipe *pi);
  422. /* extended glob support: */
  423. #ifndef __U_BOOT__
  424. static int globhack(const char *src, int flags, glob_t *pglob);
  425. static int glob_needed(const char *s);
  426. static int xglob(o_string *dest, int flags, glob_t *pglob);
  427. #endif
  428. /* variable assignment: */
  429. static int is_assignment(const char *s);
  430. /* data structure manipulation: */
  431. #ifndef __U_BOOT__
  432. static int setup_redirect(struct p_context *ctx, int fd, redir_type style, struct in_str *input);
  433. #endif
  434. static void initialize_context(struct p_context *ctx);
  435. static int done_word(o_string *dest, struct p_context *ctx);
  436. static int done_command(struct p_context *ctx);
  437. static int done_pipe(struct p_context *ctx, pipe_style type);
  438. /* primary string parsing: */
  439. #ifndef __U_BOOT__
  440. static int redirect_dup_num(struct in_str *input);
  441. static int redirect_opt_num(o_string *o);
  442. static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end);
  443. static int parse_group(o_string *dest, struct p_context *ctx, struct in_str *input, int ch);
  444. #endif
  445. static char *lookup_param(char *src);
  446. static char *make_string(char **inp, int *nonnull);
  447. static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input);
  448. #ifndef __U_BOOT__
  449. static int parse_string(o_string *dest, struct p_context *ctx, const char *src);
  450. #endif
  451. static int parse_stream(o_string *dest, struct p_context *ctx, struct in_str *input0, int end_trigger);
  452. /* setup: */
  453. static int parse_stream_outer(struct in_str *inp, int flag);
  454. #ifndef __U_BOOT__
  455. static int parse_string_outer(const char *s, int flag);
  456. static int parse_file_outer(FILE *f);
  457. #endif
  458. #ifndef __U_BOOT__
  459. /* job management: */
  460. static int checkjobs(struct pipe* fg_pipe);
  461. static void insert_bg_job(struct pipe *pi);
  462. static void remove_bg_job(struct pipe *pi);
  463. #endif
  464. /* local variable support */
  465. static char **make_list_in(char **inp, char *name);
  466. static char *insert_var_value(char *inp);
  467. static char *insert_var_value_sub(char *inp, int tag_subst);
  468. #ifndef __U_BOOT__
  469. /* Table of built-in functions. They can be forked or not, depending on
  470. * context: within pipes, they fork. As simple commands, they do not.
  471. * When used in non-forking context, they can change global variables
  472. * in the parent shell process. If forked, of course they can not.
  473. * For example, 'unset foo | whatever' will parse and run, but foo will
  474. * still be set at the end. */
  475. static struct built_in_command bltins[] = {
  476. {"bg", "Resume a job in the background", builtin_fg_bg},
  477. {"break", "Exit for, while or until loop", builtin_not_written},
  478. {"cd", "Change working directory", builtin_cd},
  479. {"continue", "Continue for, while or until loop", builtin_not_written},
  480. {"env", "Print all environment variables", builtin_env},
  481. {"eval", "Construct and run shell command", builtin_eval},
  482. {"exec", "Exec command, replacing this shell with the exec'd process",
  483. builtin_exec},
  484. {"exit", "Exit from shell()", builtin_exit},
  485. {"export", "Set environment variable", builtin_export},
  486. {"fg", "Bring job into the foreground", builtin_fg_bg},
  487. {"jobs", "Lists the active jobs", builtin_jobs},
  488. {"pwd", "Print current directory", builtin_pwd},
  489. {"read", "Input environment variable", builtin_read},
  490. {"return", "Return from a function", builtin_not_written},
  491. {"set", "Set/unset shell local variables", builtin_set},
  492. {"shift", "Shift positional parameters", builtin_shift},
  493. {"trap", "Trap signals", builtin_not_written},
  494. {"ulimit","Controls resource limits", builtin_not_written},
  495. {"umask","Sets file creation mask", builtin_umask},
  496. {"unset", "Unset environment variable", builtin_unset},
  497. {".", "Source-in and run commands in a file", builtin_source},
  498. {"help", "List shell built-in commands", builtin_help},
  499. {NULL, NULL, NULL}
  500. };
  501. static const char *set_cwd(void)
  502. {
  503. if(cwd==unknown)
  504. cwd = NULL; /* xgetcwd(arg) called free(arg) */
  505. cwd = xgetcwd((char *)cwd);
  506. if (!cwd)
  507. cwd = unknown;
  508. return cwd;
  509. }
  510. /* built-in 'eval' handler */
  511. static int builtin_eval(struct child_prog *child)
  512. {
  513. char *str = NULL;
  514. int rcode = EXIT_SUCCESS;
  515. if (child->argv[1]) {
  516. str = make_string(child->argv + 1);
  517. parse_string_outer(str, FLAG_EXIT_FROM_LOOP |
  518. FLAG_PARSE_SEMICOLON);
  519. free(str);
  520. rcode = last_return_code;
  521. }
  522. return rcode;
  523. }
  524. /* built-in 'cd <path>' handler */
  525. static int builtin_cd(struct child_prog *child)
  526. {
  527. char *newdir;
  528. if (child->argv[1] == NULL)
  529. newdir = env_get("HOME");
  530. else
  531. newdir = child->argv[1];
  532. if (chdir(newdir)) {
  533. printf("cd: %s: %s\n", newdir, strerror(errno));
  534. return EXIT_FAILURE;
  535. }
  536. set_cwd();
  537. return EXIT_SUCCESS;
  538. }
  539. /* built-in 'env' handler */
  540. static int builtin_env(struct child_prog *dummy)
  541. {
  542. char **e = environ;
  543. if (e == NULL) return EXIT_FAILURE;
  544. for (; *e; e++) {
  545. puts(*e);
  546. }
  547. return EXIT_SUCCESS;
  548. }
  549. /* built-in 'exec' handler */
  550. static int builtin_exec(struct child_prog *child)
  551. {
  552. if (child->argv[1] == NULL)
  553. return EXIT_SUCCESS; /* Really? */
  554. child->argv++;
  555. pseudo_exec(child);
  556. /* never returns */
  557. }
  558. /* built-in 'exit' handler */
  559. static int builtin_exit(struct child_prog *child)
  560. {
  561. if (child->argv[1] == NULL)
  562. exit(last_return_code);
  563. exit (atoi(child->argv[1]));
  564. }
  565. /* built-in 'export VAR=value' handler */
  566. static int builtin_export(struct child_prog *child)
  567. {
  568. int res = 0;
  569. char *name = child->argv[1];
  570. if (name == NULL) {
  571. return (builtin_env(child));
  572. }
  573. name = strdup(name);
  574. if(name) {
  575. char *value = strchr(name, '=');
  576. if (!value) {
  577. char *tmp;
  578. /* They are exporting something without an =VALUE */
  579. value = get_local_var(name);
  580. if (value) {
  581. size_t ln = strlen(name);
  582. tmp = realloc(name, ln+strlen(value)+2);
  583. if(tmp==NULL)
  584. res = -1;
  585. else {
  586. sprintf(tmp+ln, "=%s", value);
  587. name = tmp;
  588. }
  589. } else {
  590. /* bash does not return an error when trying to export
  591. * an undefined variable. Do likewise. */
  592. res = 1;
  593. }
  594. }
  595. }
  596. if (res<0)
  597. perror_msg("export");
  598. else if(res==0)
  599. res = set_local_var(name, 1);
  600. else
  601. res = 0;
  602. free(name);
  603. return res;
  604. }
  605. /* built-in 'fg' and 'bg' handler */
  606. static int builtin_fg_bg(struct child_prog *child)
  607. {
  608. int i, jobnum;
  609. struct pipe *pi=NULL;
  610. if (!interactive)
  611. return EXIT_FAILURE;
  612. /* If they gave us no args, assume they want the last backgrounded task */
  613. if (!child->argv[1]) {
  614. for (pi = job_list; pi; pi = pi->next) {
  615. if (pi->jobid == last_jobid) {
  616. break;
  617. }
  618. }
  619. if (!pi) {
  620. error_msg("%s: no current job", child->argv[0]);
  621. return EXIT_FAILURE;
  622. }
  623. } else {
  624. if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
  625. error_msg("%s: bad argument '%s'", child->argv[0], child->argv[1]);
  626. return EXIT_FAILURE;
  627. }
  628. for (pi = job_list; pi; pi = pi->next) {
  629. if (pi->jobid == jobnum) {
  630. break;
  631. }
  632. }
  633. if (!pi) {
  634. error_msg("%s: %d: no such job", child->argv[0], jobnum);
  635. return EXIT_FAILURE;
  636. }
  637. }
  638. if (*child->argv[0] == 'f') {
  639. /* Put the job into the foreground. */
  640. tcsetpgrp(shell_terminal, pi->pgrp);
  641. }
  642. /* Restart the processes in the job */
  643. for (i = 0; i < pi->num_progs; i++)
  644. pi->progs[i].is_stopped = 0;
  645. if ( (i=kill(- pi->pgrp, SIGCONT)) < 0) {
  646. if (i == ESRCH) {
  647. remove_bg_job(pi);
  648. } else {
  649. perror_msg("kill (SIGCONT)");
  650. }
  651. }
  652. pi->stopped_progs = 0;
  653. return EXIT_SUCCESS;
  654. }
  655. /* built-in 'help' handler */
  656. static int builtin_help(struct child_prog *dummy)
  657. {
  658. struct built_in_command *x;
  659. printf("\nBuilt-in commands:\n");
  660. printf("-------------------\n");
  661. for (x = bltins; x->cmd; x++) {
  662. if (x->descr==NULL)
  663. continue;
  664. printf("%s\t%s\n", x->cmd, x->descr);
  665. }
  666. printf("\n\n");
  667. return EXIT_SUCCESS;
  668. }
  669. /* built-in 'jobs' handler */
  670. static int builtin_jobs(struct child_prog *child)
  671. {
  672. struct pipe *job;
  673. char *status_string;
  674. for (job = job_list; job; job = job->next) {
  675. if (job->running_progs == job->stopped_progs)
  676. status_string = "Stopped";
  677. else
  678. status_string = "Running";
  679. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
  680. }
  681. return EXIT_SUCCESS;
  682. }
  683. /* built-in 'pwd' handler */
  684. static int builtin_pwd(struct child_prog *dummy)
  685. {
  686. puts(set_cwd());
  687. return EXIT_SUCCESS;
  688. }
  689. /* built-in 'read VAR' handler */
  690. static int builtin_read(struct child_prog *child)
  691. {
  692. int res;
  693. if (child->argv[1]) {
  694. char string[BUFSIZ];
  695. char *var = 0;
  696. string[0] = 0; /* In case stdin has only EOF */
  697. /* read string */
  698. fgets(string, sizeof(string), stdin);
  699. chomp(string);
  700. var = malloc(strlen(child->argv[1])+strlen(string)+2);
  701. if(var) {
  702. sprintf(var, "%s=%s", child->argv[1], string);
  703. res = set_local_var(var, 0);
  704. } else
  705. res = -1;
  706. if (res)
  707. fprintf(stderr, "read: %m\n");
  708. free(var); /* So not move up to avoid breaking errno */
  709. return res;
  710. } else {
  711. do res=getchar(); while(res!='\n' && res!=EOF);
  712. return 0;
  713. }
  714. }
  715. /* built-in 'set VAR=value' handler */
  716. static int builtin_set(struct child_prog *child)
  717. {
  718. char *temp = child->argv[1];
  719. struct variables *e;
  720. if (temp == NULL)
  721. for(e = top_vars; e; e=e->next)
  722. printf("%s=%s\n", e->name, e->value);
  723. else
  724. set_local_var(temp, 0);
  725. return EXIT_SUCCESS;
  726. }
  727. /* Built-in 'shift' handler */
  728. static int builtin_shift(struct child_prog *child)
  729. {
  730. int n=1;
  731. if (child->argv[1]) {
  732. n=atoi(child->argv[1]);
  733. }
  734. if (n>=0 && n<global_argc) {
  735. /* XXX This probably breaks $0 */
  736. global_argc -= n;
  737. global_argv += n;
  738. return EXIT_SUCCESS;
  739. } else {
  740. return EXIT_FAILURE;
  741. }
  742. }
  743. /* Built-in '.' handler (read-in and execute commands from file) */
  744. static int builtin_source(struct child_prog *child)
  745. {
  746. FILE *input;
  747. int status;
  748. if (child->argv[1] == NULL)
  749. return EXIT_FAILURE;
  750. /* XXX search through $PATH is missing */
  751. input = fopen(child->argv[1], "r");
  752. if (!input) {
  753. error_msg("Couldn't open file '%s'", child->argv[1]);
  754. return EXIT_FAILURE;
  755. }
  756. /* Now run the file */
  757. /* XXX argv and argc are broken; need to save old global_argv
  758. * (pointer only is OK!) on this stack frame,
  759. * set global_argv=child->argv+1, recurse, and restore. */
  760. mark_open(fileno(input));
  761. status = parse_file_outer(input);
  762. mark_closed(fileno(input));
  763. fclose(input);
  764. return (status);
  765. }
  766. static int builtin_umask(struct child_prog *child)
  767. {
  768. mode_t new_umask;
  769. const char *arg = child->argv[1];
  770. char *end;
  771. if (arg) {
  772. new_umask=strtoul(arg, &end, 8);
  773. if (*end!='\0' || end == arg) {
  774. return EXIT_FAILURE;
  775. }
  776. } else {
  777. printf("%.3o\n", (unsigned int) (new_umask=umask(0)));
  778. }
  779. umask(new_umask);
  780. return EXIT_SUCCESS;
  781. }
  782. /* built-in 'unset VAR' handler */
  783. static int builtin_unset(struct child_prog *child)
  784. {
  785. /* bash returned already true */
  786. unset_local_var(child->argv[1]);
  787. return EXIT_SUCCESS;
  788. }
  789. static int builtin_not_written(struct child_prog *child)
  790. {
  791. printf("builtin_%s not written\n",child->argv[0]);
  792. return EXIT_FAILURE;
  793. }
  794. #endif
  795. static int b_check_space(o_string *o, int len)
  796. {
  797. /* It would be easy to drop a more restrictive policy
  798. * in here, such as setting a maximum string length */
  799. if (o->length + len > o->maxlen) {
  800. char *old_data = o->data;
  801. /* assert (data == NULL || o->maxlen != 0); */
  802. o->maxlen += max(2*len, B_CHUNK);
  803. o->data = realloc(o->data, 1 + o->maxlen);
  804. if (o->data == NULL) {
  805. free(old_data);
  806. }
  807. }
  808. return o->data == NULL;
  809. }
  810. static int b_addchr(o_string *o, int ch)
  811. {
  812. debug_printf("b_addchr: %c %d %p\n", ch, o->length, o);
  813. if (b_check_space(o, 1)) return B_NOSPAC;
  814. o->data[o->length] = ch;
  815. o->length++;
  816. o->data[o->length] = '\0';
  817. return 0;
  818. }
  819. static void b_reset(o_string *o)
  820. {
  821. o->length = 0;
  822. o->nonnull = 0;
  823. if (o->data != NULL) *o->data = '\0';
  824. }
  825. static void b_free(o_string *o)
  826. {
  827. b_reset(o);
  828. free(o->data);
  829. o->data = NULL;
  830. o->maxlen = 0;
  831. }
  832. /* My analysis of quoting semantics tells me that state information
  833. * is associated with a destination, not a source.
  834. */
  835. static int b_addqchr(o_string *o, int ch, int quote)
  836. {
  837. if (quote && strchr("*?[\\",ch)) {
  838. int rc;
  839. rc = b_addchr(o, '\\');
  840. if (rc) return rc;
  841. }
  842. return b_addchr(o, ch);
  843. }
  844. #ifndef __U_BOOT__
  845. static int b_adduint(o_string *o, unsigned int i)
  846. {
  847. int r;
  848. char *p = simple_itoa(i);
  849. /* no escape checking necessary */
  850. do r=b_addchr(o, *p++); while (r==0 && *p);
  851. return r;
  852. }
  853. #endif
  854. static int static_get(struct in_str *i)
  855. {
  856. int ch = *i->p++;
  857. if (ch=='\0') return EOF;
  858. return ch;
  859. }
  860. static int static_peek(struct in_str *i)
  861. {
  862. return *i->p;
  863. }
  864. #ifndef __U_BOOT__
  865. static inline void cmdedit_set_initial_prompt(void)
  866. {
  867. #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
  868. PS1 = NULL;
  869. #else
  870. PS1 = env_get("PS1");
  871. if(PS1==0)
  872. PS1 = "\\w \\$ ";
  873. #endif
  874. }
  875. static inline void setup_prompt_string(int promptmode, char **prompt_str)
  876. {
  877. debug_printf("setup_prompt_string %d ",promptmode);
  878. #ifndef CONFIG_FEATURE_SH_FANCY_PROMPT
  879. /* Set up the prompt */
  880. if (promptmode == 1) {
  881. free(PS1);
  882. PS1=xmalloc(strlen(cwd)+4);
  883. sprintf(PS1, "%s %s", cwd, ( geteuid() != 0 ) ? "$ ":"# ");
  884. *prompt_str = PS1;
  885. } else {
  886. *prompt_str = PS2;
  887. }
  888. #else
  889. *prompt_str = (promptmode==1)? PS1 : PS2;
  890. #endif
  891. debug_printf("result %s\n",*prompt_str);
  892. }
  893. #endif
  894. #ifdef __U_BOOT__
  895. static int uboot_cli_readline(struct in_str *i)
  896. {
  897. char *prompt;
  898. char __maybe_unused *ps_prompt = NULL;
  899. if (i->promptmode == 1)
  900. prompt = CONFIG_SYS_PROMPT;
  901. else
  902. prompt = CONFIG_SYS_PROMPT_HUSH_PS2;
  903. #ifdef CONFIG_CMDLINE_PS_SUPPORT
  904. if (i->promptmode == 1)
  905. ps_prompt = env_get("PS1");
  906. else
  907. ps_prompt = env_get("PS2");
  908. if (ps_prompt)
  909. prompt = ps_prompt;
  910. #endif
  911. return cli_readline(prompt);
  912. }
  913. #endif
  914. static void get_user_input(struct in_str *i)
  915. {
  916. #ifndef __U_BOOT__
  917. char *prompt_str;
  918. static char the_command[BUFSIZ];
  919. setup_prompt_string(i->promptmode, &prompt_str);
  920. #ifdef CONFIG_FEATURE_COMMAND_EDITING
  921. /*
  922. ** enable command line editing only while a command line
  923. ** is actually being read; otherwise, we'll end up bequeathing
  924. ** atexit() handlers and other unwanted stuff to our
  925. ** child processes (rob@sysgo.de)
  926. */
  927. cmdedit_read_input(prompt_str, the_command);
  928. #else
  929. fputs(prompt_str, stdout);
  930. fflush(stdout);
  931. the_command[0]=fgetc(i->file);
  932. the_command[1]='\0';
  933. #endif
  934. fflush(stdout);
  935. i->p = the_command;
  936. #else
  937. int n;
  938. static char the_command[CONFIG_SYS_CBSIZE + 1];
  939. bootretry_reset_cmd_timeout();
  940. i->__promptme = 1;
  941. n = uboot_cli_readline(i);
  942. #ifdef CONFIG_BOOT_RETRY_TIME
  943. if (n == -2) {
  944. puts("\nTimeout waiting for command\n");
  945. # ifdef CONFIG_RESET_TO_RETRY
  946. do_reset(NULL, 0, 0, NULL);
  947. # else
  948. # error "This currently only works with CONFIG_RESET_TO_RETRY enabled"
  949. # endif
  950. }
  951. #endif
  952. if (n == -1 ) {
  953. flag_repeat = 0;
  954. i->__promptme = 0;
  955. }
  956. n = strlen(console_buffer);
  957. console_buffer[n] = '\n';
  958. console_buffer[n+1]= '\0';
  959. if (had_ctrlc()) flag_repeat = 0;
  960. clear_ctrlc();
  961. do_repeat = 0;
  962. if (i->promptmode == 1) {
  963. if (console_buffer[0] == '\n'&& flag_repeat == 0) {
  964. strcpy(the_command,console_buffer);
  965. }
  966. else {
  967. if (console_buffer[0] != '\n') {
  968. strcpy(the_command,console_buffer);
  969. flag_repeat = 1;
  970. }
  971. else {
  972. do_repeat = 1;
  973. }
  974. }
  975. i->p = the_command;
  976. }
  977. else {
  978. if (console_buffer[0] != '\n') {
  979. if (strlen(the_command) + strlen(console_buffer)
  980. < CONFIG_SYS_CBSIZE) {
  981. n = strlen(the_command);
  982. the_command[n-1] = ' ';
  983. strcpy(&the_command[n],console_buffer);
  984. }
  985. else {
  986. the_command[0] = '\n';
  987. the_command[1] = '\0';
  988. flag_repeat = 0;
  989. }
  990. }
  991. if (i->__promptme == 0) {
  992. the_command[0] = '\n';
  993. the_command[1] = '\0';
  994. }
  995. i->p = console_buffer;
  996. }
  997. #endif
  998. }
  999. /* This is the magic location that prints prompts
  1000. * and gets data back from the user */
  1001. static int file_get(struct in_str *i)
  1002. {
  1003. int ch;
  1004. ch = 0;
  1005. /* If there is data waiting, eat it up */
  1006. if (i->p && *i->p) {
  1007. ch = *i->p++;
  1008. } else {
  1009. /* need to double check i->file because we might be doing something
  1010. * more complicated by now, like sourcing or substituting. */
  1011. #ifndef __U_BOOT__
  1012. if (i->__promptme && interactive && i->file == stdin) {
  1013. while(! i->p || (interactive && strlen(i->p)==0) ) {
  1014. #else
  1015. while(! i->p || strlen(i->p)==0 ) {
  1016. #endif
  1017. get_user_input(i);
  1018. }
  1019. i->promptmode=2;
  1020. #ifndef __U_BOOT__
  1021. i->__promptme = 0;
  1022. #endif
  1023. if (i->p && *i->p) {
  1024. ch = *i->p++;
  1025. }
  1026. #ifndef __U_BOOT__
  1027. } else {
  1028. ch = fgetc(i->file);
  1029. }
  1030. #endif
  1031. debug_printf("b_getch: got a %d\n", ch);
  1032. }
  1033. #ifndef __U_BOOT__
  1034. if (ch == '\n') i->__promptme=1;
  1035. #endif
  1036. return ch;
  1037. }
  1038. /* All the callers guarantee this routine will never be
  1039. * used right after a newline, so prompting is not needed.
  1040. */
  1041. static int file_peek(struct in_str *i)
  1042. {
  1043. #ifndef __U_BOOT__
  1044. if (i->p && *i->p) {
  1045. #endif
  1046. return *i->p;
  1047. #ifndef __U_BOOT__
  1048. } else {
  1049. i->peek_buf[0] = fgetc(i->file);
  1050. i->peek_buf[1] = '\0';
  1051. i->p = i->peek_buf;
  1052. debug_printf("b_peek: got a %d\n", *i->p);
  1053. return *i->p;
  1054. }
  1055. #endif
  1056. }
  1057. #ifndef __U_BOOT__
  1058. static void setup_file_in_str(struct in_str *i, FILE *f)
  1059. #else
  1060. static void setup_file_in_str(struct in_str *i)
  1061. #endif
  1062. {
  1063. i->peek = file_peek;
  1064. i->get = file_get;
  1065. i->__promptme=1;
  1066. i->promptmode=1;
  1067. #ifndef __U_BOOT__
  1068. i->file = f;
  1069. #endif
  1070. i->p = NULL;
  1071. }
  1072. static void setup_string_in_str(struct in_str *i, const char *s)
  1073. {
  1074. i->peek = static_peek;
  1075. i->get = static_get;
  1076. i->__promptme=1;
  1077. i->promptmode=1;
  1078. i->p = s;
  1079. }
  1080. #ifndef __U_BOOT__
  1081. static void mark_open(int fd)
  1082. {
  1083. struct close_me *new = xmalloc(sizeof(struct close_me));
  1084. new->fd = fd;
  1085. new->next = close_me_head;
  1086. close_me_head = new;
  1087. }
  1088. static void mark_closed(int fd)
  1089. {
  1090. struct close_me *tmp;
  1091. if (close_me_head == NULL || close_me_head->fd != fd)
  1092. error_msg_and_die("corrupt close_me");
  1093. tmp = close_me_head;
  1094. close_me_head = close_me_head->next;
  1095. free(tmp);
  1096. }
  1097. static void close_all(void)
  1098. {
  1099. struct close_me *c;
  1100. for (c=close_me_head; c; c=c->next) {
  1101. close(c->fd);
  1102. }
  1103. close_me_head = NULL;
  1104. }
  1105. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  1106. * and stderr if they are redirected. */
  1107. static int setup_redirects(struct child_prog *prog, int squirrel[])
  1108. {
  1109. int openfd, mode;
  1110. struct redir_struct *redir;
  1111. for (redir=prog->redirects; redir; redir=redir->next) {
  1112. if (redir->dup == -1 && redir->word.gl_pathv == NULL) {
  1113. /* something went wrong in the parse. Pretend it didn't happen */
  1114. continue;
  1115. }
  1116. if (redir->dup == -1) {
  1117. mode=redir_table[redir->type].mode;
  1118. openfd = open(redir->word.gl_pathv[0], mode, 0666);
  1119. if (openfd < 0) {
  1120. /* this could get lost if stderr has been redirected, but
  1121. bash and ash both lose it as well (though zsh doesn't!) */
  1122. perror_msg("error opening %s", redir->word.gl_pathv[0]);
  1123. return 1;
  1124. }
  1125. } else {
  1126. openfd = redir->dup;
  1127. }
  1128. if (openfd != redir->fd) {
  1129. if (squirrel && redir->fd < 3) {
  1130. squirrel[redir->fd] = dup(redir->fd);
  1131. }
  1132. if (openfd == -3) {
  1133. close(openfd);
  1134. } else {
  1135. dup2(openfd, redir->fd);
  1136. if (redir->dup == -1)
  1137. close (openfd);
  1138. }
  1139. }
  1140. }
  1141. return 0;
  1142. }
  1143. static void restore_redirects(int squirrel[])
  1144. {
  1145. int i, fd;
  1146. for (i=0; i<3; i++) {
  1147. fd = squirrel[i];
  1148. if (fd != -1) {
  1149. /* No error checking. I sure wouldn't know what
  1150. * to do with an error if I found one! */
  1151. dup2(fd, i);
  1152. close(fd);
  1153. }
  1154. }
  1155. }
  1156. /* never returns */
  1157. /* XXX no exit() here. If you don't exec, use _exit instead.
  1158. * The at_exit handlers apparently confuse the calling process,
  1159. * in particular stdin handling. Not sure why? */
  1160. static void pseudo_exec(struct child_prog *child)
  1161. {
  1162. int i, rcode;
  1163. char *p;
  1164. struct built_in_command *x;
  1165. if (child->argv) {
  1166. for (i=0; is_assignment(child->argv[i]); i++) {
  1167. debug_printf("pid %d environment modification: %s\n",getpid(),child->argv[i]);
  1168. p = insert_var_value(child->argv[i]);
  1169. putenv(strdup(p));
  1170. if (p != child->argv[i]) free(p);
  1171. }
  1172. child->argv+=i; /* XXX this hack isn't so horrible, since we are about
  1173. to exit, and therefore don't need to keep data
  1174. structures consistent for free() use. */
  1175. /* If a variable is assigned in a forest, and nobody listens,
  1176. * was it ever really set?
  1177. */
  1178. if (child->argv[0] == NULL) {
  1179. _exit(EXIT_SUCCESS);
  1180. }
  1181. /*
  1182. * Check if the command matches any of the builtins.
  1183. * Depending on context, this might be redundant. But it's
  1184. * easier to waste a few CPU cycles than it is to figure out
  1185. * if this is one of those cases.
  1186. */
  1187. for (x = bltins; x->cmd; x++) {
  1188. if (strcmp(child->argv[0], x->cmd) == 0 ) {
  1189. debug_printf("builtin exec %s\n", child->argv[0]);
  1190. rcode = x->function(child);
  1191. fflush(stdout);
  1192. _exit(rcode);
  1193. }
  1194. }
  1195. /* Check if the command matches any busybox internal commands
  1196. * ("applets") here.
  1197. * FIXME: This feature is not 100% safe, since
  1198. * BusyBox is not fully reentrant, so we have no guarantee the things
  1199. * from the .bss are still zeroed, or that things from .data are still
  1200. * at their defaults. We could exec ourself from /proc/self/exe, but I
  1201. * really dislike relying on /proc for things. We could exec ourself
  1202. * from global_argv[0], but if we are in a chroot, we may not be able
  1203. * to find ourself... */
  1204. #ifdef CONFIG_FEATURE_SH_STANDALONE_SHELL
  1205. {
  1206. int argc_l;
  1207. char** argv_l=child->argv;
  1208. char *name = child->argv[0];
  1209. #ifdef CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN
  1210. /* Following discussions from November 2000 on the busybox mailing
  1211. * list, the default configuration, (without
  1212. * get_last_path_component()) lets the user force use of an
  1213. * external command by specifying the full (with slashes) filename.
  1214. * If you enable CONFIG_FEATURE_SH_APPLETS_ALWAYS_WIN then applets
  1215. * _aways_ override external commands, so if you want to run
  1216. * /bin/cat, it will use BusyBox cat even if /bin/cat exists on the
  1217. * filesystem and is _not_ busybox. Some systems may want this,
  1218. * most do not. */
  1219. name = get_last_path_component(name);
  1220. #endif
  1221. /* Count argc for use in a second... */
  1222. for(argc_l=0;*argv_l!=NULL; argv_l++, argc_l++);
  1223. optind = 1;
  1224. debug_printf("running applet %s\n", name);
  1225. run_applet_by_name(name, argc_l, child->argv);
  1226. }
  1227. #endif
  1228. debug_printf("exec of %s\n",child->argv[0]);
  1229. execvp(child->argv[0],child->argv);
  1230. perror_msg("couldn't exec: %s",child->argv[0]);
  1231. _exit(1);
  1232. } else if (child->group) {
  1233. debug_printf("runtime nesting to group\n");
  1234. interactive=0; /* crucial!!!! */
  1235. rcode = run_list_real(child->group);
  1236. /* OK to leak memory by not calling free_pipe_list,
  1237. * since this process is about to exit */
  1238. _exit(rcode);
  1239. } else {
  1240. /* Can happen. See what bash does with ">foo" by itself. */
  1241. debug_printf("trying to pseudo_exec null command\n");
  1242. _exit(EXIT_SUCCESS);
  1243. }
  1244. }
  1245. static void insert_bg_job(struct pipe *pi)
  1246. {
  1247. struct pipe *thejob;
  1248. /* Linear search for the ID of the job to use */
  1249. pi->jobid = 1;
  1250. for (thejob = job_list; thejob; thejob = thejob->next)
  1251. if (thejob->jobid >= pi->jobid)
  1252. pi->jobid = thejob->jobid + 1;
  1253. /* add thejob to the list of running jobs */
  1254. if (!job_list) {
  1255. thejob = job_list = xmalloc(sizeof(*thejob));
  1256. } else {
  1257. for (thejob = job_list; thejob->next; thejob = thejob->next) /* nothing */;
  1258. thejob->next = xmalloc(sizeof(*thejob));
  1259. thejob = thejob->next;
  1260. }
  1261. /* physically copy the struct job */
  1262. memcpy(thejob, pi, sizeof(struct pipe));
  1263. thejob->next = NULL;
  1264. thejob->running_progs = thejob->num_progs;
  1265. thejob->stopped_progs = 0;
  1266. thejob->text = xmalloc(BUFSIZ); /* cmdedit buffer size */
  1267. /*if (pi->progs[0] && pi->progs[0].argv && pi->progs[0].argv[0]) */
  1268. {
  1269. char *bar=thejob->text;
  1270. char **foo=pi->progs[0].argv;
  1271. while(foo && *foo) {
  1272. bar += sprintf(bar, "%s ", *foo++);
  1273. }
  1274. }
  1275. /* we don't wait for background thejobs to return -- append it
  1276. to the list of backgrounded thejobs and leave it alone */
  1277. printf("[%d] %d\n", thejob->jobid, thejob->progs[0].pid);
  1278. last_bg_pid = thejob->progs[0].pid;
  1279. last_jobid = thejob->jobid;
  1280. }
  1281. /* remove a backgrounded job */
  1282. static void remove_bg_job(struct pipe *pi)
  1283. {
  1284. struct pipe *prev_pipe;
  1285. if (pi == job_list) {
  1286. job_list = pi->next;
  1287. } else {
  1288. prev_pipe = job_list;
  1289. while (prev_pipe->next != pi)
  1290. prev_pipe = prev_pipe->next;
  1291. prev_pipe->next = pi->next;
  1292. }
  1293. if (job_list)
  1294. last_jobid = job_list->jobid;
  1295. else
  1296. last_jobid = 0;
  1297. pi->stopped_progs = 0;
  1298. free_pipe(pi, 0);
  1299. free(pi);
  1300. }
  1301. /* Checks to see if any processes have exited -- if they
  1302. have, figure out why and see if a job has completed */
  1303. static int checkjobs(struct pipe* fg_pipe)
  1304. {
  1305. int attributes;
  1306. int status;
  1307. int prognum = 0;
  1308. struct pipe *pi;
  1309. pid_t childpid;
  1310. attributes = WUNTRACED;
  1311. if (fg_pipe==NULL) {
  1312. attributes |= WNOHANG;
  1313. }
  1314. while ((childpid = waitpid(-1, &status, attributes)) > 0) {
  1315. if (fg_pipe) {
  1316. int i, rcode = 0;
  1317. for (i=0; i < fg_pipe->num_progs; i++) {
  1318. if (fg_pipe->progs[i].pid == childpid) {
  1319. if (i==fg_pipe->num_progs-1)
  1320. rcode=WEXITSTATUS(status);
  1321. (fg_pipe->num_progs)--;
  1322. return(rcode);
  1323. }
  1324. }
  1325. }
  1326. for (pi = job_list; pi; pi = pi->next) {
  1327. prognum = 0;
  1328. while (prognum < pi->num_progs && pi->progs[prognum].pid != childpid) {
  1329. prognum++;
  1330. }
  1331. if (prognum < pi->num_progs)
  1332. break;
  1333. }
  1334. if(pi==NULL) {
  1335. debug_printf("checkjobs: pid %d was not in our list!\n", childpid);
  1336. continue;
  1337. }
  1338. if (WIFEXITED(status) || WIFSIGNALED(status)) {
  1339. /* child exited */
  1340. pi->running_progs--;
  1341. pi->progs[prognum].pid = 0;
  1342. if (!pi->running_progs) {
  1343. printf(JOB_STATUS_FORMAT, pi->jobid, "Done", pi->text);
  1344. remove_bg_job(pi);
  1345. }
  1346. } else {
  1347. /* child stopped */
  1348. pi->stopped_progs++;
  1349. pi->progs[prognum].is_stopped = 1;
  1350. #if 0
  1351. /* Printing this stuff is a pain, since it tends to
  1352. * overwrite the prompt an inconveinient moments. So
  1353. * don't do that. */
  1354. if (pi->stopped_progs == pi->num_progs) {
  1355. printf("\n"JOB_STATUS_FORMAT, pi->jobid, "Stopped", pi->text);
  1356. }
  1357. #endif
  1358. }
  1359. }
  1360. if (childpid == -1 && errno != ECHILD)
  1361. perror_msg("waitpid");
  1362. /* move the shell to the foreground */
  1363. /*if (interactive && tcsetpgrp(shell_terminal, getpgid(0))) */
  1364. /* perror_msg("tcsetpgrp-2"); */
  1365. return -1;
  1366. }
  1367. /* Figure out our controlling tty, checking in order stderr,
  1368. * stdin, and stdout. If check_pgrp is set, also check that
  1369. * we belong to the foreground process group associated with
  1370. * that tty. The value of shell_terminal is needed in order to call
  1371. * tcsetpgrp(shell_terminal, ...); */
  1372. void controlling_tty(int check_pgrp)
  1373. {
  1374. pid_t curpgrp;
  1375. if ((curpgrp = tcgetpgrp(shell_terminal = 2)) < 0
  1376. && (curpgrp = tcgetpgrp(shell_terminal = 0)) < 0
  1377. && (curpgrp = tcgetpgrp(shell_terminal = 1)) < 0)
  1378. goto shell_terminal_error;
  1379. if (check_pgrp && curpgrp != getpgid(0))
  1380. goto shell_terminal_error;
  1381. return;
  1382. shell_terminal_error:
  1383. shell_terminal = -1;
  1384. return;
  1385. }
  1386. #endif
  1387. /* run_pipe_real() starts all the jobs, but doesn't wait for anything
  1388. * to finish. See checkjobs().
  1389. *
  1390. * return code is normally -1, when the caller has to wait for children
  1391. * to finish to determine the exit status of the pipe. If the pipe
  1392. * is a simple builtin command, however, the action is done by the
  1393. * time run_pipe_real returns, and the exit code is provided as the
  1394. * return value.
  1395. *
  1396. * The input of the pipe is always stdin, the output is always
  1397. * stdout. The outpipe[] mechanism in BusyBox-0.48 lash is bogus,
  1398. * because it tries to avoid running the command substitution in
  1399. * subshell, when that is in fact necessary. The subshell process
  1400. * now has its stdout directed to the input of the appropriate pipe,
  1401. * so this routine is noticeably simpler.
  1402. */
  1403. static int run_pipe_real(struct pipe *pi)
  1404. {
  1405. int i;
  1406. #ifndef __U_BOOT__
  1407. int nextin, nextout;
  1408. int pipefds[2]; /* pipefds[0] is for reading */
  1409. struct child_prog *child;
  1410. struct built_in_command *x;
  1411. char *p;
  1412. # if __GNUC__
  1413. /* Avoid longjmp clobbering */
  1414. (void) &i;
  1415. (void) &nextin;
  1416. (void) &nextout;
  1417. (void) &child;
  1418. # endif
  1419. #else
  1420. int nextin;
  1421. int flag = do_repeat ? CMD_FLAG_REPEAT : 0;
  1422. struct child_prog *child;
  1423. char *p;
  1424. # if __GNUC__
  1425. /* Avoid longjmp clobbering */
  1426. (void) &i;
  1427. (void) &nextin;
  1428. (void) &child;
  1429. # endif
  1430. #endif /* __U_BOOT__ */
  1431. nextin = 0;
  1432. #ifndef __U_BOOT__
  1433. pi->pgrp = -1;
  1434. #endif
  1435. /* Check if this is a simple builtin (not part of a pipe).
  1436. * Builtins within pipes have to fork anyway, and are handled in
  1437. * pseudo_exec. "echo foo | read bar" doesn't work on bash, either.
  1438. */
  1439. if (pi->num_progs == 1) child = & (pi->progs[0]);
  1440. #ifndef __U_BOOT__
  1441. if (pi->num_progs == 1 && child->group && child->subshell == 0) {
  1442. int squirrel[] = {-1, -1, -1};
  1443. int rcode;
  1444. debug_printf("non-subshell grouping\n");
  1445. setup_redirects(child, squirrel);
  1446. /* XXX could we merge code with following builtin case,
  1447. * by creating a pseudo builtin that calls run_list_real? */
  1448. rcode = run_list_real(child->group);
  1449. restore_redirects(squirrel);
  1450. #else
  1451. if (pi->num_progs == 1 && child->group) {
  1452. int rcode;
  1453. debug_printf("non-subshell grouping\n");
  1454. rcode = run_list_real(child->group);
  1455. #endif
  1456. return rcode;
  1457. } else if (pi->num_progs == 1 && pi->progs[0].argv != NULL) {
  1458. for (i=0; is_assignment(child->argv[i]); i++) { /* nothing */ }
  1459. if (i!=0 && child->argv[i]==NULL) {
  1460. /* assignments, but no command: set the local environment */
  1461. for (i=0; child->argv[i]!=NULL; i++) {
  1462. /* Ok, this case is tricky. We have to decide if this is a
  1463. * local variable, or an already exported variable. If it is
  1464. * already exported, we have to export the new value. If it is
  1465. * not exported, we need only set this as a local variable.
  1466. * This junk is all to decide whether or not to export this
  1467. * variable. */
  1468. int export_me=0;
  1469. char *name, *value;
  1470. name = xstrdup(child->argv[i]);
  1471. debug_printf("Local environment set: %s\n", name);
  1472. value = strchr(name, '=');
  1473. if (value)
  1474. *value=0;
  1475. #ifndef __U_BOOT__
  1476. if ( get_local_var(name)) {
  1477. export_me=1;
  1478. }
  1479. #endif
  1480. free(name);
  1481. p = insert_var_value(child->argv[i]);
  1482. set_local_var(p, export_me);
  1483. if (p != child->argv[i]) free(p);
  1484. }
  1485. return EXIT_SUCCESS; /* don't worry about errors in set_local_var() yet */
  1486. }
  1487. for (i = 0; is_assignment(child->argv[i]); i++) {
  1488. p = insert_var_value(child->argv[i]);
  1489. #ifndef __U_BOOT__
  1490. putenv(strdup(p));
  1491. #else
  1492. set_local_var(p, 0);
  1493. #endif
  1494. if (p != child->argv[i]) {
  1495. child->sp--;
  1496. free(p);
  1497. }
  1498. }
  1499. if (child->sp) {
  1500. char * str = NULL;
  1501. str = make_string(child->argv + i,
  1502. child->argv_nonnull + i);
  1503. parse_string_outer(str, FLAG_EXIT_FROM_LOOP | FLAG_REPARSING);
  1504. free(str);
  1505. return last_return_code;
  1506. }
  1507. #ifndef __U_BOOT__
  1508. for (x = bltins; x->cmd; x++) {
  1509. if (strcmp(child->argv[i], x->cmd) == 0 ) {
  1510. int squirrel[] = {-1, -1, -1};
  1511. int rcode;
  1512. if (x->function == builtin_exec && child->argv[i+1]==NULL) {
  1513. debug_printf("magic exec\n");
  1514. setup_redirects(child,NULL);
  1515. return EXIT_SUCCESS;
  1516. }
  1517. debug_printf("builtin inline %s\n", child->argv[0]);
  1518. /* XXX setup_redirects acts on file descriptors, not FILEs.
  1519. * This is perfect for work that comes after exec().
  1520. * Is it really safe for inline use? Experimentally,
  1521. * things seem to work with glibc. */
  1522. setup_redirects(child, squirrel);
  1523. child->argv += i; /* XXX horrible hack */
  1524. rcode = x->function(child);
  1525. /* XXX restore hack so free() can work right */
  1526. child->argv -= i;
  1527. restore_redirects(squirrel);
  1528. }
  1529. return rcode;
  1530. }
  1531. #else
  1532. /* check ";", because ,example , argv consist from
  1533. * "help;flinfo" must not execute
  1534. */
  1535. if (strchr(child->argv[i], ';')) {
  1536. printf("Unknown command '%s' - try 'help' or use "
  1537. "'run' command\n", child->argv[i]);
  1538. return -1;
  1539. }
  1540. /* Process the command */
  1541. return cmd_process(flag, child->argc - i, child->argv + i,
  1542. &flag_repeat, NULL);
  1543. #endif
  1544. }
  1545. #ifndef __U_BOOT__
  1546. for (i = 0; i < pi->num_progs; i++) {
  1547. child = & (pi->progs[i]);
  1548. /* pipes are inserted between pairs of commands */
  1549. if ((i + 1) < pi->num_progs) {
  1550. if (pipe(pipefds)<0) perror_msg_and_die("pipe");
  1551. nextout = pipefds[1];
  1552. } else {
  1553. nextout=1;
  1554. pipefds[0] = -1;
  1555. }
  1556. /* XXX test for failed fork()? */
  1557. if (!(child->pid = fork())) {
  1558. /* Set the handling for job control signals back to the default. */
  1559. signal(SIGINT, SIG_DFL);
  1560. signal(SIGQUIT, SIG_DFL);
  1561. signal(SIGTERM, SIG_DFL);
  1562. signal(SIGTSTP, SIG_DFL);
  1563. signal(SIGTTIN, SIG_DFL);
  1564. signal(SIGTTOU, SIG_DFL);
  1565. signal(SIGCHLD, SIG_DFL);
  1566. close_all();
  1567. if (nextin != 0) {
  1568. dup2(nextin, 0);
  1569. close(nextin);
  1570. }
  1571. if (nextout != 1) {
  1572. dup2(nextout, 1);
  1573. close(nextout);
  1574. }
  1575. if (pipefds[0]!=-1) {
  1576. close(pipefds[0]); /* opposite end of our output pipe */
  1577. }
  1578. /* Like bash, explicit redirects override pipes,
  1579. * and the pipe fd is available for dup'ing. */
  1580. setup_redirects(child,NULL);
  1581. if (interactive && pi->followup!=PIPE_BG) {
  1582. /* If we (the child) win the race, put ourselves in the process
  1583. * group whose leader is the first process in this pipe. */
  1584. if (pi->pgrp < 0) {
  1585. pi->pgrp = getpid();
  1586. }
  1587. if (setpgid(0, pi->pgrp) == 0) {
  1588. tcsetpgrp(2, pi->pgrp);
  1589. }
  1590. }
  1591. pseudo_exec(child);
  1592. }
  1593. /* put our child in the process group whose leader is the
  1594. first process in this pipe */
  1595. if (pi->pgrp < 0) {
  1596. pi->pgrp = child->pid;
  1597. }
  1598. /* Don't check for errors. The child may be dead already,
  1599. * in which case setpgid returns error code EACCES. */
  1600. setpgid(child->pid, pi->pgrp);
  1601. if (nextin != 0)
  1602. close(nextin);
  1603. if (nextout != 1)
  1604. close(nextout);
  1605. /* If there isn't another process, nextin is garbage
  1606. but it doesn't matter */
  1607. nextin = pipefds[0];
  1608. }
  1609. #endif
  1610. return -1;
  1611. }
  1612. static int run_list_real(struct pipe *pi)
  1613. {
  1614. char *save_name = NULL;
  1615. char **list = NULL;
  1616. char **save_list = NULL;
  1617. struct pipe *rpipe;
  1618. int flag_rep = 0;
  1619. #ifndef __U_BOOT__
  1620. int save_num_progs;
  1621. #endif
  1622. int rcode=0, flag_skip=1;
  1623. int flag_restore = 0;
  1624. int if_code=0, next_if_code=0; /* need double-buffer to handle elif */
  1625. reserved_style rmode, skip_more_in_this_rmode=RES_XXXX;
  1626. /* check syntax for "for" */
  1627. for (rpipe = pi; rpipe; rpipe = rpipe->next) {
  1628. if ((rpipe->r_mode == RES_IN ||
  1629. rpipe->r_mode == RES_FOR) &&
  1630. (rpipe->next == NULL)) {
  1631. syntax();
  1632. #ifdef __U_BOOT__
  1633. flag_repeat = 0;
  1634. #endif
  1635. return 1;
  1636. }
  1637. if ((rpipe->r_mode == RES_IN &&
  1638. (rpipe->next->r_mode == RES_IN &&
  1639. rpipe->next->progs->argv != NULL))||
  1640. (rpipe->r_mode == RES_FOR &&
  1641. rpipe->next->r_mode != RES_IN)) {
  1642. syntax();
  1643. #ifdef __U_BOOT__
  1644. flag_repeat = 0;
  1645. #endif
  1646. return 1;
  1647. }
  1648. }
  1649. for (; pi; pi = (flag_restore != 0) ? rpipe : pi->next) {
  1650. if (pi->r_mode == RES_WHILE || pi->r_mode == RES_UNTIL ||
  1651. pi->r_mode == RES_FOR) {
  1652. #ifdef __U_BOOT__
  1653. /* check Ctrl-C */
  1654. ctrlc();
  1655. if ((had_ctrlc())) {
  1656. return 1;
  1657. }
  1658. #endif
  1659. flag_restore = 0;
  1660. if (!rpipe) {
  1661. flag_rep = 0;
  1662. rpipe = pi;
  1663. }
  1664. }
  1665. rmode = pi->r_mode;
  1666. debug_printf("rmode=%d if_code=%d next_if_code=%d skip_more=%d\n", rmode, if_code, next_if_code, skip_more_in_this_rmode);
  1667. if (rmode == skip_more_in_this_rmode && flag_skip) {
  1668. if (pi->followup == PIPE_SEQ) flag_skip=0;
  1669. continue;
  1670. }
  1671. flag_skip = 1;
  1672. skip_more_in_this_rmode = RES_XXXX;
  1673. if (rmode == RES_THEN || rmode == RES_ELSE) if_code = next_if_code;
  1674. if (rmode == RES_THEN && if_code) continue;
  1675. if (rmode == RES_ELSE && !if_code) continue;
  1676. if (rmode == RES_ELIF && !if_code) break;
  1677. if (rmode == RES_FOR && pi->num_progs) {
  1678. if (!list) {
  1679. /* if no variable values after "in" we skip "for" */
  1680. if (!pi->next->progs->argv) continue;
  1681. /* create list of variable values */
  1682. list = make_list_in(pi->next->progs->argv,
  1683. pi->progs->argv[0]);
  1684. save_list = list;
  1685. save_name = pi->progs->argv[0];
  1686. pi->progs->argv[0] = NULL;
  1687. flag_rep = 1;
  1688. }
  1689. if (!(*list)) {
  1690. free(pi->progs->argv[0]);
  1691. free(save_list);
  1692. list = NULL;
  1693. flag_rep = 0;
  1694. pi->progs->argv[0] = save_name;
  1695. #ifndef __U_BOOT__
  1696. pi->progs->glob_result.gl_pathv[0] =
  1697. pi->progs->argv[0];
  1698. #endif
  1699. continue;
  1700. } else {
  1701. /* insert new value from list for variable */
  1702. free(pi->progs->argv[0]);
  1703. pi->progs->argv[0] = *list++;
  1704. #ifndef __U_BOOT__
  1705. pi->progs->glob_result.gl_pathv[0] =
  1706. pi->progs->argv[0];
  1707. #endif
  1708. }
  1709. }
  1710. if (rmode == RES_IN) continue;
  1711. if (rmode == RES_DO) {
  1712. if (!flag_rep) continue;
  1713. }
  1714. if (rmode == RES_DONE) {
  1715. if (flag_rep) {
  1716. flag_restore = 1;
  1717. } else {
  1718. rpipe = NULL;
  1719. }
  1720. }
  1721. if (pi->num_progs == 0) continue;
  1722. #ifndef __U_BOOT__
  1723. save_num_progs = pi->num_progs; /* save number of programs */
  1724. #endif
  1725. rcode = run_pipe_real(pi);
  1726. debug_printf("run_pipe_real returned %d\n",rcode);
  1727. #ifndef __U_BOOT__
  1728. if (rcode!=-1) {
  1729. /* We only ran a builtin: rcode was set by the return value
  1730. * of run_pipe_real(), and we don't need to wait for anything. */
  1731. } else if (pi->followup==PIPE_BG) {
  1732. /* XXX check bash's behavior with nontrivial pipes */
  1733. /* XXX compute jobid */
  1734. /* XXX what does bash do with attempts to background builtins? */
  1735. insert_bg_job(pi);
  1736. rcode = EXIT_SUCCESS;
  1737. } else {
  1738. if (interactive) {
  1739. /* move the new process group into the foreground */
  1740. if (tcsetpgrp(shell_terminal, pi->pgrp) && errno != ENOTTY)
  1741. perror_msg("tcsetpgrp-3");
  1742. rcode = checkjobs(pi);
  1743. /* move the shell to the foreground */
  1744. if (tcsetpgrp(shell_terminal, getpgid(0)) && errno != ENOTTY)
  1745. perror_msg("tcsetpgrp-4");
  1746. } else {
  1747. rcode = checkjobs(pi);
  1748. }
  1749. debug_printf("checkjobs returned %d\n",rcode);
  1750. }
  1751. last_return_code=rcode;
  1752. #else
  1753. if (rcode < -1) {
  1754. last_return_code = -rcode - 2;
  1755. return -2; /* exit */
  1756. }
  1757. last_return_code=(rcode == 0) ? 0 : 1;
  1758. #endif
  1759. #ifndef __U_BOOT__
  1760. pi->num_progs = save_num_progs; /* restore number of programs */
  1761. #endif
  1762. if ( rmode == RES_IF || rmode == RES_ELIF )
  1763. next_if_code=rcode; /* can be overwritten a number of times */
  1764. if (rmode == RES_WHILE)
  1765. flag_rep = !last_return_code;
  1766. if (rmode == RES_UNTIL)
  1767. flag_rep = last_return_code;
  1768. if ( (rcode==EXIT_SUCCESS && pi->followup==PIPE_OR) ||
  1769. (rcode!=EXIT_SUCCESS && pi->followup==PIPE_AND) )
  1770. skip_more_in_this_rmode=rmode;
  1771. #ifndef __U_BOOT__
  1772. checkjobs(NULL);
  1773. #endif
  1774. }
  1775. return rcode;
  1776. }
  1777. /* broken, of course, but OK for testing */
  1778. static char *indenter(int i)
  1779. {
  1780. static char blanks[]=" ";
  1781. return &blanks[sizeof(blanks)-i-1];
  1782. }
  1783. /* return code is the exit status of the pipe */
  1784. static int free_pipe(struct pipe *pi, int indent)
  1785. {
  1786. char **p;
  1787. struct child_prog *child;
  1788. #ifndef __U_BOOT__
  1789. struct redir_struct *r, *rnext;
  1790. #endif
  1791. int a, i, ret_code=0;
  1792. char *ind = indenter(indent);
  1793. #ifndef __U_BOOT__
  1794. if (pi->stopped_progs > 0)
  1795. return ret_code;
  1796. final_printf("%s run pipe: (pid %d)\n",ind,getpid());
  1797. #endif
  1798. for (i=0; i<pi->num_progs; i++) {
  1799. child = &pi->progs[i];
  1800. final_printf("%s command %d:\n",ind,i);
  1801. if (child->argv) {
  1802. for (a=0,p=child->argv; *p; a++,p++) {
  1803. final_printf("%s argv[%d] = %s\n",ind,a,*p);
  1804. }
  1805. #ifndef __U_BOOT__
  1806. globfree(&child->glob_result);
  1807. #else
  1808. for (a = 0; a < child->argc; a++) {
  1809. free(child->argv[a]);
  1810. }
  1811. free(child->argv);
  1812. free(child->argv_nonnull);
  1813. child->argc = 0;
  1814. #endif
  1815. child->argv=NULL;
  1816. } else if (child->group) {
  1817. #ifndef __U_BOOT__
  1818. final_printf("%s begin group (subshell:%d)\n",ind, child->subshell);
  1819. #endif
  1820. ret_code = free_pipe_list(child->group,indent+3);
  1821. final_printf("%s end group\n",ind);
  1822. } else {
  1823. final_printf("%s (nil)\n",ind);
  1824. }
  1825. #ifndef __U_BOOT__
  1826. for (r=child->redirects; r; r=rnext) {
  1827. final_printf("%s redirect %d%s", ind, r->fd, redir_table[r->type].descrip);
  1828. if (r->dup == -1) {
  1829. /* guard against the case >$FOO, where foo is unset or blank */
  1830. if (r->word.gl_pathv) {
  1831. final_printf(" %s\n", *r->word.gl_pathv);
  1832. globfree(&r->word);
  1833. }
  1834. } else {
  1835. final_printf("&%d\n", r->dup);
  1836. }
  1837. rnext=r->next;
  1838. free(r);
  1839. }
  1840. child->redirects=NULL;
  1841. #endif
  1842. }
  1843. free(pi->progs); /* children are an array, they get freed all at once */
  1844. pi->progs=NULL;
  1845. return ret_code;
  1846. }
  1847. static int free_pipe_list(struct pipe *head, int indent)
  1848. {
  1849. int rcode=0; /* if list has no members */
  1850. struct pipe *pi, *next;
  1851. char *ind = indenter(indent);
  1852. for (pi=head; pi; pi=next) {
  1853. final_printf("%s pipe reserved mode %d\n", ind, pi->r_mode);
  1854. rcode = free_pipe(pi, indent);
  1855. final_printf("%s pipe followup code %d\n", ind, pi->followup);
  1856. next=pi->next;
  1857. pi->next=NULL;
  1858. free(pi);
  1859. }
  1860. return rcode;
  1861. }
  1862. /* Select which version we will use */
  1863. static int run_list(struct pipe *pi)
  1864. {
  1865. int rcode=0;
  1866. #ifndef __U_BOOT__
  1867. if (fake_mode==0) {
  1868. #endif
  1869. rcode = run_list_real(pi);
  1870. #ifndef __U_BOOT__
  1871. }
  1872. #endif
  1873. /* free_pipe_list has the side effect of clearing memory
  1874. * In the long run that function can be merged with run_list_real,
  1875. * but doing that now would hobble the debugging effort. */
  1876. free_pipe_list(pi,0);
  1877. return rcode;
  1878. }
  1879. /* The API for glob is arguably broken. This routine pushes a non-matching
  1880. * string into the output structure, removing non-backslashed backslashes.
  1881. * If someone can prove me wrong, by performing this function within the
  1882. * original glob(3) api, feel free to rewrite this routine into oblivion.
  1883. * Return code (0 vs. GLOB_NOSPACE) matches glob(3).
  1884. * XXX broken if the last character is '\\', check that before calling.
  1885. */
  1886. #ifndef __U_BOOT__
  1887. static int globhack(const char *src, int flags, glob_t *pglob)
  1888. {
  1889. int cnt=0, pathc;
  1890. const char *s;
  1891. char *dest;
  1892. for (cnt=1, s=src; s && *s; s++) {
  1893. if (*s == '\\') s++;
  1894. cnt++;
  1895. }
  1896. dest = malloc(cnt);
  1897. if (!dest) return GLOB_NOSPACE;
  1898. if (!(flags & GLOB_APPEND)) {
  1899. pglob->gl_pathv=NULL;
  1900. pglob->gl_pathc=0;
  1901. pglob->gl_offs=0;
  1902. pglob->gl_offs=0;
  1903. }
  1904. pathc = ++pglob->gl_pathc;
  1905. pglob->gl_pathv = realloc(pglob->gl_pathv, (pathc+1)*sizeof(*pglob->gl_pathv));
  1906. if (pglob->gl_pathv == NULL) return GLOB_NOSPACE;
  1907. pglob->gl_pathv[pathc-1]=dest;
  1908. pglob->gl_pathv[pathc]=NULL;
  1909. for (s=src; s && *s; s++, dest++) {
  1910. if (*s == '\\') s++;
  1911. *dest = *s;
  1912. }
  1913. *dest='\0';
  1914. return 0;
  1915. }
  1916. /* XXX broken if the last character is '\\', check that before calling */
  1917. static int glob_needed(const char *s)
  1918. {
  1919. for (; *s; s++) {
  1920. if (*s == '\\') s++;
  1921. if (strchr("*[?",*s)) return 1;
  1922. }
  1923. return 0;
  1924. }
  1925. #if 0
  1926. static void globprint(glob_t *pglob)
  1927. {
  1928. int i;
  1929. debug_printf("glob_t at %p:\n", pglob);
  1930. debug_printf(" gl_pathc=%d gl_pathv=%p gl_offs=%d gl_flags=%d\n",
  1931. pglob->gl_pathc, pglob->gl_pathv, pglob->gl_offs, pglob->gl_flags);
  1932. for (i=0; i<pglob->gl_pathc; i++)
  1933. debug_printf("pglob->gl_pathv[%d] = %p = %s\n", i,
  1934. pglob->gl_pathv[i], pglob->gl_pathv[i]);
  1935. }
  1936. #endif
  1937. static int xglob(o_string *dest, int flags, glob_t *pglob)
  1938. {
  1939. int gr;
  1940. /* short-circuit for null word */
  1941. /* we can code this better when the debug_printf's are gone */
  1942. if (dest->length == 0) {
  1943. if (dest->nonnull) {
  1944. /* bash man page calls this an "explicit" null */
  1945. gr = globhack(dest->data, flags, pglob);
  1946. debug_printf("globhack returned %d\n",gr);
  1947. } else {
  1948. return 0;
  1949. }
  1950. } else if (glob_needed(dest->data)) {
  1951. gr = glob(dest->data, flags, NULL, pglob);
  1952. debug_printf("glob returned %d\n",gr);
  1953. if (gr == GLOB_NOMATCH) {
  1954. /* quote removal, or more accurately, backslash removal */
  1955. gr = globhack(dest->data, flags, pglob);
  1956. debug_printf("globhack returned %d\n",gr);
  1957. }
  1958. } else {
  1959. gr = globhack(dest->data, flags, pglob);
  1960. debug_printf("globhack returned %d\n",gr);
  1961. }
  1962. if (gr == GLOB_NOSPACE)
  1963. error_msg_and_die("out of memory during glob");
  1964. if (gr != 0) { /* GLOB_ABORTED ? */
  1965. error_msg("glob(3) error %d",gr);
  1966. }
  1967. /* globprint(glob_target); */
  1968. return gr;
  1969. }
  1970. #endif
  1971. #ifdef __U_BOOT__
  1972. static char *get_dollar_var(char ch);
  1973. #endif
  1974. /* This is used to get/check local shell variables */
  1975. char *get_local_var(const char *s)
  1976. {
  1977. struct variables *cur;
  1978. if (!s)
  1979. return NULL;
  1980. #ifdef __U_BOOT__
  1981. if (*s == '$')
  1982. return get_dollar_var(s[1]);
  1983. #endif
  1984. for (cur = top_vars; cur; cur=cur->next)
  1985. if(strcmp(cur->name, s)==0)
  1986. return cur->value;
  1987. return NULL;
  1988. }
  1989. /* This is used to set local shell variables
  1990. flg_export==0 if only local (not exporting) variable
  1991. flg_export==1 if "new" exporting environ
  1992. flg_export>1 if current startup environ (not call putenv()) */
  1993. int set_local_var(const char *s, int flg_export)
  1994. {
  1995. char *name, *value;
  1996. int result=0;
  1997. struct variables *cur;
  1998. #ifdef __U_BOOT__
  1999. /* might be possible! */
  2000. if (!isalpha(*s))
  2001. return -1;
  2002. #endif
  2003. name=strdup(s);
  2004. /* Assume when we enter this function that we are already in
  2005. * NAME=VALUE format. So the first order of business is to
  2006. * split 's' on the '=' into 'name' and 'value' */
  2007. value = strchr(name, '=');
  2008. if (value == NULL || *(value + 1) == 0) {
  2009. free(name);
  2010. return -1;
  2011. }
  2012. *value++ = 0;
  2013. for(cur = top_vars; cur; cur = cur->next) {
  2014. if(strcmp(cur->name, name)==0)
  2015. break;
  2016. }
  2017. if(cur) {
  2018. if(strcmp(cur->value, value)==0) {
  2019. if(flg_export>0 && cur->flg_export==0)
  2020. cur->flg_export=flg_export;
  2021. else
  2022. result++;
  2023. } else {
  2024. if(cur->flg_read_only) {
  2025. error_msg("%s: readonly variable", name);
  2026. result = -1;
  2027. } else {
  2028. if(flg_export>0 || cur->flg_export>1)
  2029. cur->flg_export=1;
  2030. free(cur->value);
  2031. cur->value = strdup(value);
  2032. }
  2033. }
  2034. } else {
  2035. cur = malloc(sizeof(struct variables));
  2036. if(!cur) {
  2037. result = -1;
  2038. } else {
  2039. cur->name = strdup(name);
  2040. if (cur->name == NULL) {
  2041. free(cur);
  2042. result = -1;
  2043. } else {
  2044. struct variables *bottom = top_vars;
  2045. cur->value = strdup(value);
  2046. cur->next = NULL;
  2047. cur->flg_export = flg_export;
  2048. cur->flg_read_only = 0;
  2049. while(bottom->next) bottom=bottom->next;
  2050. bottom->next = cur;
  2051. }
  2052. }
  2053. }
  2054. #ifndef __U_BOOT__
  2055. if(result==0 && cur->flg_export==1) {
  2056. *(value-1) = '=';
  2057. result = putenv(name);
  2058. } else {
  2059. #endif
  2060. free(name);
  2061. #ifndef __U_BOOT__
  2062. if(result>0) /* equivalent to previous set */
  2063. result = 0;
  2064. }
  2065. #endif
  2066. return result;
  2067. }
  2068. void unset_local_var(const char *name)
  2069. {
  2070. struct variables *cur;
  2071. if (name) {
  2072. for (cur = top_vars; cur; cur=cur->next) {
  2073. if(strcmp(cur->name, name)==0)
  2074. break;
  2075. }
  2076. if (cur != NULL) {
  2077. struct variables *next = top_vars;
  2078. if(cur->flg_read_only) {
  2079. error_msg("%s: readonly variable", name);
  2080. return;
  2081. } else {
  2082. #ifndef __U_BOOT__
  2083. if(cur->flg_export)
  2084. unenv_set(cur->name);
  2085. #endif
  2086. free(cur->name);
  2087. free(cur->value);
  2088. while (next->next != cur)
  2089. next = next->next;
  2090. next->next = cur->next;
  2091. }
  2092. free(cur);
  2093. }
  2094. }
  2095. }
  2096. static int is_assignment(const char *s)
  2097. {
  2098. if (s == NULL)
  2099. return 0;
  2100. if (!isalpha(*s)) return 0;
  2101. ++s;
  2102. while(isalnum(*s) || *s=='_') ++s;
  2103. return *s=='=';
  2104. }
  2105. #ifndef __U_BOOT__
  2106. /* the src parameter allows us to peek forward to a possible &n syntax
  2107. * for file descriptor duplication, e.g., "2>&1".
  2108. * Return code is 0 normally, 1 if a syntax error is detected in src.
  2109. * Resource errors (in xmalloc) cause the process to exit */
  2110. static int setup_redirect(struct p_context *ctx, int fd, redir_type style,
  2111. struct in_str *input)
  2112. {
  2113. struct child_prog *child=ctx->child;
  2114. struct redir_struct *redir = child->redirects;
  2115. struct redir_struct *last_redir=NULL;
  2116. /* Create a new redir_struct and drop it onto the end of the linked list */
  2117. while(redir) {
  2118. last_redir=redir;
  2119. redir=redir->next;
  2120. }
  2121. redir = xmalloc(sizeof(struct redir_struct));
  2122. redir->next=NULL;
  2123. redir->word.gl_pathv=NULL;
  2124. if (last_redir) {
  2125. last_redir->next=redir;
  2126. } else {
  2127. child->redirects=redir;
  2128. }
  2129. redir->type=style;
  2130. redir->fd= (fd==-1) ? redir_table[style].default_fd : fd ;
  2131. debug_printf("Redirect type %d%s\n", redir->fd, redir_table[style].descrip);
  2132. /* Check for a '2>&1' type redirect */
  2133. redir->dup = redirect_dup_num(input);
  2134. if (redir->dup == -2) return 1; /* syntax error */
  2135. if (redir->dup != -1) {
  2136. /* Erik had a check here that the file descriptor in question
  2137. * is legit; I postpone that to "run time"
  2138. * A "-" representation of "close me" shows up as a -3 here */
  2139. debug_printf("Duplicating redirect '%d>&%d'\n", redir->fd, redir->dup);
  2140. } else {
  2141. /* We do _not_ try to open the file that src points to,
  2142. * since we need to return and let src be expanded first.
  2143. * Set ctx->pending_redirect, so we know what to do at the
  2144. * end of the next parsed word.
  2145. */
  2146. ctx->pending_redirect = redir;
  2147. }
  2148. return 0;
  2149. }
  2150. #endif
  2151. static struct pipe *new_pipe(void)
  2152. {
  2153. struct pipe *pi;
  2154. pi = xmalloc(sizeof(struct pipe));
  2155. pi->num_progs = 0;
  2156. pi->progs = NULL;
  2157. pi->next = NULL;
  2158. pi->followup = 0; /* invalid */
  2159. pi->r_mode = RES_NONE;
  2160. return pi;
  2161. }
  2162. static void initialize_context(struct p_context *ctx)
  2163. {
  2164. ctx->pipe=NULL;
  2165. #ifndef __U_BOOT__
  2166. ctx->pending_redirect=NULL;
  2167. #endif
  2168. ctx->child=NULL;
  2169. ctx->list_head=new_pipe();
  2170. ctx->pipe=ctx->list_head;
  2171. ctx->w=RES_NONE;
  2172. ctx->stack=NULL;
  2173. #ifdef __U_BOOT__
  2174. ctx->old_flag=0;
  2175. #endif
  2176. done_command(ctx); /* creates the memory for working child */
  2177. }
  2178. /* normal return is 0
  2179. * if a reserved word is found, and processed, return 1
  2180. * should handle if, then, elif, else, fi, for, while, until, do, done.
  2181. * case, function, and select are obnoxious, save those for later.
  2182. */
  2183. struct reserved_combo {
  2184. char *literal;
  2185. int code;
  2186. long flag;
  2187. };
  2188. /* Mostly a list of accepted follow-up reserved words.
  2189. * FLAG_END means we are done with the sequence, and are ready
  2190. * to turn the compound list into a command.
  2191. * FLAG_START means the word must start a new compound list.
  2192. */
  2193. static struct reserved_combo reserved_list[] = {
  2194. { "if", RES_IF, FLAG_THEN | FLAG_START },
  2195. { "then", RES_THEN, FLAG_ELIF | FLAG_ELSE | FLAG_FI },
  2196. { "elif", RES_ELIF, FLAG_THEN },
  2197. { "else", RES_ELSE, FLAG_FI },
  2198. { "fi", RES_FI, FLAG_END },
  2199. { "for", RES_FOR, FLAG_IN | FLAG_START },
  2200. { "while", RES_WHILE, FLAG_DO | FLAG_START },
  2201. { "until", RES_UNTIL, FLAG_DO | FLAG_START },
  2202. { "in", RES_IN, FLAG_DO },
  2203. { "do", RES_DO, FLAG_DONE },
  2204. { "done", RES_DONE, FLAG_END }
  2205. };
  2206. #define NRES (sizeof(reserved_list)/sizeof(struct reserved_combo))
  2207. static int reserved_word(o_string *dest, struct p_context *ctx)
  2208. {
  2209. struct reserved_combo *r;
  2210. for (r=reserved_list;
  2211. r<reserved_list+NRES; r++) {
  2212. if (strcmp(dest->data, r->literal) == 0) {
  2213. debug_printf("found reserved word %s, code %d\n",r->literal,r->code);
  2214. if (r->flag & FLAG_START) {
  2215. struct p_context *new = xmalloc(sizeof(struct p_context));
  2216. debug_printf("push stack\n");
  2217. if (ctx->w == RES_IN || ctx->w == RES_FOR) {
  2218. syntax();
  2219. free(new);
  2220. ctx->w = RES_SNTX;
  2221. b_reset(dest);
  2222. return 1;
  2223. }
  2224. *new = *ctx; /* physical copy */
  2225. initialize_context(ctx);
  2226. ctx->stack=new;
  2227. } else if ( ctx->w == RES_NONE || ! (ctx->old_flag & (1<<r->code))) {
  2228. syntax();
  2229. ctx->w = RES_SNTX;
  2230. b_reset(dest);
  2231. return 1;
  2232. }
  2233. ctx->w=r->code;
  2234. ctx->old_flag = r->flag;
  2235. if (ctx->old_flag & FLAG_END) {
  2236. struct p_context *old;
  2237. debug_printf("pop stack\n");
  2238. done_pipe(ctx,PIPE_SEQ);
  2239. old = ctx->stack;
  2240. old->child->group = ctx->list_head;
  2241. #ifndef __U_BOOT__
  2242. old->child->subshell = 0;
  2243. #endif
  2244. *ctx = *old; /* physical copy */
  2245. free(old);
  2246. }
  2247. b_reset (dest);
  2248. return 1;
  2249. }
  2250. }
  2251. return 0;
  2252. }
  2253. /* normal return is 0.
  2254. * Syntax or xglob errors return 1. */
  2255. static int done_word(o_string *dest, struct p_context *ctx)
  2256. {
  2257. struct child_prog *child=ctx->child;
  2258. #ifndef __U_BOOT__
  2259. glob_t *glob_target;
  2260. int gr, flags = 0;
  2261. #else
  2262. char *str, *s;
  2263. int argc, cnt;
  2264. #endif
  2265. debug_printf("done_word: %s %p\n", dest->data, child);
  2266. if (dest->length == 0 && !dest->nonnull) {
  2267. debug_printf(" true null, ignored\n");
  2268. return 0;
  2269. }
  2270. #ifndef __U_BOOT__
  2271. if (ctx->pending_redirect) {
  2272. glob_target = &ctx->pending_redirect->word;
  2273. } else {
  2274. #endif
  2275. if (child->group) {
  2276. syntax();
  2277. return 1; /* syntax error, groups and arglists don't mix */
  2278. }
  2279. if (!child->argv && (ctx->type & FLAG_PARSE_SEMICOLON)) {
  2280. debug_printf("checking %s for reserved-ness\n",dest->data);
  2281. if (reserved_word(dest,ctx)) return ctx->w==RES_SNTX;
  2282. }
  2283. #ifndef __U_BOOT__
  2284. glob_target = &child->glob_result;
  2285. if (child->argv) flags |= GLOB_APPEND;
  2286. #else
  2287. for (cnt = 1, s = dest->data; s && *s; s++) {
  2288. if (*s == '\\') s++;
  2289. cnt++;
  2290. }
  2291. str = malloc(cnt);
  2292. if (!str) return 1;
  2293. if ( child->argv == NULL) {
  2294. child->argc=0;
  2295. }
  2296. argc = ++child->argc;
  2297. child->argv = realloc(child->argv, (argc+1)*sizeof(*child->argv));
  2298. if (child->argv == NULL) {
  2299. free(str);
  2300. return 1;
  2301. }
  2302. child->argv_nonnull = realloc(child->argv_nonnull,
  2303. (argc+1)*sizeof(*child->argv_nonnull));
  2304. if (child->argv_nonnull == NULL) {
  2305. free(str);
  2306. return 1;
  2307. }
  2308. child->argv[argc-1]=str;
  2309. child->argv_nonnull[argc-1] = dest->nonnull;
  2310. child->argv[argc]=NULL;
  2311. child->argv_nonnull[argc] = 0;
  2312. for (s = dest->data; s && *s; s++,str++) {
  2313. if (*s == '\\') s++;
  2314. *str = *s;
  2315. }
  2316. *str = '\0';
  2317. #endif
  2318. #ifndef __U_BOOT__
  2319. }
  2320. gr = xglob(dest, flags, glob_target);
  2321. if (gr != 0) return 1;
  2322. #endif
  2323. b_reset(dest);
  2324. #ifndef __U_BOOT__
  2325. if (ctx->pending_redirect) {
  2326. ctx->pending_redirect=NULL;
  2327. if (glob_target->gl_pathc != 1) {
  2328. error_msg("ambiguous redirect");
  2329. return 1;
  2330. }
  2331. } else {
  2332. child->argv = glob_target->gl_pathv;
  2333. }
  2334. #endif
  2335. if (ctx->w == RES_FOR) {
  2336. done_word(dest,ctx);
  2337. done_pipe(ctx,PIPE_SEQ);
  2338. }
  2339. return 0;
  2340. }
  2341. /* The only possible error here is out of memory, in which case
  2342. * xmalloc exits. */
  2343. static int done_command(struct p_context *ctx)
  2344. {
  2345. /* The child is really already in the pipe structure, so
  2346. * advance the pipe counter and make a new, null child.
  2347. * Only real trickiness here is that the uncommitted
  2348. * child structure, to which ctx->child points, is not
  2349. * counted in pi->num_progs. */
  2350. struct pipe *pi=ctx->pipe;
  2351. struct child_prog *prog=ctx->child;
  2352. if (prog && prog->group == NULL
  2353. && prog->argv == NULL
  2354. #ifndef __U_BOOT__
  2355. && prog->redirects == NULL) {
  2356. #else
  2357. ) {
  2358. #endif
  2359. debug_printf("done_command: skipping null command\n");
  2360. return 0;
  2361. } else if (prog) {
  2362. pi->num_progs++;
  2363. debug_printf("done_command: num_progs incremented to %d\n",pi->num_progs);
  2364. } else {
  2365. debug_printf("done_command: initializing\n");
  2366. }
  2367. pi->progs = xrealloc(pi->progs, sizeof(*pi->progs) * (pi->num_progs+1));
  2368. prog = pi->progs + pi->num_progs;
  2369. #ifndef __U_BOOT__
  2370. prog->redirects = NULL;
  2371. #endif
  2372. prog->argv = NULL;
  2373. prog->argv_nonnull = NULL;
  2374. #ifndef __U_BOOT__
  2375. prog->is_stopped = 0;
  2376. #endif
  2377. prog->group = NULL;
  2378. #ifndef __U_BOOT__
  2379. prog->glob_result.gl_pathv = NULL;
  2380. prog->family = pi;
  2381. #endif
  2382. prog->sp = 0;
  2383. ctx->child = prog;
  2384. prog->type = ctx->type;
  2385. /* but ctx->pipe and ctx->list_head remain unchanged */
  2386. return 0;
  2387. }
  2388. static int done_pipe(struct p_context *ctx, pipe_style type)
  2389. {
  2390. struct pipe *new_p;
  2391. done_command(ctx); /* implicit closure of previous command */
  2392. debug_printf("done_pipe, type %d\n", type);
  2393. ctx->pipe->followup = type;
  2394. ctx->pipe->r_mode = ctx->w;
  2395. new_p=new_pipe();
  2396. ctx->pipe->next = new_p;
  2397. ctx->pipe = new_p;
  2398. ctx->child = NULL;
  2399. done_command(ctx); /* set up new pipe to accept commands */
  2400. return 0;
  2401. }
  2402. #ifndef __U_BOOT__
  2403. /* peek ahead in the in_str to find out if we have a "&n" construct,
  2404. * as in "2>&1", that represents duplicating a file descriptor.
  2405. * returns either -2 (syntax error), -1 (no &), or the number found.
  2406. */
  2407. static int redirect_dup_num(struct in_str *input)
  2408. {
  2409. int ch, d=0, ok=0;
  2410. ch = b_peek(input);
  2411. if (ch != '&') return -1;
  2412. b_getch(input); /* get the & */
  2413. ch=b_peek(input);
  2414. if (ch == '-') {
  2415. b_getch(input);
  2416. return -3; /* "-" represents "close me" */
  2417. }
  2418. while (isdigit(ch)) {
  2419. d = d*10+(ch-'0');
  2420. ok=1;
  2421. b_getch(input);
  2422. ch = b_peek(input);
  2423. }
  2424. if (ok) return d;
  2425. error_msg("ambiguous redirect");
  2426. return -2;
  2427. }
  2428. /* If a redirect is immediately preceded by a number, that number is
  2429. * supposed to tell which file descriptor to redirect. This routine
  2430. * looks for such preceding numbers. In an ideal world this routine
  2431. * needs to handle all the following classes of redirects...
  2432. * echo 2>foo # redirects fd 2 to file "foo", nothing passed to echo
  2433. * echo 49>foo # redirects fd 49 to file "foo", nothing passed to echo
  2434. * echo -2>foo # redirects fd 1 to file "foo", "-2" passed to echo
  2435. * echo 49x>foo # redirects fd 1 to file "foo", "49x" passed to echo
  2436. * A -1 output from this program means no valid number was found, so the
  2437. * caller should use the appropriate default for this redirection.
  2438. */
  2439. static int redirect_opt_num(o_string *o)
  2440. {
  2441. int num;
  2442. if (o->length==0) return -1;
  2443. for(num=0; num<o->length; num++) {
  2444. if (!isdigit(*(o->data+num))) {
  2445. return -1;
  2446. }
  2447. }
  2448. /* reuse num (and save an int) */
  2449. num=atoi(o->data);
  2450. b_reset(o);
  2451. return num;
  2452. }
  2453. FILE *generate_stream_from_list(struct pipe *head)
  2454. {
  2455. FILE *pf;
  2456. #if 1
  2457. int pid, channel[2];
  2458. if (pipe(channel)<0) perror_msg_and_die("pipe");
  2459. pid=fork();
  2460. if (pid<0) {
  2461. perror_msg_and_die("fork");
  2462. } else if (pid==0) {
  2463. close(channel[0]);
  2464. if (channel[1] != 1) {
  2465. dup2(channel[1],1);
  2466. close(channel[1]);
  2467. }
  2468. #if 0
  2469. #define SURROGATE "surrogate response"
  2470. write(1,SURROGATE,sizeof(SURROGATE));
  2471. _exit(run_list(head));
  2472. #else
  2473. _exit(run_list_real(head)); /* leaks memory */
  2474. #endif
  2475. }
  2476. debug_printf("forked child %d\n",pid);
  2477. close(channel[1]);
  2478. pf = fdopen(channel[0],"r");
  2479. debug_printf("pipe on FILE *%p\n",pf);
  2480. #else
  2481. free_pipe_list(head,0);
  2482. pf=popen("echo surrogate response","r");
  2483. debug_printf("started fake pipe on FILE *%p\n",pf);
  2484. #endif
  2485. return pf;
  2486. }
  2487. /* this version hacked for testing purposes */
  2488. /* return code is exit status of the process that is run. */
  2489. static int process_command_subs(o_string *dest, struct p_context *ctx, struct in_str *input, int subst_end)
  2490. {
  2491. int retcode;
  2492. o_string result=NULL_O_STRING;
  2493. struct p_context inner;
  2494. FILE *p;
  2495. struct in_str pipe_str;
  2496. initialize_context(&inner);
  2497. /* recursion to generate command */
  2498. retcode = parse_stream(&result, &inner, input, subst_end);
  2499. if (retcode != 0) return retcode; /* syntax error or EOF */
  2500. done_word(&result, &inner);
  2501. done_pipe(&inner, PIPE_SEQ);
  2502. b_free(&result);
  2503. p=generate_stream_from_list(inner.list_head);
  2504. if (p==NULL) return 1;
  2505. mark_open(fileno(p));
  2506. setup_file_in_str(&pipe_str, p);
  2507. /* now send results of command back into original context */
  2508. retcode = parse_stream(dest, ctx, &pipe_str, '\0');
  2509. /* XXX In case of a syntax error, should we try to kill the child?
  2510. * That would be tough to do right, so just read until EOF. */
  2511. if (retcode == 1) {
  2512. while (b_getch(&pipe_str)!=EOF) { /* discard */ };
  2513. }
  2514. debug_printf("done reading from pipe, pclose()ing\n");
  2515. /* This is the step that wait()s for the child. Should be pretty
  2516. * safe, since we just read an EOF from its stdout. We could try
  2517. * to better, by using wait(), and keeping track of background jobs
  2518. * at the same time. That would be a lot of work, and contrary
  2519. * to the KISS philosophy of this program. */
  2520. mark_closed(fileno(p));
  2521. retcode=pclose(p);
  2522. free_pipe_list(inner.list_head,0);
  2523. debug_printf("pclosed, retcode=%d\n",retcode);
  2524. /* XXX this process fails to trim a single trailing newline */
  2525. return retcode;
  2526. }
  2527. static int parse_group(o_string *dest, struct p_context *ctx,
  2528. struct in_str *input, int ch)
  2529. {
  2530. int rcode, endch=0;
  2531. struct p_context sub;
  2532. struct child_prog *child = ctx->child;
  2533. if (child->argv) {
  2534. syntax();
  2535. return 1; /* syntax error, groups and arglists don't mix */
  2536. }
  2537. initialize_context(&sub);
  2538. switch(ch) {
  2539. case '(': endch=')'; child->subshell=1; break;
  2540. case '{': endch='}'; break;
  2541. default: syntax(); /* really logic error */
  2542. }
  2543. rcode=parse_stream(dest,&sub,input,endch);
  2544. done_word(dest,&sub); /* finish off the final word in the subcontext */
  2545. done_pipe(&sub, PIPE_SEQ); /* and the final command there, too */
  2546. child->group = sub.list_head;
  2547. return rcode;
  2548. /* child remains "open", available for possible redirects */
  2549. }
  2550. #endif
  2551. /* basically useful version until someone wants to get fancier,
  2552. * see the bash man page under "Parameter Expansion" */
  2553. static char *lookup_param(char *src)
  2554. {
  2555. char *p;
  2556. char *sep;
  2557. char *default_val = NULL;
  2558. int assign = 0;
  2559. int expand_empty = 0;
  2560. if (!src)
  2561. return NULL;
  2562. sep = strchr(src, ':');
  2563. if (sep) {
  2564. *sep = '\0';
  2565. if (*(sep + 1) == '-')
  2566. default_val = sep+2;
  2567. if (*(sep + 1) == '=') {
  2568. default_val = sep+2;
  2569. assign = 1;
  2570. }
  2571. if (*(sep + 1) == '+') {
  2572. default_val = sep+2;
  2573. expand_empty = 1;
  2574. }
  2575. }
  2576. p = env_get(src);
  2577. if (!p)
  2578. p = get_local_var(src);
  2579. if (!p || strlen(p) == 0) {
  2580. p = default_val;
  2581. if (assign) {
  2582. char *var = malloc(strlen(src)+strlen(default_val)+2);
  2583. if (var) {
  2584. sprintf(var, "%s=%s", src, default_val);
  2585. set_local_var(var, 0);
  2586. }
  2587. free(var);
  2588. }
  2589. } else if (expand_empty) {
  2590. p += strlen(p);
  2591. }
  2592. if (sep)
  2593. *sep = ':';
  2594. return p;
  2595. }
  2596. #ifdef __U_BOOT__
  2597. static char *get_dollar_var(char ch)
  2598. {
  2599. static char buf[40];
  2600. buf[0] = '\0';
  2601. switch (ch) {
  2602. case '?':
  2603. sprintf(buf, "%u", (unsigned int)last_return_code);
  2604. break;
  2605. default:
  2606. return NULL;
  2607. }
  2608. return buf;
  2609. }
  2610. #endif
  2611. /* return code: 0 for OK, 1 for syntax error */
  2612. static int handle_dollar(o_string *dest, struct p_context *ctx, struct in_str *input)
  2613. {
  2614. #ifndef __U_BOOT__
  2615. int i, advance=0;
  2616. #else
  2617. int advance=0;
  2618. #endif
  2619. #ifndef __U_BOOT__
  2620. char sep[]=" ";
  2621. #endif
  2622. int ch = input->peek(input); /* first character after the $ */
  2623. debug_printf("handle_dollar: ch=%c\n",ch);
  2624. if (isalpha(ch)) {
  2625. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2626. ctx->child->sp++;
  2627. while(ch=b_peek(input),isalnum(ch) || ch=='_') {
  2628. b_getch(input);
  2629. b_addchr(dest,ch);
  2630. }
  2631. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2632. #ifndef __U_BOOT__
  2633. } else if (isdigit(ch)) {
  2634. i = ch-'0'; /* XXX is $0 special? */
  2635. if (i<global_argc) {
  2636. parse_string(dest, ctx, global_argv[i]); /* recursion */
  2637. }
  2638. advance = 1;
  2639. #endif
  2640. } else switch (ch) {
  2641. #ifndef __U_BOOT__
  2642. case '$':
  2643. b_adduint(dest,getpid());
  2644. advance = 1;
  2645. break;
  2646. case '!':
  2647. if (last_bg_pid > 0) b_adduint(dest, last_bg_pid);
  2648. advance = 1;
  2649. break;
  2650. #endif
  2651. case '?':
  2652. #ifndef __U_BOOT__
  2653. b_adduint(dest,last_return_code);
  2654. #else
  2655. ctx->child->sp++;
  2656. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2657. b_addchr(dest, '$');
  2658. b_addchr(dest, '?');
  2659. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2660. #endif
  2661. advance = 1;
  2662. break;
  2663. #ifndef __U_BOOT__
  2664. case '#':
  2665. b_adduint(dest,global_argc ? global_argc-1 : 0);
  2666. advance = 1;
  2667. break;
  2668. #endif
  2669. case '{':
  2670. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2671. ctx->child->sp++;
  2672. b_getch(input);
  2673. /* XXX maybe someone will try to escape the '}' */
  2674. while(ch=b_getch(input),ch!=EOF && ch!='}') {
  2675. b_addchr(dest,ch);
  2676. }
  2677. if (ch != '}') {
  2678. syntax();
  2679. return 1;
  2680. }
  2681. b_addchr(dest, SPECIAL_VAR_SYMBOL);
  2682. break;
  2683. #ifndef __U_BOOT__
  2684. case '(':
  2685. b_getch(input);
  2686. process_command_subs(dest, ctx, input, ')');
  2687. break;
  2688. case '*':
  2689. sep[0]=ifs[0];
  2690. for (i=1; i<global_argc; i++) {
  2691. parse_string(dest, ctx, global_argv[i]);
  2692. if (i+1 < global_argc) parse_string(dest, ctx, sep);
  2693. }
  2694. break;
  2695. case '@':
  2696. case '-':
  2697. case '_':
  2698. /* still unhandled, but should be eventually */
  2699. error_msg("unhandled syntax: $%c",ch);
  2700. return 1;
  2701. break;
  2702. #endif
  2703. default:
  2704. b_addqchr(dest,'$',dest->quote);
  2705. }
  2706. /* Eat the character if the flag was set. If the compiler
  2707. * is smart enough, we could substitute "b_getch(input);"
  2708. * for all the "advance = 1;" above, and also end up with
  2709. * a nice size-optimized program. Hah! That'll be the day.
  2710. */
  2711. if (advance) b_getch(input);
  2712. return 0;
  2713. }
  2714. #ifndef __U_BOOT__
  2715. int parse_string(o_string *dest, struct p_context *ctx, const char *src)
  2716. {
  2717. struct in_str foo;
  2718. setup_string_in_str(&foo, src);
  2719. return parse_stream(dest, ctx, &foo, '\0');
  2720. }
  2721. #endif
  2722. /* return code is 0 for normal exit, 1 for syntax error */
  2723. static int parse_stream(o_string *dest, struct p_context *ctx,
  2724. struct in_str *input, int end_trigger)
  2725. {
  2726. unsigned int ch, m;
  2727. #ifndef __U_BOOT__
  2728. int redir_fd;
  2729. redir_type redir_style;
  2730. #endif
  2731. int next;
  2732. /* Only double-quote state is handled in the state variable dest->quote.
  2733. * A single-quote triggers a bypass of the main loop until its mate is
  2734. * found. When recursing, quote state is passed in via dest->quote. */
  2735. debug_printf("parse_stream, end_trigger=%d\n",end_trigger);
  2736. while ((ch=b_getch(input))!=EOF) {
  2737. m = map[ch];
  2738. #ifdef __U_BOOT__
  2739. if (input->__promptme == 0) return 1;
  2740. #endif
  2741. next = (ch == '\n') ? 0 : b_peek(input);
  2742. debug_printf("parse_stream: ch=%c (%d) m=%d quote=%d - %c\n",
  2743. ch >= ' ' ? ch : '.', ch, m,
  2744. dest->quote, ctx->stack == NULL ? '*' : '.');
  2745. if (m==0 || ((m==1 || m==2) && dest->quote)) {
  2746. b_addqchr(dest, ch, dest->quote);
  2747. } else {
  2748. if (m==2) { /* unquoted IFS */
  2749. if (done_word(dest, ctx)) {
  2750. return 1;
  2751. }
  2752. /* If we aren't performing a substitution, treat a newline as a
  2753. * command separator. */
  2754. if (end_trigger != '\0' && ch=='\n')
  2755. done_pipe(ctx,PIPE_SEQ);
  2756. }
  2757. if (ch == end_trigger && !dest->quote && ctx->w==RES_NONE) {
  2758. debug_printf("leaving parse_stream (triggered)\n");
  2759. return 0;
  2760. }
  2761. #if 0
  2762. if (ch=='\n') {
  2763. /* Yahoo! Time to run with it! */
  2764. done_pipe(ctx,PIPE_SEQ);
  2765. run_list(ctx->list_head);
  2766. initialize_context(ctx);
  2767. }
  2768. #endif
  2769. if (m!=2) switch (ch) {
  2770. case '#':
  2771. if (dest->length == 0 && !dest->quote) {
  2772. while(ch=b_peek(input),ch!=EOF && ch!='\n') { b_getch(input); }
  2773. } else {
  2774. b_addqchr(dest, ch, dest->quote);
  2775. }
  2776. break;
  2777. case '\\':
  2778. if (next == EOF) {
  2779. syntax();
  2780. return 1;
  2781. }
  2782. b_addqchr(dest, '\\', dest->quote);
  2783. b_addqchr(dest, b_getch(input), dest->quote);
  2784. break;
  2785. case '$':
  2786. if (handle_dollar(dest, ctx, input)!=0) return 1;
  2787. break;
  2788. case '\'':
  2789. dest->nonnull = 1;
  2790. while(ch=b_getch(input),ch!=EOF && ch!='\'') {
  2791. #ifdef __U_BOOT__
  2792. if(input->__promptme == 0) return 1;
  2793. #endif
  2794. b_addchr(dest,ch);
  2795. }
  2796. if (ch==EOF) {
  2797. syntax();
  2798. return 1;
  2799. }
  2800. break;
  2801. case '"':
  2802. dest->nonnull = 1;
  2803. dest->quote = !dest->quote;
  2804. break;
  2805. #ifndef __U_BOOT__
  2806. case '`':
  2807. process_command_subs(dest, ctx, input, '`');
  2808. break;
  2809. case '>':
  2810. redir_fd = redirect_opt_num(dest);
  2811. done_word(dest, ctx);
  2812. redir_style=REDIRECT_OVERWRITE;
  2813. if (next == '>') {
  2814. redir_style=REDIRECT_APPEND;
  2815. b_getch(input);
  2816. } else if (next == '(') {
  2817. syntax(); /* until we support >(list) Process Substitution */
  2818. return 1;
  2819. }
  2820. setup_redirect(ctx, redir_fd, redir_style, input);
  2821. break;
  2822. case '<':
  2823. redir_fd = redirect_opt_num(dest);
  2824. done_word(dest, ctx);
  2825. redir_style=REDIRECT_INPUT;
  2826. if (next == '<') {
  2827. redir_style=REDIRECT_HEREIS;
  2828. b_getch(input);
  2829. } else if (next == '>') {
  2830. redir_style=REDIRECT_IO;
  2831. b_getch(input);
  2832. } else if (next == '(') {
  2833. syntax(); /* until we support <(list) Process Substitution */
  2834. return 1;
  2835. }
  2836. setup_redirect(ctx, redir_fd, redir_style, input);
  2837. break;
  2838. #endif
  2839. case ';':
  2840. done_word(dest, ctx);
  2841. done_pipe(ctx,PIPE_SEQ);
  2842. break;
  2843. case '&':
  2844. done_word(dest, ctx);
  2845. if (next=='&') {
  2846. b_getch(input);
  2847. done_pipe(ctx,PIPE_AND);
  2848. } else {
  2849. #ifndef __U_BOOT__
  2850. done_pipe(ctx,PIPE_BG);
  2851. #else
  2852. syntax_err();
  2853. return 1;
  2854. #endif
  2855. }
  2856. break;
  2857. case '|':
  2858. done_word(dest, ctx);
  2859. if (next=='|') {
  2860. b_getch(input);
  2861. done_pipe(ctx,PIPE_OR);
  2862. } else {
  2863. /* we could pick up a file descriptor choice here
  2864. * with redirect_opt_num(), but bash doesn't do it.
  2865. * "echo foo 2| cat" yields "foo 2". */
  2866. #ifndef __U_BOOT__
  2867. done_command(ctx);
  2868. #else
  2869. syntax_err();
  2870. return 1;
  2871. #endif
  2872. }
  2873. break;
  2874. #ifndef __U_BOOT__
  2875. case '(':
  2876. case '{':
  2877. if (parse_group(dest, ctx, input, ch)!=0) return 1;
  2878. break;
  2879. case ')':
  2880. case '}':
  2881. syntax(); /* Proper use of this character caught by end_trigger */
  2882. return 1;
  2883. break;
  2884. #endif
  2885. case SUBSTED_VAR_SYMBOL:
  2886. dest->nonnull = 1;
  2887. while (ch = b_getch(input), ch != EOF &&
  2888. ch != SUBSTED_VAR_SYMBOL) {
  2889. debug_printf("subst, pass=%d\n", ch);
  2890. if (input->__promptme == 0)
  2891. return 1;
  2892. b_addchr(dest, ch);
  2893. }
  2894. debug_printf("subst, term=%d\n", ch);
  2895. if (ch == EOF) {
  2896. syntax();
  2897. return 1;
  2898. }
  2899. break;
  2900. default:
  2901. syntax(); /* this is really an internal logic error */
  2902. return 1;
  2903. }
  2904. }
  2905. }
  2906. /* complain if quote? No, maybe we just finished a command substitution
  2907. * that was quoted. Example:
  2908. * $ echo "`cat foo` plus more"
  2909. * and we just got the EOF generated by the subshell that ran "cat foo"
  2910. * The only real complaint is if we got an EOF when end_trigger != '\0',
  2911. * that is, we were really supposed to get end_trigger, and never got
  2912. * one before the EOF. Can't use the standard "syntax error" return code,
  2913. * so that parse_stream_outer can distinguish the EOF and exit smoothly. */
  2914. debug_printf("leaving parse_stream (EOF)\n");
  2915. if (end_trigger != '\0') return -1;
  2916. return 0;
  2917. }
  2918. static void mapset(const unsigned char *set, int code)
  2919. {
  2920. const unsigned char *s;
  2921. for (s=set; *s; s++) map[*s] = code;
  2922. }
  2923. static void update_ifs_map(void)
  2924. {
  2925. /* char *ifs and char map[256] are both globals. */
  2926. ifs = (uchar *)env_get("IFS");
  2927. if (ifs == NULL) ifs=(uchar *)" \t\n";
  2928. /* Precompute a list of 'flow through' behavior so it can be treated
  2929. * quickly up front. Computation is necessary because of IFS.
  2930. * Special case handling of IFS == " \t\n" is not implemented.
  2931. * The map[] array only really needs two bits each, and on most machines
  2932. * that would be faster because of the reduced L1 cache footprint.
  2933. */
  2934. memset(map,0,sizeof(map)); /* most characters flow through always */
  2935. #ifndef __U_BOOT__
  2936. mapset((uchar *)"\\$'\"`", 3); /* never flow through */
  2937. mapset((uchar *)"<>;&|(){}#", 1); /* flow through if quoted */
  2938. #else
  2939. {
  2940. uchar subst[2] = {SUBSTED_VAR_SYMBOL, 0};
  2941. mapset(subst, 3); /* never flow through */
  2942. }
  2943. mapset((uchar *)"\\$'\"", 3); /* never flow through */
  2944. mapset((uchar *)";&|#", 1); /* flow through if quoted */
  2945. #endif
  2946. mapset(ifs, 2); /* also flow through if quoted */
  2947. }
  2948. /* most recursion does not come through here, the exeception is
  2949. * from builtin_source() */
  2950. static int parse_stream_outer(struct in_str *inp, int flag)
  2951. {
  2952. struct p_context ctx;
  2953. o_string temp=NULL_O_STRING;
  2954. int rcode;
  2955. #ifdef __U_BOOT__
  2956. int code = 1;
  2957. #endif
  2958. do {
  2959. ctx.type = flag;
  2960. initialize_context(&ctx);
  2961. update_ifs_map();
  2962. if (!(flag & FLAG_PARSE_SEMICOLON) || (flag & FLAG_REPARSING)) mapset((uchar *)";$&|", 0);
  2963. inp->promptmode=1;
  2964. rcode = parse_stream(&temp, &ctx, inp,
  2965. flag & FLAG_CONT_ON_NEWLINE ? -1 : '\n');
  2966. #ifdef __U_BOOT__
  2967. if (rcode == 1) flag_repeat = 0;
  2968. #endif
  2969. if (rcode != 1 && ctx.old_flag != 0) {
  2970. syntax();
  2971. #ifdef __U_BOOT__
  2972. flag_repeat = 0;
  2973. #endif
  2974. }
  2975. if (rcode != 1 && ctx.old_flag == 0) {
  2976. done_word(&temp, &ctx);
  2977. done_pipe(&ctx,PIPE_SEQ);
  2978. #ifndef __U_BOOT__
  2979. run_list(ctx.list_head);
  2980. #else
  2981. code = run_list(ctx.list_head);
  2982. if (code == -2) { /* exit */
  2983. b_free(&temp);
  2984. code = 0;
  2985. /* XXX hackish way to not allow exit from main loop */
  2986. if (inp->peek == file_peek) {
  2987. printf("exit not allowed from main input shell.\n");
  2988. continue;
  2989. }
  2990. break;
  2991. }
  2992. if (code == -1)
  2993. flag_repeat = 0;
  2994. #endif
  2995. } else {
  2996. if (ctx.old_flag != 0) {
  2997. free(ctx.stack);
  2998. b_reset(&temp);
  2999. }
  3000. #ifdef __U_BOOT__
  3001. if (inp->__promptme == 0) printf("<INTERRUPT>\n");
  3002. inp->__promptme = 1;
  3003. #endif
  3004. temp.nonnull = 0;
  3005. temp.quote = 0;
  3006. inp->p = NULL;
  3007. free_pipe_list(ctx.list_head,0);
  3008. }
  3009. b_free(&temp);
  3010. /* loop on syntax errors, return on EOF */
  3011. } while (rcode != -1 && !(flag & FLAG_EXIT_FROM_LOOP) &&
  3012. (inp->peek != static_peek || b_peek(inp)));
  3013. #ifndef __U_BOOT__
  3014. return 0;
  3015. #else
  3016. return (code != 0) ? 1 : 0;
  3017. #endif /* __U_BOOT__ */
  3018. }
  3019. #ifndef __U_BOOT__
  3020. static int parse_string_outer(const char *s, int flag)
  3021. #else
  3022. int parse_string_outer(const char *s, int flag)
  3023. #endif /* __U_BOOT__ */
  3024. {
  3025. struct in_str input;
  3026. #ifdef __U_BOOT__
  3027. char *p = NULL;
  3028. int rcode;
  3029. if (!s)
  3030. return 1;
  3031. if (!*s)
  3032. return 0;
  3033. if (!(p = strchr(s, '\n')) || *++p) {
  3034. p = xmalloc(strlen(s) + 2);
  3035. strcpy(p, s);
  3036. strcat(p, "\n");
  3037. setup_string_in_str(&input, p);
  3038. rcode = parse_stream_outer(&input, flag);
  3039. free(p);
  3040. return rcode;
  3041. } else {
  3042. #endif
  3043. setup_string_in_str(&input, s);
  3044. return parse_stream_outer(&input, flag);
  3045. #ifdef __U_BOOT__
  3046. }
  3047. #endif
  3048. }
  3049. #ifndef __U_BOOT__
  3050. static int parse_file_outer(FILE *f)
  3051. #else
  3052. int parse_file_outer(void)
  3053. #endif
  3054. {
  3055. int rcode;
  3056. struct in_str input;
  3057. #ifndef __U_BOOT__
  3058. setup_file_in_str(&input, f);
  3059. #else
  3060. setup_file_in_str(&input);
  3061. #endif
  3062. rcode = parse_stream_outer(&input, FLAG_PARSE_SEMICOLON);
  3063. return rcode;
  3064. }
  3065. #ifdef __U_BOOT__
  3066. #ifdef CONFIG_NEEDS_MANUAL_RELOC
  3067. static void u_boot_hush_reloc(void)
  3068. {
  3069. unsigned long addr;
  3070. struct reserved_combo *r;
  3071. for (r=reserved_list; r<reserved_list+NRES; r++) {
  3072. addr = (ulong) (r->literal) + gd->reloc_off;
  3073. r->literal = (char *)addr;
  3074. }
  3075. }
  3076. #endif
  3077. int u_boot_hush_start(void)
  3078. {
  3079. if (top_vars == NULL) {
  3080. top_vars = malloc(sizeof(struct variables));
  3081. top_vars->name = "HUSH_VERSION";
  3082. top_vars->value = "0.01";
  3083. top_vars->next = NULL;
  3084. top_vars->flg_export = 0;
  3085. top_vars->flg_read_only = 1;
  3086. #ifdef CONFIG_NEEDS_MANUAL_RELOC
  3087. u_boot_hush_reloc();
  3088. #endif
  3089. }
  3090. return 0;
  3091. }
  3092. static void *xmalloc(size_t size)
  3093. {
  3094. void *p = NULL;
  3095. if (!(p = malloc(size))) {
  3096. printf("ERROR : xmalloc failed\n");
  3097. for(;;);
  3098. }
  3099. return p;
  3100. }
  3101. static void *xrealloc(void *ptr, size_t size)
  3102. {
  3103. void *p = NULL;
  3104. if (!(p = realloc(ptr, size))) {
  3105. printf("ERROR : xrealloc failed\n");
  3106. for(;;);
  3107. }
  3108. return p;
  3109. }
  3110. #endif /* __U_BOOT__ */
  3111. #ifndef __U_BOOT__
  3112. /* Make sure we have a controlling tty. If we get started under a job
  3113. * aware app (like bash for example), make sure we are now in charge so
  3114. * we don't fight over who gets the foreground */
  3115. static void setup_job_control(void)
  3116. {
  3117. static pid_t shell_pgrp;
  3118. /* Loop until we are in the foreground. */
  3119. while (tcgetpgrp (shell_terminal) != (shell_pgrp = getpgrp ()))
  3120. kill (- shell_pgrp, SIGTTIN);
  3121. /* Ignore interactive and job-control signals. */
  3122. signal(SIGINT, SIG_IGN);
  3123. signal(SIGQUIT, SIG_IGN);
  3124. signal(SIGTERM, SIG_IGN);
  3125. signal(SIGTSTP, SIG_IGN);
  3126. signal(SIGTTIN, SIG_IGN);
  3127. signal(SIGTTOU, SIG_IGN);
  3128. signal(SIGCHLD, SIG_IGN);
  3129. /* Put ourselves in our own process group. */
  3130. setsid();
  3131. shell_pgrp = getpid ();
  3132. setpgid (shell_pgrp, shell_pgrp);
  3133. /* Grab control of the terminal. */
  3134. tcsetpgrp(shell_terminal, shell_pgrp);
  3135. }
  3136. int hush_main(int argc, char * const *argv)
  3137. {
  3138. int opt;
  3139. FILE *input;
  3140. char **e = environ;
  3141. /* XXX what should these be while sourcing /etc/profile? */
  3142. global_argc = argc;
  3143. global_argv = argv;
  3144. /* (re?) initialize globals. Sometimes hush_main() ends up calling
  3145. * hush_main(), therefore we cannot rely on the BSS to zero out this
  3146. * stuff. Reset these to 0 every time. */
  3147. ifs = NULL;
  3148. /* map[] is taken care of with call to update_ifs_map() */
  3149. fake_mode = 0;
  3150. interactive = 0;
  3151. close_me_head = NULL;
  3152. last_bg_pid = 0;
  3153. job_list = NULL;
  3154. last_jobid = 0;
  3155. /* Initialize some more globals to non-zero values */
  3156. set_cwd();
  3157. #ifdef CONFIG_FEATURE_COMMAND_EDITING
  3158. cmdedit_set_initial_prompt();
  3159. #else
  3160. PS1 = NULL;
  3161. #endif
  3162. PS2 = "> ";
  3163. /* initialize our shell local variables with the values
  3164. * currently living in the environment */
  3165. if (e) {
  3166. for (; *e; e++)
  3167. set_local_var(*e, 2); /* without call putenv() */
  3168. }
  3169. last_return_code=EXIT_SUCCESS;
  3170. if (argv[0] && argv[0][0] == '-') {
  3171. debug_printf("\nsourcing /etc/profile\n");
  3172. if ((input = fopen("/etc/profile", "r")) != NULL) {
  3173. mark_open(fileno(input));
  3174. parse_file_outer(input);
  3175. mark_closed(fileno(input));
  3176. fclose(input);
  3177. }
  3178. }
  3179. input=stdin;
  3180. while ((opt = getopt(argc, argv, "c:xif")) > 0) {
  3181. switch (opt) {
  3182. case 'c':
  3183. {
  3184. global_argv = argv+optind;
  3185. global_argc = argc-optind;
  3186. opt = parse_string_outer(optarg, FLAG_PARSE_SEMICOLON);
  3187. goto final_return;
  3188. }
  3189. break;
  3190. case 'i':
  3191. interactive++;
  3192. break;
  3193. case 'f':
  3194. fake_mode++;
  3195. break;
  3196. default:
  3197. #ifndef BB_VER
  3198. fprintf(stderr, "Usage: sh [FILE]...\n"
  3199. " or: sh -c command [args]...\n\n");
  3200. exit(EXIT_FAILURE);
  3201. #else
  3202. show_usage();
  3203. #endif
  3204. }
  3205. }
  3206. /* A shell is interactive if the `-i' flag was given, or if all of
  3207. * the following conditions are met:
  3208. * no -c command
  3209. * no arguments remaining or the -s flag given
  3210. * standard input is a terminal
  3211. * standard output is a terminal
  3212. * Refer to Posix.2, the description of the `sh' utility. */
  3213. if (argv[optind]==NULL && input==stdin &&
  3214. isatty(fileno(stdin)) && isatty(fileno(stdout))) {
  3215. interactive++;
  3216. }
  3217. debug_printf("\ninteractive=%d\n", interactive);
  3218. if (interactive) {
  3219. /* Looks like they want an interactive shell */
  3220. #ifndef CONFIG_FEATURE_SH_EXTRA_QUIET
  3221. printf( "\n\n" BB_BANNER " hush - the humble shell v0.01 (testing)\n");
  3222. printf( "Enter 'help' for a list of built-in commands.\n\n");
  3223. #endif
  3224. setup_job_control();
  3225. }
  3226. if (argv[optind]==NULL) {
  3227. opt=parse_file_outer(stdin);
  3228. goto final_return;
  3229. }
  3230. debug_printf("\nrunning script '%s'\n", argv[optind]);
  3231. global_argv = argv+optind;
  3232. global_argc = argc-optind;
  3233. input = xfopen(argv[optind], "r");
  3234. opt = parse_file_outer(input);
  3235. #ifdef CONFIG_FEATURE_CLEAN_UP
  3236. fclose(input);
  3237. if (cwd && cwd != unknown)
  3238. free((char*)cwd);
  3239. {
  3240. struct variables *cur, *tmp;
  3241. for(cur = top_vars; cur; cur = tmp) {
  3242. tmp = cur->next;
  3243. if (!cur->flg_read_only) {
  3244. free(cur->name);
  3245. free(cur->value);
  3246. free(cur);
  3247. }
  3248. }
  3249. }
  3250. #endif
  3251. final_return:
  3252. return(opt?opt:last_return_code);
  3253. }
  3254. #endif
  3255. static char *insert_var_value(char *inp)
  3256. {
  3257. return insert_var_value_sub(inp, 0);
  3258. }
  3259. static char *insert_var_value_sub(char *inp, int tag_subst)
  3260. {
  3261. int res_str_len = 0;
  3262. int len;
  3263. int done = 0;
  3264. char *p, *p1, *res_str = NULL;
  3265. while ((p = strchr(inp, SPECIAL_VAR_SYMBOL))) {
  3266. /* check the beginning of the string for normal characters */
  3267. if (p != inp) {
  3268. /* copy any characters to the result string */
  3269. len = p - inp;
  3270. res_str = xrealloc(res_str, (res_str_len + len));
  3271. strncpy((res_str + res_str_len), inp, len);
  3272. res_str_len += len;
  3273. }
  3274. inp = ++p;
  3275. /* find the ending marker */
  3276. p = strchr(inp, SPECIAL_VAR_SYMBOL);
  3277. *p = '\0';
  3278. /* look up the value to substitute */
  3279. if ((p1 = lookup_param(inp))) {
  3280. if (tag_subst)
  3281. len = res_str_len + strlen(p1) + 2;
  3282. else
  3283. len = res_str_len + strlen(p1);
  3284. res_str = xrealloc(res_str, (1 + len));
  3285. if (tag_subst) {
  3286. /*
  3287. * copy the variable value to the result
  3288. * string
  3289. */
  3290. strcpy((res_str + res_str_len + 1), p1);
  3291. /*
  3292. * mark the replaced text to be accepted as
  3293. * is
  3294. */
  3295. res_str[res_str_len] = SUBSTED_VAR_SYMBOL;
  3296. res_str[res_str_len + 1 + strlen(p1)] =
  3297. SUBSTED_VAR_SYMBOL;
  3298. } else
  3299. /*
  3300. * copy the variable value to the result
  3301. * string
  3302. */
  3303. strcpy((res_str + res_str_len), p1);
  3304. res_str_len = len;
  3305. }
  3306. *p = SPECIAL_VAR_SYMBOL;
  3307. inp = ++p;
  3308. done = 1;
  3309. }
  3310. if (done) {
  3311. res_str = xrealloc(res_str, (1 + res_str_len + strlen(inp)));
  3312. strcpy((res_str + res_str_len), inp);
  3313. while ((p = strchr(res_str, '\n'))) {
  3314. *p = ' ';
  3315. }
  3316. }
  3317. return (res_str == NULL) ? inp : res_str;
  3318. }
  3319. static char **make_list_in(char **inp, char *name)
  3320. {
  3321. int len, i;
  3322. int name_len = strlen(name);
  3323. int n = 0;
  3324. char **list;
  3325. char *p1, *p2, *p3;
  3326. /* create list of variable values */
  3327. list = xmalloc(sizeof(*list));
  3328. for (i = 0; inp[i]; i++) {
  3329. p3 = insert_var_value(inp[i]);
  3330. p1 = p3;
  3331. while (*p1) {
  3332. if (*p1 == ' ') {
  3333. p1++;
  3334. continue;
  3335. }
  3336. if ((p2 = strchr(p1, ' '))) {
  3337. len = p2 - p1;
  3338. } else {
  3339. len = strlen(p1);
  3340. p2 = p1 + len;
  3341. }
  3342. /* we use n + 2 in realloc for list,because we add
  3343. * new element and then we will add NULL element */
  3344. list = xrealloc(list, sizeof(*list) * (n + 2));
  3345. list[n] = xmalloc(2 + name_len + len);
  3346. strcpy(list[n], name);
  3347. strcat(list[n], "=");
  3348. strncat(list[n], p1, len);
  3349. list[n++][name_len + len + 1] = '\0';
  3350. p1 = p2;
  3351. }
  3352. if (p3 != inp[i]) free(p3);
  3353. }
  3354. list[n] = NULL;
  3355. return list;
  3356. }
  3357. /*
  3358. * Make new string for parser
  3359. * inp - array of argument strings to flatten
  3360. * nonnull - indicates argument was quoted when originally parsed
  3361. */
  3362. static char *make_string(char **inp, int *nonnull)
  3363. {
  3364. char *p;
  3365. char *str = NULL;
  3366. int n;
  3367. int len = 2;
  3368. char *noeval_str;
  3369. int noeval = 0;
  3370. noeval_str = get_local_var("HUSH_NO_EVAL");
  3371. if (noeval_str != NULL && *noeval_str != '0' && *noeval_str != '\0')
  3372. noeval = 1;
  3373. for (n = 0; inp[n]; n++) {
  3374. p = insert_var_value_sub(inp[n], noeval);
  3375. str = xrealloc(str, (len + strlen(p) + (2 * nonnull[n])));
  3376. if (n) {
  3377. strcat(str, " ");
  3378. } else {
  3379. *str = '\0';
  3380. }
  3381. if (nonnull[n])
  3382. strcat(str, "'");
  3383. strcat(str, p);
  3384. if (nonnull[n])
  3385. strcat(str, "'");
  3386. len = strlen(str) + 3;
  3387. if (p != inp[n]) free(p);
  3388. }
  3389. len = strlen(str);
  3390. *(str + len) = '\n';
  3391. *(str + len + 1) = '\0';
  3392. return str;
  3393. }
  3394. #ifdef __U_BOOT__
  3395. static int do_showvar(struct cmd_tbl *cmdtp, int flag, int argc,
  3396. char *const argv[])
  3397. {
  3398. int i, k;
  3399. int rcode = 0;
  3400. struct variables *cur;
  3401. if (argc == 1) { /* Print all env variables */
  3402. for (cur = top_vars; cur; cur = cur->next) {
  3403. printf ("%s=%s\n", cur->name, cur->value);
  3404. if (ctrlc ()) {
  3405. puts ("\n ** Abort\n");
  3406. return 1;
  3407. }
  3408. }
  3409. return 0;
  3410. }
  3411. for (i = 1; i < argc; ++i) { /* print single env variables */
  3412. char *name = argv[i];
  3413. k = -1;
  3414. for (cur = top_vars; cur; cur = cur->next) {
  3415. if(strcmp (cur->name, name) == 0) {
  3416. k = 0;
  3417. printf ("%s=%s\n", cur->name, cur->value);
  3418. }
  3419. if (ctrlc ()) {
  3420. puts ("\n ** Abort\n");
  3421. return 1;
  3422. }
  3423. }
  3424. if (k < 0) {
  3425. printf ("## Error: \"%s\" not defined\n", name);
  3426. rcode ++;
  3427. }
  3428. }
  3429. return rcode;
  3430. }
  3431. U_BOOT_CMD(
  3432. showvar, CONFIG_SYS_MAXARGS, 1, do_showvar,
  3433. "print local hushshell variables",
  3434. "\n - print values of all hushshell variables\n"
  3435. "showvar name ...\n"
  3436. " - print value of hushshell variable 'name'"
  3437. );
  3438. #endif
  3439. /****************************************************************************/