hush.c 91 KB

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