hush.c 92 KB

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