cli_hush.c 94 KB

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