hush.c 92 KB

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