hush.c 90 KB

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