hush.c 92 KB

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