lash_unused.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * lash -- the BusyBox Lame-Ass SHell
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Based in part on ladsh.c by Michael K. Johnson and Erik W. Troan, which is
  8. * under the following liberal license: "We have placed this source code in the
  9. * public domain. Use it in any project, free or commercial."
  10. *
  11. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  12. */
  13. /* This shell's parsing engine is officially at a dead-end. Future
  14. * work shell work should be done using hush, msh, or ash. This is
  15. * still a very useful, small shell -- it just don't need any more
  16. * features beyond what it already has...
  17. */
  18. //For debugging/development on the shell only...
  19. //#define DEBUG_SHELL
  20. #include <getopt.h>
  21. #include <glob.h>
  22. #include "libbb.h"
  23. #define expand_t glob_t
  24. /* Always enable for the moment... */
  25. #define CONFIG_LASH_PIPE_N_REDIRECTS
  26. #define CONFIG_LASH_JOB_CONTROL
  27. #define ENABLE_LASH_PIPE_N_REDIRECTS 1
  28. #define ENABLE_LASH_JOB_CONTROL 1
  29. enum { MAX_READ = 128 }; /* size of input buffer for 'read' builtin */
  30. #define JOB_STATUS_FORMAT "[%d] %-22s %.40s\n"
  31. #if ENABLE_LASH_PIPE_N_REDIRECTS
  32. enum redir_type { REDIRECT_INPUT, REDIRECT_OVERWRITE,
  33. REDIRECT_APPEND
  34. };
  35. #endif
  36. enum {
  37. DEFAULT_CONTEXT = 0x1,
  38. IF_TRUE_CONTEXT = 0x2,
  39. IF_FALSE_CONTEXT = 0x4,
  40. THEN_EXP_CONTEXT = 0x8,
  41. ELSE_EXP_CONTEXT = 0x10
  42. };
  43. #define LASH_OPT_DONE (1)
  44. #define LASH_OPT_SAW_QUOTE (2)
  45. #if ENABLE_LASH_PIPE_N_REDIRECTS
  46. struct redir_struct {
  47. enum redir_type type; /* type of redirection */
  48. int fd; /* file descriptor being redirected */
  49. char *filename; /* file to redirect fd to */
  50. };
  51. #endif
  52. struct child_prog {
  53. pid_t pid; /* 0 if exited */
  54. char **argv; /* program name and arguments */
  55. int num_redirects; /* elements in redirection array */
  56. int is_stopped; /* is the program currently running? */
  57. struct job *family; /* pointer back to the child's parent job */
  58. #if ENABLE_LASH_PIPE_N_REDIRECTS
  59. struct redir_struct *redirects; /* I/O redirects */
  60. #endif
  61. };
  62. struct jobset {
  63. struct job *head; /* head of list of running jobs */
  64. struct job *fg; /* current foreground job */
  65. };
  66. struct job {
  67. int jobid; /* job number */
  68. int num_progs; /* total number of programs in job */
  69. int running_progs; /* number of programs running */
  70. char *text; /* name of job */
  71. char *cmdbuf; /* buffer various argv's point into */
  72. pid_t pgrp; /* process group ID for the job */
  73. struct child_prog *progs; /* array of programs in job */
  74. struct job *next; /* to track background commands */
  75. int stopped_progs; /* number of programs alive, but stopped */
  76. unsigned int job_context; /* bitmask defining current context */
  77. struct jobset *job_list;
  78. };
  79. struct built_in_command {
  80. const char *cmd; /* name */
  81. const char *descr; /* description */
  82. int (*function) (struct child_prog *); /* function ptr */
  83. };
  84. /* function prototypes for builtins */
  85. static int builtin_cd(struct child_prog *cmd);
  86. static int builtin_exec(struct child_prog *cmd);
  87. static int builtin_exit(struct child_prog *cmd);
  88. static int builtin_fg_bg(struct child_prog *cmd);
  89. static int builtin_help(struct child_prog *cmd);
  90. static int builtin_jobs(struct child_prog *dummy);
  91. static int builtin_pwd(struct child_prog *dummy);
  92. static int builtin_export(struct child_prog *cmd);
  93. static int builtin_source(struct child_prog *cmd);
  94. static int builtin_unset(struct child_prog *cmd);
  95. static int builtin_read(struct child_prog *cmd);
  96. /* function prototypes for shell stuff */
  97. static void checkjobs(struct jobset *job_list);
  98. static void remove_job(struct jobset *j_list, struct job *job);
  99. static int get_command_bufsiz(FILE *source, char *command);
  100. static int parse_command(char **command_ptr, struct job *job, int *inbg);
  101. static int run_command(struct job *newjob, int inbg, int outpipe[2]);
  102. static int pseudo_exec(struct child_prog *cmd) NORETURN;
  103. static int busy_loop(FILE *input);
  104. /* Table of built-in functions (these are non-forking builtins, meaning they
  105. * can change global variables in the parent shell process but they will not
  106. * work with pipes and redirects; 'unset foo | whatever' will not work) */
  107. static const struct built_in_command bltins[] = {
  108. {"bg" , "Resume a job in the background", builtin_fg_bg},
  109. {"cd" , "Change working directory", builtin_cd},
  110. {"exec" , "Exec command, replacing this shell with the exec'd process", builtin_exec},
  111. {"exit" , "Exit from shell()", builtin_exit},
  112. {"fg" , "Bring job into the foreground", builtin_fg_bg},
  113. {"jobs" , "Lists the active jobs", builtin_jobs},
  114. {"export", "Set environment variable", builtin_export},
  115. {"unset" , "Unset environment variable", builtin_unset},
  116. {"read" , "Input environment variable", builtin_read},
  117. {"." , "Source-in and run commands in a file", builtin_source},
  118. /* These were "forked applets", but distinction was nuked */
  119. /* Original comment retained: */
  120. /* Table of forking built-in functions (things that fork cannot change global
  121. * variables in the parent process, such as the current working directory) */
  122. {"pwd" , "Print current directory", builtin_pwd},
  123. {"help" , "List shell built-in commands", builtin_help},
  124. /* to do: add ulimit */
  125. };
  126. #define VEC_LAST(v) v[ARRAY_SIZE(v)-1]
  127. static int shell_context; /* Type prompt trigger (PS1 or PS2) */
  128. /* Globals that are static to this file */
  129. static char *cwd;
  130. static char *local_pending_command;
  131. static struct jobset job_list = { NULL, NULL };
  132. static int global_argc;
  133. static char **global_argv;
  134. static llist_t *close_me_list;
  135. static int last_return_code;
  136. static int last_bg_pid;
  137. static unsigned int last_jobid;
  138. static int shell_terminal;
  139. static const char *PS1;
  140. static const char *PS2 = "> ";
  141. #ifdef DEBUG_SHELL
  142. static inline void debug_printf(const char *format, ...)
  143. {
  144. va_list args;
  145. va_start(args, format);
  146. vfprintf(stderr, format, args);
  147. va_end(args);
  148. }
  149. #else
  150. static inline void debug_printf(const char UNUSED_PARAM *format, ...) { }
  151. #endif
  152. /*
  153. Most builtins need access to the struct child_prog that has
  154. their arguments, previously coded as cmd->progs[0]. That coding
  155. can exhibit a bug, if the builtin is not the first command in
  156. a pipeline: "echo foo | exec sort" will attempt to exec foo.
  157. builtin previous use notes
  158. ------ ----------------- ---------
  159. cd cmd->progs[0]
  160. exec cmd->progs[0] squashed bug: didn't look for applets or forking builtins
  161. exit cmd->progs[0]
  162. fg_bg cmd->progs[0], job_list->head, job_list->fg
  163. help 0
  164. jobs job_list->head
  165. pwd 0
  166. export cmd->progs[0]
  167. source cmd->progs[0]
  168. unset cmd->progs[0]
  169. read cmd->progs[0]
  170. I added "struct job *family;" to struct child_prog,
  171. and switched API to builtin_foo(struct child_prog *child);
  172. So cmd->text becomes child->family->text
  173. cmd->job_context becomes child->family->job_context
  174. cmd->progs[0] becomes *child
  175. job_list becomes child->family->job_list
  176. */
  177. static void update_cwd(void)
  178. {
  179. cwd = xrealloc_getcwd_or_warn(cwd);
  180. if (!cwd)
  181. cwd = xstrdup(bb_msg_unknown);
  182. }
  183. /* built-in 'cd <path>' handler */
  184. static int builtin_cd(struct child_prog *child)
  185. {
  186. char *newdir;
  187. if (child->argv[1] == NULL)
  188. newdir = getenv("HOME");
  189. else
  190. newdir = child->argv[1];
  191. if (chdir(newdir)) {
  192. bb_perror_msg("cd: %s", newdir);
  193. return EXIT_FAILURE;
  194. }
  195. update_cwd();
  196. return EXIT_SUCCESS;
  197. }
  198. /* built-in 'exec' handler */
  199. static int builtin_exec(struct child_prog *child)
  200. {
  201. if (child->argv[1] == NULL)
  202. return EXIT_SUCCESS; /* Really? */
  203. child->argv++;
  204. while (close_me_list)
  205. close((long)llist_pop(&close_me_list));
  206. pseudo_exec(child);
  207. /* never returns */
  208. }
  209. /* built-in 'exit' handler */
  210. static int builtin_exit(struct child_prog *child)
  211. {
  212. if (child->argv[1] == NULL)
  213. exit(EXIT_SUCCESS);
  214. exit(atoi(child->argv[1]));
  215. }
  216. /* built-in 'fg' and 'bg' handler */
  217. static int builtin_fg_bg(struct child_prog *child)
  218. {
  219. int i, jobnum;
  220. struct job *job;
  221. /* If they gave us no args, assume they want the last backgrounded task */
  222. if (!child->argv[1]) {
  223. for (job = child->family->job_list->head; job; job = job->next) {
  224. if (job->jobid == last_jobid) {
  225. goto found;
  226. }
  227. }
  228. bb_error_msg("%s: no current job", child->argv[0]);
  229. return EXIT_FAILURE;
  230. }
  231. if (sscanf(child->argv[1], "%%%d", &jobnum) != 1) {
  232. bb_error_msg(bb_msg_invalid_arg, child->argv[1], child->argv[0]);
  233. return EXIT_FAILURE;
  234. }
  235. for (job = child->family->job_list->head; job; job = job->next) {
  236. if (job->jobid == jobnum) {
  237. goto found;
  238. }
  239. }
  240. bb_error_msg("%s: %d: no such job", child->argv[0], jobnum);
  241. return EXIT_FAILURE;
  242. found:
  243. if (*child->argv[0] == 'f') {
  244. /* Put the job into the foreground. */
  245. tcsetpgrp(shell_terminal, job->pgrp);
  246. child->family->job_list->fg = job;
  247. }
  248. /* Restart the processes in the job */
  249. for (i = 0; i < job->num_progs; i++)
  250. job->progs[i].is_stopped = 0;
  251. job->stopped_progs = 0;
  252. i = kill(- job->pgrp, SIGCONT);
  253. if (i < 0) {
  254. if (errno == ESRCH) {
  255. remove_job(&job_list, job);
  256. } else {
  257. bb_perror_msg("kill (SIGCONT)");
  258. }
  259. }
  260. return EXIT_SUCCESS;
  261. }
  262. /* built-in 'help' handler */
  263. static int builtin_help(struct child_prog UNUSED_PARAM *dummy)
  264. {
  265. const struct built_in_command *x;
  266. printf(
  267. "Built-in commands:\n"
  268. "------------------\n");
  269. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  270. if (x->descr == NULL)
  271. continue;
  272. printf("%s\t%s\n", x->cmd, x->descr);
  273. }
  274. bb_putchar('\n');
  275. return EXIT_SUCCESS;
  276. }
  277. /* built-in 'jobs' handler */
  278. static int builtin_jobs(struct child_prog *child)
  279. {
  280. struct job *job;
  281. const char *status_string;
  282. for (job = child->family->job_list->head; job; job = job->next) {
  283. if (job->running_progs == job->stopped_progs)
  284. status_string = "Stopped";
  285. else
  286. status_string = "Running";
  287. printf(JOB_STATUS_FORMAT, job->jobid, status_string, job->text);
  288. }
  289. return EXIT_SUCCESS;
  290. }
  291. /* built-in 'pwd' handler */
  292. static int builtin_pwd(struct child_prog UNUSED_PARAM *dummy)
  293. {
  294. update_cwd();
  295. puts(cwd);
  296. return EXIT_SUCCESS;
  297. }
  298. /* built-in 'export VAR=value' handler */
  299. static int builtin_export(struct child_prog *child)
  300. {
  301. int res;
  302. char *v = child->argv[1];
  303. if (v == NULL) {
  304. char **e;
  305. for (e = environ; *e; e++) {
  306. puts(*e);
  307. }
  308. return 0;
  309. }
  310. res = putenv(v);
  311. if (res)
  312. bb_perror_msg("export");
  313. #if ENABLE_FEATURE_EDITING_FANCY_PROMPT
  314. if (strncmp(v, "PS1=", 4) == 0)
  315. PS1 = getenv("PS1");
  316. #endif
  317. #if ENABLE_LOCALE_SUPPORT
  318. // TODO: why getenv? "" would be just as good...
  319. if (strncmp(v, "LC_ALL=", 7) == 0)
  320. setlocale(LC_ALL, getenv("LC_ALL"));
  321. if (strncmp(v, "LC_CTYPE=", 9) == 0)
  322. setlocale(LC_CTYPE, getenv("LC_CTYPE"));
  323. #endif
  324. return res;
  325. }
  326. /* built-in 'read VAR' handler */
  327. static int builtin_read(struct child_prog *child)
  328. {
  329. int res = 0, len;
  330. char *s;
  331. char string[MAX_READ];
  332. if (child->argv[1]) {
  333. /* argument (VAR) given: put "VAR=" into buffer */
  334. safe_strncpy(string, child->argv[1], MAX_READ-1);
  335. len = strlen(string);
  336. string[len++] = '=';
  337. string[len] = '\0';
  338. fgets(&string[len], sizeof(string) - len, stdin); /* read string */
  339. res = strlen(string);
  340. if (res > len)
  341. string[--res] = '\0'; /* chomp trailing newline */
  342. /*
  343. ** string should now contain "VAR=<value>"
  344. ** copy it (putenv() won't do that, so we must make sure
  345. ** the string resides in a static buffer!)
  346. */
  347. res = -1;
  348. s = strdup(string);
  349. if (s)
  350. res = putenv(s);
  351. if (res)
  352. bb_perror_msg("read");
  353. } else
  354. fgets(string, sizeof(string), stdin);
  355. return res;
  356. }
  357. /* Built-in '.' handler (read-in and execute commands from file) */
  358. static int builtin_source(struct child_prog *child)
  359. {
  360. FILE *input;
  361. int status;
  362. input = fopen_or_warn(child->argv[1], "r");
  363. if (!input) {
  364. return EXIT_FAILURE;
  365. }
  366. llist_add_to(&close_me_list, (void *)(long)fileno(input));
  367. /* Now run the file */
  368. status = busy_loop(input);
  369. fclose(input);
  370. llist_pop(&close_me_list);
  371. return status;
  372. }
  373. /* built-in 'unset VAR' handler */
  374. static int builtin_unset(struct child_prog *child)
  375. {
  376. if (child->argv[1] == NULL) {
  377. printf(bb_msg_requires_arg, "unset");
  378. return EXIT_FAILURE;
  379. }
  380. unsetenv(child->argv[1]);
  381. return EXIT_SUCCESS;
  382. }
  383. #if ENABLE_LASH_JOB_CONTROL
  384. /* free up all memory from a job */
  385. static void free_job(struct job *cmd)
  386. {
  387. int i;
  388. struct jobset *keep;
  389. for (i = 0; i < cmd->num_progs; i++) {
  390. free(cmd->progs[i].argv);
  391. #if ENABLE_LASH_PIPE_N_REDIRECTS
  392. free(cmd->progs[i].redirects);
  393. #endif
  394. }
  395. free(cmd->progs);
  396. free(cmd->text);
  397. free(cmd->cmdbuf);
  398. keep = cmd->job_list;
  399. memset(cmd, 0, sizeof(struct job));
  400. cmd->job_list = keep;
  401. }
  402. /* remove a job from a jobset */
  403. static void remove_job(struct jobset *j_list, struct job *job)
  404. {
  405. struct job *prevjob;
  406. free_job(job);
  407. if (job == j_list->head) {
  408. j_list->head = job->next;
  409. } else {
  410. prevjob = j_list->head;
  411. while (prevjob->next != job)
  412. prevjob = prevjob->next;
  413. prevjob->next = job->next;
  414. }
  415. if (j_list->head)
  416. last_jobid = j_list->head->jobid;
  417. else
  418. last_jobid = 0;
  419. free(job);
  420. }
  421. /* Checks to see if any background processes have exited -- if they
  422. have, figure out why and see if a job has completed */
  423. static void checkjobs(struct jobset *j_list)
  424. {
  425. struct job *job;
  426. pid_t childpid;
  427. int status;
  428. int prognum = 0;
  429. while ((childpid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
  430. for (job = j_list->head; job; job = job->next) {
  431. prognum = 0;
  432. while (prognum < job->num_progs &&
  433. job->progs[prognum].pid != childpid) prognum++;
  434. if (prognum < job->num_progs)
  435. break;
  436. }
  437. /* This happens on backticked commands */
  438. if (job == NULL)
  439. return;
  440. if (WIFEXITED(status) || WIFSIGNALED(status)) {
  441. /* child exited */
  442. job->running_progs--;
  443. job->progs[prognum].pid = 0;
  444. if (!job->running_progs) {
  445. printf(JOB_STATUS_FORMAT, job->jobid, "Done", job->text);
  446. last_jobid = 0;
  447. remove_job(j_list, job);
  448. }
  449. } else {
  450. /* child stopped */
  451. job->stopped_progs++;
  452. job->progs[prognum].is_stopped = 1;
  453. }
  454. }
  455. if (childpid == -1 && errno != ECHILD)
  456. bb_perror_msg("waitpid");
  457. }
  458. #else
  459. static void checkjobs(struct jobset *j_list)
  460. {
  461. }
  462. static void free_job(struct job *cmd)
  463. {
  464. }
  465. static void remove_job(struct jobset *j_list, struct job *job)
  466. {
  467. }
  468. #endif
  469. #if ENABLE_LASH_PIPE_N_REDIRECTS
  470. /* squirrel != NULL means we squirrel away copies of stdin, stdout,
  471. * and stderr if they are redirected. */
  472. static int setup_redirects(struct child_prog *prog, int squirrel[])
  473. {
  474. int i;
  475. int openfd;
  476. int mode = O_RDONLY;
  477. struct redir_struct *redir = prog->redirects;
  478. for (i = 0; i < prog->num_redirects; i++, redir++) {
  479. switch (redir->type) {
  480. case REDIRECT_INPUT:
  481. mode = O_RDONLY;
  482. break;
  483. case REDIRECT_OVERWRITE:
  484. mode = O_WRONLY | O_CREAT | O_TRUNC;
  485. break;
  486. case REDIRECT_APPEND:
  487. mode = O_WRONLY | O_CREAT | O_APPEND;
  488. break;
  489. }
  490. openfd = open_or_warn(redir->filename, mode);
  491. if (openfd < 0) {
  492. /* this could get lost if stderr has been redirected, but
  493. bash and ash both lose it as well (though zsh doesn't!) */
  494. return 1;
  495. }
  496. if (openfd != redir->fd) {
  497. if (squirrel && redir->fd < 3) {
  498. squirrel[redir->fd] = dup(redir->fd);
  499. close_on_exec_on(squirrel[redir->fd]);
  500. }
  501. dup2(openfd, redir->fd);
  502. close(openfd);
  503. }
  504. }
  505. return 0;
  506. }
  507. static void restore_redirects(int squirrel[])
  508. {
  509. int i, fd;
  510. for (i = 0; i < 3; i++) {
  511. fd = squirrel[i];
  512. if (fd != -1) {
  513. /* No error checking. I sure wouldn't know what
  514. * to do with an error if I found one! */
  515. dup2(fd, i);
  516. close(fd);
  517. }
  518. }
  519. }
  520. #else
  521. static inline int setup_redirects(struct child_prog *prog, int squirrel[])
  522. {
  523. return 0;
  524. }
  525. static inline void restore_redirects(int squirrel[])
  526. {
  527. }
  528. #endif
  529. static inline void cmdedit_set_initial_prompt(void)
  530. {
  531. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  532. PS1 = NULL;
  533. #else
  534. PS1 = getenv("PS1");
  535. if (PS1 == 0)
  536. PS1 = "\\w \\$ ";
  537. #endif
  538. }
  539. static inline const char* setup_prompt_string(void)
  540. {
  541. #if !ENABLE_FEATURE_EDITING_FANCY_PROMPT
  542. /* Set up the prompt */
  543. if (shell_context == 0) {
  544. char *ns;
  545. free((char*)PS1);
  546. ns = xmalloc(strlen(cwd)+4);
  547. sprintf(ns, "%s %c ", cwd, (geteuid() != 0) ? '$': '#');
  548. PS1 = ns;
  549. return ns;
  550. } else {
  551. return PS2;
  552. }
  553. #else
  554. return (shell_context == 0)? PS1 : PS2;
  555. #endif
  556. }
  557. #if ENABLE_FEATURE_EDITING
  558. static line_input_t *line_input_state;
  559. #endif
  560. static int get_command_bufsiz(FILE *source, char *command)
  561. {
  562. const char *prompt_str;
  563. if (source == NULL) {
  564. if (local_pending_command) {
  565. /* a command specified (-c option): return it & mark it done */
  566. strncpy(command, local_pending_command, BUFSIZ);
  567. local_pending_command = NULL;
  568. return 0;
  569. }
  570. return 1;
  571. }
  572. if (source == stdin) {
  573. prompt_str = setup_prompt_string();
  574. #if ENABLE_FEATURE_EDITING
  575. /*
  576. ** enable command line editing only while a command line
  577. ** is actually being read; otherwise, we'll end up bequeathing
  578. ** atexit() handlers and other unwanted stuff to our
  579. ** child processes (rob@sysgo.de)
  580. */
  581. read_line_input(prompt_str, command, BUFSIZ, line_input_state);
  582. return 0;
  583. #else
  584. fputs(prompt_str, stdout);
  585. #endif
  586. }
  587. if (!fgets(command, BUFSIZ - 2, source)) {
  588. if (source == stdin)
  589. bb_putchar('\n');
  590. return 1;
  591. }
  592. return 0;
  593. }
  594. static char * strsep_space(char *string, int * ix)
  595. {
  596. /* Short circuit the trivial case */
  597. if (!string || ! string[*ix])
  598. return NULL;
  599. /* Find the end of the token. */
  600. while (string[*ix] && !isspace(string[*ix]) ) {
  601. (*ix)++;
  602. }
  603. /* Find the end of any whitespace trailing behind
  604. * the token and let that be part of the token */
  605. while (string[*ix] && (isspace)(string[*ix]) ) {
  606. (*ix)++;
  607. }
  608. if (!*ix) {
  609. /* Nothing useful was found */
  610. return NULL;
  611. }
  612. return xstrndup(string, *ix);
  613. }
  614. static int expand_arguments(char *command)
  615. {
  616. static const char out_of_space[] ALIGN1 = "out of space during expansion";
  617. int total_length = 0, length, i, retval, ix = 0;
  618. expand_t expand_result;
  619. char *tmpcmd, *cmd, *cmd_copy;
  620. char *src, *dst, *var;
  621. int flags = GLOB_NOCHECK
  622. #ifdef GLOB_BRACE
  623. | GLOB_BRACE
  624. #endif
  625. #ifdef GLOB_TILDE
  626. | GLOB_TILDE
  627. #endif
  628. ;
  629. /* get rid of the terminating \n */
  630. chomp(command);
  631. /* Fix up escape sequences to be the Real Thing(tm) */
  632. while (command && command[ix]) {
  633. if (command[ix] == '\\') {
  634. const char *tmp = command+ix+1;
  635. command[ix] = bb_process_escape_sequence( &tmp );
  636. memmove(command+ix + 1, tmp, strlen(tmp)+1);
  637. }
  638. ix++;
  639. }
  640. /* Use glob and then fixup environment variables and such */
  641. /* It turns out that glob is very stupid. We have to feed it one word at a
  642. * time since it can't cope with a full string. Here we convert command
  643. * (char*) into cmd (char**, one word per string) */
  644. /* We need a clean copy, so strsep can mess up the copy while
  645. * we write stuff into the original (in a minute) */
  646. cmd = cmd_copy = xstrdup(command);
  647. *command = '\0';
  648. for (ix = 0, tmpcmd = cmd;
  649. (tmpcmd = strsep_space(cmd, &ix)) != NULL; cmd += ix, ix = 0) {
  650. if (*tmpcmd == '\0')
  651. break;
  652. /* we need to trim() the result for glob! */
  653. trim(tmpcmd);
  654. retval = glob(tmpcmd, flags, NULL, &expand_result);
  655. free(tmpcmd); /* Free mem allocated by strsep_space */
  656. if (retval == GLOB_NOSPACE) {
  657. /* Mem may have been allocated... */
  658. globfree(&expand_result);
  659. bb_error_msg(out_of_space);
  660. return FALSE;
  661. } else if (retval != 0) {
  662. /* Some other error. GLOB_NOMATCH shouldn't
  663. * happen because of the GLOB_NOCHECK flag in
  664. * the glob call. */
  665. bb_error_msg("syntax error");
  666. return FALSE;
  667. } else {
  668. /* Convert from char** (one word per string) to a simple char*,
  669. * but don't overflow command which is BUFSIZ in length */
  670. for (i = 0; i < expand_result.gl_pathc; i++) {
  671. length = strlen(expand_result.gl_pathv[i]);
  672. if (total_length+length+1 >= BUFSIZ) {
  673. bb_error_msg(out_of_space);
  674. return FALSE;
  675. }
  676. strcat(command+total_length, " ");
  677. total_length += 1;
  678. strcat(command+total_length, expand_result.gl_pathv[i]);
  679. total_length += length;
  680. }
  681. globfree(&expand_result);
  682. }
  683. }
  684. free(cmd_copy);
  685. trim(command);
  686. /* Now do the shell variable substitutions which
  687. * wordexp can't do for us, namely $? and $! */
  688. src = command;
  689. while ((dst = strchr(src,'$')) != NULL) {
  690. var = NULL;
  691. switch (*(dst+1)) {
  692. case '?':
  693. var = itoa(last_return_code);
  694. break;
  695. case '!':
  696. if (last_bg_pid == -1)
  697. *var = '\0';
  698. else
  699. var = itoa(last_bg_pid);
  700. break;
  701. /* Everything else like $$, $#, $[0-9], etc. should all be
  702. * expanded by wordexp(), so we can in theory skip that stuff
  703. * here, but just to be on the safe side (i.e., since uClibc
  704. * wordexp doesn't do this stuff yet), lets leave it in for
  705. * now. */
  706. case '$':
  707. var = itoa(getpid());
  708. break;
  709. case '#':
  710. var = itoa(global_argc - 1);
  711. break;
  712. case '0':case '1':case '2':case '3':case '4':
  713. case '5':case '6':case '7':case '8':case '9':
  714. {
  715. int ixx = *(dst+1)-48+1;
  716. if (ixx >= global_argc) {
  717. var = '\0';
  718. } else {
  719. var = global_argv[ixx];
  720. }
  721. }
  722. break;
  723. }
  724. if (var) {
  725. /* a single character construction was found, and
  726. * already handled in the case statement */
  727. src = dst + 2;
  728. } else {
  729. /* Looks like an environment variable */
  730. char delim_hold;
  731. int num_skip_chars = 0;
  732. int dstlen = strlen(dst);
  733. /* Is this a ${foo} type variable? */
  734. if (dstlen >= 2 && *(dst+1) == '{') {
  735. src = strchr(dst+1, '}');
  736. num_skip_chars = 1;
  737. } else {
  738. src = dst + 1;
  739. while ((isalnum)(*src) || *src == '_') src++;
  740. }
  741. if (src == NULL) {
  742. src = dst+dstlen;
  743. }
  744. delim_hold = *src;
  745. *src = '\0'; /* temporary */
  746. var = getenv(dst + 1 + num_skip_chars);
  747. *src = delim_hold;
  748. src += num_skip_chars;
  749. }
  750. if (var == NULL) {
  751. /* Seems we got an un-expandable variable. So delete it. */
  752. var = (char*)"";
  753. }
  754. {
  755. int subst_len = strlen(var);
  756. int trail_len = strlen(src);
  757. if (dst+subst_len+trail_len >= command+BUFSIZ) {
  758. bb_error_msg(out_of_space);
  759. return FALSE;
  760. }
  761. /* Move stuff to the end of the string to accommodate
  762. * filling the created gap with the new stuff */
  763. memmove(dst+subst_len, src, trail_len+1);
  764. /* Now copy in the new stuff */
  765. memcpy(dst, var, subst_len);
  766. src = dst+subst_len;
  767. }
  768. }
  769. return TRUE;
  770. }
  771. /* Return cmd->num_progs as 0 if no command is present (e.g. an empty
  772. line). If a valid command is found, command_ptr is set to point to
  773. the beginning of the next command (if the original command had more
  774. then one job associated with it) or NULL if no more commands are
  775. present. */
  776. static int parse_command(char **command_ptr, struct job *job, int *inbg)
  777. {
  778. char *command;
  779. char *return_command = NULL;
  780. char *src, *buf;
  781. int argc_l;
  782. int flag;
  783. int argv_alloced;
  784. char quote = '\0';
  785. struct child_prog *prog;
  786. #if ENABLE_LASH_PIPE_N_REDIRECTS
  787. int i;
  788. char *chptr;
  789. #endif
  790. /* skip leading white space */
  791. *command_ptr = skip_whitespace(*command_ptr);
  792. /* this handles empty lines or leading '#' characters */
  793. if (!**command_ptr || (**command_ptr == '#')) {
  794. job->num_progs = 0;
  795. return 0;
  796. }
  797. *inbg = 0;
  798. job->num_progs = 1;
  799. job->progs = xmalloc(sizeof(*job->progs));
  800. /* We set the argv elements to point inside of this string. The
  801. memory is freed by free_job(). Allocate twice the original
  802. length in case we need to quote every single character.
  803. Getting clean memory relieves us of the task of NULL
  804. terminating things and makes the rest of this look a bit
  805. cleaner (though it is, admittedly, a tad less efficient) */
  806. job->cmdbuf = command = xzalloc(2*strlen(*command_ptr) + 1);
  807. job->text = NULL;
  808. prog = job->progs;
  809. prog->num_redirects = 0;
  810. prog->is_stopped = 0;
  811. prog->family = job;
  812. #if ENABLE_LASH_PIPE_N_REDIRECTS
  813. prog->redirects = NULL;
  814. #endif
  815. argv_alloced = 5;
  816. prog->argv = xmalloc(sizeof(*prog->argv) * argv_alloced);
  817. prog->argv[0] = job->cmdbuf;
  818. flag = argc_l = 0;
  819. buf = command;
  820. src = *command_ptr;
  821. while (*src && !(flag & LASH_OPT_DONE)) {
  822. if (quote == *src) {
  823. quote = '\0';
  824. } else if (quote) {
  825. if (*src == '\\') {
  826. src++;
  827. if (!*src) {
  828. bb_error_msg("character expected after \\");
  829. free_job(job);
  830. return 1;
  831. }
  832. /* in shell, "\'" should yield \' */
  833. if (*src != quote) {
  834. *buf++ = '\\';
  835. *buf++ = '\\';
  836. }
  837. } else if (*src == '*' || *src == '?' || *src == '[' ||
  838. *src == ']') *buf++ = '\\';
  839. *buf++ = *src;
  840. } else if (isspace(*src)) {
  841. if (*prog->argv[argc_l] || (flag & LASH_OPT_SAW_QUOTE)) {
  842. buf++, argc_l++;
  843. /* +1 here leaves room for the NULL which ends argv */
  844. if ((argc_l + 1) == argv_alloced) {
  845. argv_alloced += 5;
  846. prog->argv = xrealloc(prog->argv,
  847. sizeof(*prog->argv) * argv_alloced);
  848. }
  849. prog->argv[argc_l] = buf;
  850. flag ^= LASH_OPT_SAW_QUOTE;
  851. }
  852. } else
  853. switch (*src) {
  854. case '"':
  855. case '\'':
  856. quote = *src;
  857. flag |= LASH_OPT_SAW_QUOTE;
  858. break;
  859. case '#': /* comment */
  860. if (*(src-1)== '$')
  861. *buf++ = *src;
  862. else
  863. flag |= LASH_OPT_DONE;
  864. break;
  865. #if ENABLE_LASH_PIPE_N_REDIRECTS
  866. case '>': /* redirects */
  867. case '<':
  868. i = prog->num_redirects++;
  869. prog->redirects = xrealloc(prog->redirects,
  870. sizeof(*prog->redirects) * (i + 1));
  871. prog->redirects[i].fd = -1;
  872. if (buf != prog->argv[argc_l]) {
  873. /* the stuff before this character may be the file number
  874. being redirected */
  875. prog->redirects[i].fd =
  876. strtol(prog->argv[argc_l], &chptr, 10);
  877. if (*chptr && *prog->argv[argc_l]) {
  878. buf++, argc_l++;
  879. prog->argv[argc_l] = buf;
  880. }
  881. }
  882. if (prog->redirects[i].fd == -1) {
  883. if (*src == '>')
  884. prog->redirects[i].fd = 1;
  885. else
  886. prog->redirects[i].fd = 0;
  887. }
  888. if (*src++ == '>') {
  889. if (*src == '>')
  890. prog->redirects[i].type =
  891. REDIRECT_APPEND, src++;
  892. else
  893. prog->redirects[i].type = REDIRECT_OVERWRITE;
  894. } else {
  895. prog->redirects[i].type = REDIRECT_INPUT;
  896. }
  897. /* This isn't POSIX sh compliant. Oh well. */
  898. chptr = src;
  899. chptr = skip_whitespace(chptr);
  900. if (!*chptr) {
  901. bb_error_msg("file name expected after %c", *(src-1));
  902. free_job(job);
  903. job->num_progs = 0;
  904. return 1;
  905. }
  906. prog->redirects[i].filename = buf;
  907. while (*chptr && !isspace(*chptr))
  908. *buf++ = *chptr++;
  909. src = chptr - 1; /* we src++ later */
  910. prog->argv[argc_l] = ++buf;
  911. break;
  912. case '|': /* pipe */
  913. /* finish this command */
  914. if (*prog->argv[argc_l] || flag & LASH_OPT_SAW_QUOTE)
  915. argc_l++;
  916. if (!argc_l) {
  917. goto empty_command_in_pipe;
  918. }
  919. prog->argv[argc_l] = NULL;
  920. /* and start the next */
  921. job->num_progs++;
  922. job->progs = xrealloc(job->progs,
  923. sizeof(*job->progs) * job->num_progs);
  924. prog = job->progs + (job->num_progs - 1);
  925. prog->num_redirects = 0;
  926. prog->redirects = NULL;
  927. prog->is_stopped = 0;
  928. prog->family = job;
  929. argc_l = 0;
  930. argv_alloced = 5;
  931. prog->argv = xmalloc(sizeof(*prog->argv) * argv_alloced);
  932. prog->argv[0] = ++buf;
  933. src++;
  934. src = skip_whitespace(src);
  935. if (!*src) {
  936. empty_command_in_pipe:
  937. bb_error_msg("empty command in pipe");
  938. free_job(job);
  939. job->num_progs = 0;
  940. return 1;
  941. }
  942. src--; /* we'll ++ it at the end of the loop */
  943. break;
  944. #endif
  945. #if ENABLE_LASH_JOB_CONTROL
  946. case '&': /* background */
  947. *inbg = 1;
  948. /* fallthrough */
  949. #endif
  950. case ';': /* multiple commands */
  951. flag |= LASH_OPT_DONE;
  952. return_command = *command_ptr + (src - *command_ptr) + 1;
  953. break;
  954. case '\\':
  955. src++;
  956. if (!*src) {
  957. bb_error_msg("character expected after \\");
  958. free_job(job);
  959. return 1;
  960. }
  961. if (*src == '*' || *src == '[' || *src == ']'
  962. || *src == '?') *buf++ = '\\';
  963. /* fallthrough */
  964. default:
  965. *buf++ = *src;
  966. }
  967. src++;
  968. }
  969. if (*prog->argv[argc_l] || flag & LASH_OPT_SAW_QUOTE) {
  970. argc_l++;
  971. }
  972. if (!argc_l) {
  973. free_job(job);
  974. return 0;
  975. }
  976. prog->argv[argc_l] = NULL;
  977. if (!return_command) {
  978. job->text = xstrdup(*command_ptr);
  979. } else {
  980. /* This leaves any trailing spaces, which is a bit sloppy */
  981. job->text = xstrndup(*command_ptr, return_command - *command_ptr);
  982. }
  983. *command_ptr = return_command;
  984. return 0;
  985. }
  986. /* Run the child_prog, no matter what kind of command it uses.
  987. */
  988. static int pseudo_exec(struct child_prog *child)
  989. {
  990. const struct built_in_command *x;
  991. /* Check if the command matches any of the non-forking builtins.
  992. * Depending on context, this might be redundant. But it's
  993. * easier to waste a few CPU cycles than it is to figure out
  994. * if this is one of those cases.
  995. */
  996. /* Check if the command matches any of the forking builtins. */
  997. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  998. if (strcmp(child->argv[0], x->cmd) == 0) {
  999. _exit(x->function(child));
  1000. }
  1001. }
  1002. /* Check if the command matches any busybox internal
  1003. * commands ("applets") here. Following discussions from
  1004. * November 2000 on busybox@busybox.net, don't use
  1005. * bb_get_last_path_component_nostrip(). This way explicit
  1006. * (with slashes) filenames will never be interpreted as an
  1007. * applet, just like with builtins. This way the user can
  1008. * override an applet with an explicit filename reference.
  1009. * The only downside to this change is that an explicit
  1010. * /bin/foo invocation will fork and exec /bin/foo, even if
  1011. * /bin/foo is a symlink to busybox.
  1012. */
  1013. if (ENABLE_FEATURE_SH_STANDALONE) {
  1014. run_applet_and_exit(child->argv[0], child->argv);
  1015. }
  1016. execvp(child->argv[0], child->argv);
  1017. /* Do not use bb_perror_msg_and_die() here, since we must not
  1018. * call exit() but should call _exit() instead */
  1019. bb_simple_perror_msg(child->argv[0]);
  1020. _exit(EXIT_FAILURE);
  1021. }
  1022. static void insert_job(struct job *newjob, int inbg)
  1023. {
  1024. struct job *thejob;
  1025. struct jobset *j_list = newjob->job_list;
  1026. /* find the ID for thejob to use */
  1027. newjob->jobid = 1;
  1028. for (thejob = j_list->head; thejob; thejob = thejob->next)
  1029. if (thejob->jobid >= newjob->jobid)
  1030. newjob->jobid = thejob->jobid + 1;
  1031. /* add thejob to the list of running jobs */
  1032. if (!j_list->head) {
  1033. thejob = j_list->head = xmalloc(sizeof(*thejob));
  1034. } else {
  1035. for (thejob = j_list->head; thejob->next; thejob = thejob->next) /* nothing */;
  1036. thejob->next = xmalloc(sizeof(*thejob));
  1037. thejob = thejob->next;
  1038. }
  1039. *thejob = *newjob; /* physically copy the struct job */
  1040. thejob->next = NULL;
  1041. thejob->running_progs = thejob->num_progs;
  1042. thejob->stopped_progs = 0;
  1043. #if ENABLE_LASH_JOB_CONTROL
  1044. if (inbg) {
  1045. /* we don't wait for background thejobs to return -- append it
  1046. to the list of backgrounded thejobs and leave it alone */
  1047. printf("[%d] %d\n", thejob->jobid,
  1048. newjob->progs[newjob->num_progs - 1].pid);
  1049. last_jobid = newjob->jobid;
  1050. last_bg_pid = newjob->progs[newjob->num_progs - 1].pid;
  1051. } else {
  1052. newjob->job_list->fg = thejob;
  1053. /* move the new process group into the foreground */
  1054. /* Ignore errors since child could have already exited */
  1055. tcsetpgrp(shell_terminal, newjob->pgrp);
  1056. }
  1057. #endif
  1058. }
  1059. static int run_command(struct job *newjob, int inbg, int outpipe[2])
  1060. {
  1061. /* struct job *thejob; */
  1062. int i;
  1063. int nextin, nextout;
  1064. int pipefds[2]; /* pipefd[0] is for reading */
  1065. const struct built_in_command *x;
  1066. struct child_prog *child;
  1067. nextin = 0;
  1068. for (i = 0; i < newjob->num_progs; i++) {
  1069. child = &(newjob->progs[i]);
  1070. nextout = 1;
  1071. if ((i + 1) < newjob->num_progs) {
  1072. xpipe(pipefds);
  1073. nextout = pipefds[1];
  1074. } else if (outpipe[1] != -1) {
  1075. nextout = outpipe[1];
  1076. }
  1077. /* Check if the command matches any non-forking builtins,
  1078. * but only if this is a simple command.
  1079. * Non-forking builtins within pipes have to fork anyway,
  1080. * and are handled in pseudo_exec. "echo foo | read bar"
  1081. * is doomed to failure, and doesn't work on bash, either.
  1082. */
  1083. if (newjob->num_progs == 1) {
  1084. int rcode;
  1085. int squirrel[] = {-1, -1, -1};
  1086. /* Check if the command sets an environment variable. */
  1087. if (strchr(child->argv[0], '=') != NULL) {
  1088. child->argv[1] = child->argv[0];
  1089. return builtin_export(child);
  1090. }
  1091. for (x = bltins; x <= &VEC_LAST(bltins); x++) {
  1092. if (strcmp(child->argv[0], x->cmd) == 0) {
  1093. setup_redirects(child, squirrel);
  1094. rcode = x->function(child);
  1095. restore_redirects(squirrel);
  1096. return rcode;
  1097. }
  1098. }
  1099. #if ENABLE_FEATURE_SH_STANDALONE
  1100. {
  1101. int a = find_applet_by_name(child->argv[i]);
  1102. if (a >= 0 && APPLET_IS_NOFORK(a)) {
  1103. setup_redirects(child, squirrel);
  1104. rcode = run_nofork_applet(a, child->argv + i);
  1105. restore_redirects(squirrel);
  1106. return rcode;
  1107. }
  1108. }
  1109. #endif
  1110. }
  1111. #if BB_MMU
  1112. child->pid = fork();
  1113. #else
  1114. child->pid = vfork();
  1115. #endif
  1116. if (!child->pid) {
  1117. /* Set the handling for job control signals back to the default. */
  1118. signal(SIGINT, SIG_DFL);
  1119. signal(SIGQUIT, SIG_DFL);
  1120. signal(SIGTSTP, SIG_DFL);
  1121. signal(SIGTTIN, SIG_DFL);
  1122. signal(SIGTTOU, SIG_DFL);
  1123. signal(SIGCHLD, SIG_DFL);
  1124. /* Close all open filehandles. */
  1125. while (close_me_list)
  1126. close((long)llist_pop(&close_me_list));
  1127. if (outpipe[1] != -1) {
  1128. close(outpipe[0]);
  1129. }
  1130. if (nextin != 0) {
  1131. dup2(nextin, 0);
  1132. close(nextin);
  1133. }
  1134. if (nextout != 1) {
  1135. dup2(nextout, 1);
  1136. dup2(nextout, 2); /* Really? */
  1137. close(nextout);
  1138. close(pipefds[0]);
  1139. }
  1140. /* explicit redirects override pipes */
  1141. setup_redirects(child,NULL);
  1142. pseudo_exec(child);
  1143. }
  1144. if (outpipe[1] != -1) {
  1145. close(outpipe[1]);
  1146. }
  1147. /* put our child in the process group whose leader is the
  1148. first process in this pipe */
  1149. setpgid(child->pid, newjob->progs[0].pid);
  1150. if (nextin != 0)
  1151. close(nextin);
  1152. if (nextout != 1)
  1153. close(nextout);
  1154. /* If there isn't another process, nextin is garbage
  1155. but it doesn't matter */
  1156. nextin = pipefds[0];
  1157. }
  1158. newjob->pgrp = newjob->progs[0].pid;
  1159. insert_job(newjob, inbg);
  1160. return 0;
  1161. }
  1162. static int busy_loop(FILE *input)
  1163. {
  1164. char *command;
  1165. char *next_command = NULL;
  1166. struct job newjob;
  1167. int i;
  1168. int inbg = 0;
  1169. int status;
  1170. #if ENABLE_LASH_JOB_CONTROL
  1171. pid_t parent_pgrp;
  1172. /* save current owner of TTY so we can restore it on exit */
  1173. parent_pgrp = tcgetpgrp(shell_terminal);
  1174. #endif
  1175. newjob.job_list = &job_list;
  1176. newjob.job_context = DEFAULT_CONTEXT;
  1177. command = xzalloc(BUFSIZ);
  1178. while (1) {
  1179. if (!job_list.fg) {
  1180. /* no job is in the foreground */
  1181. /* see if any background processes have exited */
  1182. checkjobs(&job_list);
  1183. if (!next_command) {
  1184. if (get_command_bufsiz(input, command))
  1185. break;
  1186. next_command = command;
  1187. }
  1188. if (!expand_arguments(next_command)) {
  1189. free(command);
  1190. command = xzalloc(BUFSIZ);
  1191. next_command = NULL;
  1192. continue;
  1193. }
  1194. if (!parse_command(&next_command, &newjob, &inbg) &&
  1195. newjob.num_progs) {
  1196. int pipefds[2] = { -1, -1 };
  1197. debug_printf("job=%p fed to run_command by busy_loop()'\n",
  1198. &newjob);
  1199. run_command(&newjob, inbg, pipefds);
  1200. }
  1201. else {
  1202. free(command);
  1203. command = xzalloc(BUFSIZ);
  1204. next_command = NULL;
  1205. }
  1206. } else {
  1207. /* a job is running in the foreground; wait for it */
  1208. i = 0;
  1209. while (!job_list.fg->progs[i].pid ||
  1210. job_list.fg->progs[i].is_stopped == 1) i++;
  1211. if (waitpid(job_list.fg->progs[i].pid, &status, WUNTRACED) < 0) {
  1212. if (errno != ECHILD) {
  1213. bb_perror_msg_and_die("waitpid(%d)", job_list.fg->progs[i].pid);
  1214. }
  1215. }
  1216. if (WIFEXITED(status) || WIFSIGNALED(status)) {
  1217. /* the child exited */
  1218. job_list.fg->running_progs--;
  1219. job_list.fg->progs[i].pid = 0;
  1220. last_return_code = WEXITSTATUS(status);
  1221. if (!job_list.fg->running_progs) {
  1222. /* child exited */
  1223. remove_job(&job_list, job_list.fg);
  1224. job_list.fg = NULL;
  1225. }
  1226. }
  1227. #if ENABLE_LASH_JOB_CONTROL
  1228. else {
  1229. /* the child was stopped */
  1230. job_list.fg->stopped_progs++;
  1231. job_list.fg->progs[i].is_stopped = 1;
  1232. if (job_list.fg->stopped_progs == job_list.fg->running_progs) {
  1233. printf("\n" JOB_STATUS_FORMAT, job_list.fg->jobid,
  1234. "Stopped", job_list.fg->text);
  1235. job_list.fg = NULL;
  1236. }
  1237. }
  1238. if (!job_list.fg) {
  1239. /* move the shell to the foreground */
  1240. /* suppress messages when run from /linuxrc mag@sysgo.de */
  1241. if (tcsetpgrp(shell_terminal, getpgrp()) && errno != ENOTTY)
  1242. bb_perror_msg("tcsetpgrp");
  1243. }
  1244. #endif
  1245. }
  1246. }
  1247. free(command);
  1248. #if ENABLE_LASH_JOB_CONTROL
  1249. /* return controlling TTY back to parent process group before exiting */
  1250. if (tcsetpgrp(shell_terminal, parent_pgrp) && errno != ENOTTY)
  1251. bb_perror_msg("tcsetpgrp");
  1252. #endif
  1253. /* return exit status if called with "-c" */
  1254. if (input == NULL && WIFEXITED(status))
  1255. return WEXITSTATUS(status);
  1256. return 0;
  1257. }
  1258. #if ENABLE_FEATURE_CLEAN_UP
  1259. static void free_memory(void)
  1260. {
  1261. free(cwd);
  1262. if (job_list.fg && !job_list.fg->running_progs) {
  1263. remove_job(&job_list, job_list.fg);
  1264. }
  1265. }
  1266. #else
  1267. void free_memory(void);
  1268. #endif
  1269. #if ENABLE_LASH_JOB_CONTROL
  1270. /* Make sure we have a controlling tty. If we get started under a job
  1271. * aware app (like bash for example), make sure we are now in charge so
  1272. * we don't fight over who gets the foreground */
  1273. static void setup_job_control(void)
  1274. {
  1275. int status;
  1276. pid_t shell_pgrp;
  1277. /* Loop until we are in the foreground. */
  1278. while ((status = tcgetpgrp(shell_terminal)) >= 0) {
  1279. shell_pgrp = getpgrp();
  1280. if (status == shell_pgrp) {
  1281. break;
  1282. }
  1283. kill(- shell_pgrp, SIGTTIN);
  1284. }
  1285. /* Ignore interactive and job-control signals. */
  1286. signal(SIGINT, SIG_IGN);
  1287. signal(SIGQUIT, SIG_IGN);
  1288. signal(SIGTSTP, SIG_IGN);
  1289. signal(SIGTTIN, SIG_IGN);
  1290. signal(SIGTTOU, SIG_IGN);
  1291. signal(SIGCHLD, SIG_IGN);
  1292. /* Put ourselves in our own process group. */
  1293. setsid();
  1294. shell_pgrp = getpid();
  1295. setpgid(shell_pgrp, shell_pgrp);
  1296. /* Grab control of the terminal. */
  1297. tcsetpgrp(shell_terminal, shell_pgrp);
  1298. }
  1299. #else
  1300. static inline void setup_job_control(void)
  1301. {
  1302. }
  1303. #endif
  1304. int lash_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1305. int lash_main(int argc, char **argv)
  1306. {
  1307. unsigned opt;
  1308. FILE *input = stdin;
  1309. global_argc = argc;
  1310. global_argv = argv;
  1311. #if ENABLE_FEATURE_EDITING
  1312. line_input_state = new_line_input_t(FOR_SHELL);
  1313. #endif
  1314. /* These variables need re-initializing when recursing */
  1315. last_jobid = 0;
  1316. close_me_list = NULL;
  1317. job_list.head = NULL;
  1318. job_list.fg = NULL;
  1319. last_return_code = 1;
  1320. if (global_argv[0] && global_argv[0][0] == '-') {
  1321. FILE *prof_input;
  1322. prof_input = fopen_for_read("/etc/profile");
  1323. if (prof_input) {
  1324. llist_add_to(&close_me_list, (void *)(long)fileno(prof_input));
  1325. /* Now run the file */
  1326. busy_loop(prof_input);
  1327. fclose_if_not_stdin(prof_input);
  1328. llist_pop(&close_me_list);
  1329. }
  1330. }
  1331. opt = getopt32(argv, "+ic:", &local_pending_command);
  1332. #define LASH_OPT_i (1<<0)
  1333. #define LASH_OPT_c (1<<1)
  1334. if (opt & LASH_OPT_c) {
  1335. input = NULL;
  1336. optind++;
  1337. global_argv += optind;
  1338. }
  1339. /* A shell is interactive if the `-i' flag was given, or if all of
  1340. * the following conditions are met:
  1341. * no -c command
  1342. * no arguments remaining or the -s flag given
  1343. * standard input is a terminal
  1344. * standard output is a terminal
  1345. * Refer to Posix.2, the description of the `sh' utility. */
  1346. if (global_argv[optind] == NULL && input == stdin
  1347. && isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)
  1348. ) {
  1349. opt |= LASH_OPT_i;
  1350. }
  1351. setup_job_control();
  1352. if (opt & LASH_OPT_i) {
  1353. /* Looks like they want an interactive shell */
  1354. if (!ENABLE_FEATURE_SH_EXTRA_QUIET) {
  1355. printf("\n\n%s built-in shell (lash)\n"
  1356. "Enter 'help' for a list of built-in commands.\n\n",
  1357. bb_banner);
  1358. }
  1359. } else if (!local_pending_command && global_argv[optind]) {
  1360. //printf( "optind=%d argv[optind]='%s'\n", optind, argv[optind]);
  1361. input = xfopen_for_read(global_argv[optind]);
  1362. /* be lazy, never mark this closed */
  1363. llist_add_to(&close_me_list, (void *)(long)fileno(input));
  1364. }
  1365. /* initialize the cwd -- this is never freed...*/
  1366. update_cwd();
  1367. if (ENABLE_FEATURE_CLEAN_UP) atexit(free_memory);
  1368. if (ENABLE_FEATURE_EDITING) cmdedit_set_initial_prompt();
  1369. else PS1 = NULL;
  1370. return busy_loop(input);
  1371. }