hush.c 93 KB

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