hush.c 92 KB

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