hush.c 91 KB

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