cli_hush.c 93 KB

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