cli_hush.c 94 KB

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