hush.c 92 KB

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