cli_hush.c 93 KB

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