hush.c 90 KB

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