cli_hush.c 93 KB

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