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