hush.c 91 KB

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