hush.c 91 KB

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