hush.c 91 KB

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