hush.c 92 KB

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