main.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. #include "GlobalState.h"
  2. #include "LineEditor.h"
  3. #include "Parser.h"
  4. #include <AK/FileSystemPath.h>
  5. #include <AK/StringBuilder.h>
  6. #include <LibCore/CDirIterator.h>
  7. #include <LibCore/CElapsedTimer.h>
  8. #include <LibCore/CFile.h>
  9. #include <errno.h>
  10. #include <fcntl.h>
  11. #include <pwd.h>
  12. #include <signal.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <sys/mman.h>
  17. #include <sys/stat.h>
  18. #include <sys/utsname.h>
  19. #include <sys/wait.h>
  20. #include <termios.h>
  21. #include <unistd.h>
  22. #define SH_DEBUG
  23. GlobalState g;
  24. static LineEditor editor;
  25. static int run_command(const String&);
  26. static String prompt()
  27. {
  28. if (g.uid == 0)
  29. return "# ";
  30. StringBuilder builder;
  31. builder.appendf("\033]0;%s@%s:%s\007", g.username.characters(), g.hostname, g.cwd.characters());
  32. builder.appendf("\033[31;1m%s\033[0m@\033[37;1m%s\033[0m:\033[32;1m%s\033[0m$> ", g.username.characters(), g.hostname, g.cwd.characters());
  33. return builder.to_string();
  34. }
  35. static int sh_pwd(int, char**)
  36. {
  37. printf("%s\n", g.cwd.characters());
  38. return 0;
  39. }
  40. static int sh_exit(int, char**)
  41. {
  42. printf("Good-bye!\n");
  43. exit(0);
  44. return 0;
  45. }
  46. static int sh_export(int argc, char** argv)
  47. {
  48. if (argc == 1) {
  49. for (int i = 0; environ[i]; ++i)
  50. puts(environ[i]);
  51. return 0;
  52. }
  53. auto parts = String(argv[1]).split('=');
  54. if (parts.size() != 2) {
  55. fprintf(stderr, "usage: export variable=value\n");
  56. return 1;
  57. }
  58. return setenv(parts[0].characters(), parts[1].characters(), 1);
  59. }
  60. static int sh_unset(int argc, char** argv)
  61. {
  62. if (argc != 2) {
  63. fprintf(stderr, "usage: unset variable\n");
  64. return 1;
  65. }
  66. unsetenv(argv[1]);
  67. return 0;
  68. }
  69. static int sh_cd(int argc, char** argv)
  70. {
  71. char pathbuf[PATH_MAX];
  72. if (argc == 1) {
  73. strcpy(pathbuf, g.home.characters());
  74. } else {
  75. if (strcmp(argv[1], "-") == 0) {
  76. char* oldpwd = getenv("OLDPWD");
  77. if (oldpwd == nullptr)
  78. return 1;
  79. size_t len = strlen(oldpwd);
  80. ASSERT(len + 1 <= PATH_MAX);
  81. memcpy(pathbuf, oldpwd, len + 1);
  82. } else if (argv[1][0] == '/') {
  83. memcpy(pathbuf, argv[1], strlen(argv[1]) + 1);
  84. } else {
  85. sprintf(pathbuf, "%s/%s", g.cwd.characters(), argv[1]);
  86. }
  87. }
  88. FileSystemPath canonical_path(pathbuf);
  89. if (!canonical_path.is_valid()) {
  90. printf("FileSystemPath failed to canonicalize '%s'\n", pathbuf);
  91. return 1;
  92. }
  93. const char* path = canonical_path.string().characters();
  94. struct stat st;
  95. int rc = stat(path, &st);
  96. if (rc < 0) {
  97. printf("stat(%s) failed: %s\n", path, strerror(errno));
  98. return 1;
  99. }
  100. if (!S_ISDIR(st.st_mode)) {
  101. printf("Not a directory: %s\n", path);
  102. return 1;
  103. }
  104. rc = chdir(path);
  105. if (rc < 0) {
  106. printf("chdir(%s) failed: %s\n", path, strerror(errno));
  107. return 1;
  108. }
  109. setenv("OLDPWD", g.cwd.characters(), 1);
  110. g.cwd = canonical_path.string();
  111. setenv("PWD", g.cwd.characters(), 1);
  112. return 0;
  113. }
  114. static int sh_history(int, char**)
  115. {
  116. for (int i = 0; i < editor.history().size(); ++i) {
  117. printf("%6d %s\n", i, editor.history()[i].characters());
  118. }
  119. return 0;
  120. }
  121. static int sh_time(int argc, char** argv)
  122. {
  123. if (argc == 1) {
  124. printf("usage: time <command>\n");
  125. return 0;
  126. }
  127. StringBuilder builder;
  128. for (int i = 1; i < argc; ++i) {
  129. builder.append(argv[i]);
  130. if (i != argc - 1)
  131. builder.append(' ');
  132. }
  133. CElapsedTimer timer;
  134. timer.start();
  135. int exit_code = run_command(builder.to_string());
  136. printf("Time: %d ms\n", timer.elapsed());
  137. return exit_code;
  138. }
  139. static int sh_umask(int argc, char** argv)
  140. {
  141. if (argc == 1) {
  142. mode_t old_mask = umask(0);
  143. printf("%#o\n", old_mask);
  144. umask(old_mask);
  145. return 0;
  146. }
  147. if (argc == 2) {
  148. unsigned mask;
  149. int matches = sscanf(argv[1], "%o", &mask);
  150. if (matches == 1) {
  151. umask(mask);
  152. return 0;
  153. }
  154. }
  155. printf("usage: umask <octal-mask>\n");
  156. return 0;
  157. }
  158. static int sh_popd(int argc, char** argv)
  159. {
  160. if (g.directory_stack.size() <= 1) {
  161. fprintf(stderr, "Shell: popd: directory stack empty\n");
  162. return 1;
  163. }
  164. bool should_switch = true;
  165. String path = g.directory_stack.take_last();
  166. // When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory.
  167. if (argc == 1) {
  168. int rc = chdir(path.characters());
  169. if (rc < 0) {
  170. fprintf(stderr, "chdir(%s) failed: %s", path.characters(), strerror(errno));
  171. return 1;
  172. }
  173. g.cwd = path;
  174. return 0;
  175. }
  176. for (int i = 1; i < argc; i++) {
  177. const char* arg = argv[i];
  178. if (!strcmp(arg, "-n")) {
  179. should_switch = false;
  180. }
  181. }
  182. FileSystemPath canonical_path(path.characters());
  183. if (!canonical_path.is_valid()) {
  184. fprintf(stderr, "FileSystemPath failed to canonicalize '%s'\n", path.characters());
  185. return 1;
  186. }
  187. const char* real_path = canonical_path.string().characters();
  188. struct stat st;
  189. int rc = stat(real_path, &st);
  190. if (rc < 0) {
  191. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  192. return 1;
  193. }
  194. if (!S_ISDIR(st.st_mode)) {
  195. fprintf(stderr, "Not a directory: %s\n", real_path);
  196. return 1;
  197. }
  198. if (should_switch) {
  199. int rc = chdir(real_path);
  200. if (rc < 0) {
  201. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  202. return 1;
  203. }
  204. g.cwd = canonical_path.string();
  205. }
  206. return 0;
  207. }
  208. static int sh_pushd(int argc, char** argv)
  209. {
  210. StringBuilder path_builder;
  211. bool should_switch = true;
  212. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  213. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  214. if (argc == 1) {
  215. if (g.directory_stack.size() < 2) {
  216. fprintf(stderr, "pushd: no other directory\n");
  217. return 1;
  218. }
  219. String dir1 = g.directory_stack.take_first();
  220. String dir2 = g.directory_stack.take_first();
  221. g.directory_stack.insert(0, dir2);
  222. g.directory_stack.insert(1, dir1);
  223. int rc = chdir(dir2.characters());
  224. if (rc < 0) {
  225. fprintf(stderr, "chdir(%s) failed: %s", dir2.characters(), strerror(errno));
  226. return 1;
  227. }
  228. g.cwd = dir2;
  229. return 0;
  230. }
  231. // Let's assume the user's typed in 'pushd <dir>'
  232. if (argc == 2) {
  233. g.directory_stack.append(g.cwd.characters());
  234. if (argv[1][0] == '/') {
  235. path_builder.append(argv[1]);
  236. }
  237. else {
  238. path_builder.appendf("%s/%s", g.cwd.characters(), argv[1]);
  239. }
  240. } else if (argc == 3) {
  241. g.directory_stack.append(g.cwd.characters());
  242. for (int i = 1; i < argc; i++) {
  243. const char* arg = argv[i];
  244. if (arg[0] != '-') {
  245. if (arg[0] == '/') {
  246. path_builder.append(arg);
  247. }
  248. else
  249. path_builder.appendf("%s/%s", g.cwd.characters(), arg);
  250. }
  251. if (!strcmp(arg, "-n"))
  252. should_switch = false;
  253. }
  254. }
  255. FileSystemPath canonical_path(path_builder.to_string());
  256. if (!canonical_path.is_valid()) {
  257. fprintf(stderr, "FileSystemPath failed to canonicalize '%s'\n", path_builder.to_string().characters());
  258. return 1;
  259. }
  260. const char* real_path = canonical_path.string().characters();
  261. struct stat st;
  262. int rc = stat(real_path, &st);
  263. if (rc < 0) {
  264. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  265. return 1;
  266. }
  267. if (!S_ISDIR(st.st_mode)) {
  268. fprintf(stderr, "Not a directory: %s\n", real_path);
  269. return 1;
  270. }
  271. if (should_switch) {
  272. int rc = chdir(real_path);
  273. if (rc < 0) {
  274. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  275. return 1;
  276. }
  277. g.cwd = canonical_path.string();
  278. }
  279. return 0;
  280. }
  281. static int sh_dirs(int argc, char** argv)
  282. {
  283. // The first directory in the stack is ALWAYS the current directory
  284. g.directory_stack.at(0) = g.cwd.characters();
  285. if (argc == 1) {
  286. for (String dir : g.directory_stack)
  287. printf("%s ", dir.characters());
  288. printf("\n");
  289. return 0;
  290. }
  291. bool printed = false;
  292. for (int i = 0; i < argc; i++) {
  293. const char* arg = argv[i];
  294. if (!strcmp(arg, "-c")) {
  295. for (int i = 1; i < g.directory_stack.size(); i++)
  296. g.directory_stack.remove(i);
  297. printed = true;
  298. continue;
  299. }
  300. if (!strcmp(arg, "-p") && !printed) {
  301. for (auto& directory : g.directory_stack)
  302. printf("%s\n", directory.characters());
  303. printed = true;
  304. continue;
  305. }
  306. if (!strcmp(arg, "-v") && !printed) {
  307. int idx = 0;
  308. for (auto& directory : g.directory_stack) {
  309. printf("%d %s\n", idx++, directory.characters());
  310. }
  311. printed = true;
  312. continue;
  313. }
  314. }
  315. return 0;
  316. }
  317. static bool handle_builtin(int argc, char** argv, int& retval)
  318. {
  319. if (argc == 0)
  320. return false;
  321. if (!strcmp(argv[0], "cd")) {
  322. retval = sh_cd(argc, argv);
  323. return true;
  324. }
  325. if (!strcmp(argv[0], "pwd")) {
  326. retval = sh_pwd(argc, argv);
  327. return true;
  328. }
  329. if (!strcmp(argv[0], "exit")) {
  330. retval = sh_exit(argc, argv);
  331. return true;
  332. }
  333. if (!strcmp(argv[0], "export")) {
  334. retval = sh_export(argc, argv);
  335. return true;
  336. }
  337. if (!strcmp(argv[0], "unset")) {
  338. retval = sh_unset(argc, argv);
  339. return true;
  340. }
  341. if (!strcmp(argv[0], "history")) {
  342. retval = sh_history(argc, argv);
  343. return true;
  344. }
  345. if (!strcmp(argv[0], "umask")) {
  346. retval = sh_umask(argc, argv);
  347. return true;
  348. }
  349. if (!strcmp(argv[0], "dirs")) {
  350. retval = sh_dirs(argc, argv);
  351. return true;
  352. }
  353. if (!strcmp(argv[0], "pushd")) {
  354. retval = sh_pushd(argc, argv);
  355. return true;
  356. }
  357. if (!strcmp(argv[0], "popd")) {
  358. retval = sh_popd(argc, argv);
  359. return true;
  360. }
  361. if (!strcmp(argv[0], "time")) {
  362. retval = sh_time(argc, argv);
  363. return true;
  364. }
  365. return false;
  366. }
  367. class FileDescriptionCollector {
  368. public:
  369. FileDescriptionCollector() {}
  370. ~FileDescriptionCollector() { collect(); }
  371. void collect()
  372. {
  373. for (auto fd : m_fds)
  374. close(fd);
  375. m_fds.clear();
  376. }
  377. void add(int fd) { m_fds.append(fd); }
  378. private:
  379. Vector<int, 32> m_fds;
  380. };
  381. struct CommandTimer {
  382. CommandTimer()
  383. {
  384. timer.start();
  385. }
  386. ~CommandTimer()
  387. {
  388. dbgprintf("sh: command finished in %d ms\n", timer.elapsed());
  389. }
  390. CElapsedTimer timer;
  391. };
  392. static bool is_glob(const StringView& s)
  393. {
  394. for (int i = 0; i < s.length(); i++) {
  395. char c = s.characters_without_null_termination()[i];
  396. if (c == '*' || c == '?')
  397. return true;
  398. }
  399. return false;
  400. }
  401. static Vector<StringView> split_path(const StringView& path)
  402. {
  403. Vector<StringView> parts;
  404. ssize_t substart = 0;
  405. for (ssize_t i = 0; i < path.length(); i++) {
  406. char ch = path.characters_without_null_termination()[i];
  407. if (ch != '/')
  408. continue;
  409. ssize_t sublen = i - substart;
  410. if (sublen != 0)
  411. parts.append(path.substring_view(substart, sublen));
  412. parts.append(path.substring_view(i, 1));
  413. substart = i + 1;
  414. }
  415. ssize_t taillen = path.length() - substart;
  416. if (taillen != 0)
  417. parts.append(path.substring_view(substart, taillen));
  418. return parts;
  419. }
  420. static Vector<String> expand_globs(const StringView& path, const StringView& base)
  421. {
  422. auto parts = split_path(path);
  423. StringBuilder builder;
  424. builder.append(base);
  425. Vector<String> res;
  426. for (int i = 0; i < parts.size(); ++i) {
  427. auto& part = parts[i];
  428. if (!is_glob(part)) {
  429. builder.append(part);
  430. continue;
  431. }
  432. // Found a glob.
  433. String new_base = builder.to_string();
  434. StringView new_base_v = new_base;
  435. if (new_base_v.is_empty())
  436. new_base_v = ".";
  437. CDirIterator di(new_base_v, CDirIterator::NoFlags);
  438. if (di.has_error()) {
  439. return res;
  440. }
  441. while (di.has_next()) {
  442. String name = di.next_path();
  443. // Dotfiles have to be explicitly requested
  444. if (name[0] == '.' && part[0] != '.')
  445. continue;
  446. // And even if they are, skip . and ..
  447. if (name == "." || name == "..")
  448. continue;
  449. if (name.matches(part, String::CaseSensitivity::CaseSensitive)) {
  450. StringBuilder nested_base;
  451. nested_base.append(new_base);
  452. nested_base.append(name);
  453. StringView remaining_path = path.substring_view_starting_after_substring(part);
  454. Vector<String> nested_res = expand_globs(remaining_path, nested_base.to_string());
  455. for (auto& s : nested_res)
  456. res.append(s);
  457. }
  458. }
  459. return res;
  460. }
  461. // Found no globs.
  462. String new_path = builder.to_string();
  463. if (access(new_path.characters(), F_OK) == 0)
  464. res.append(new_path);
  465. return res;
  466. }
  467. static Vector<String> expand_parameters(const StringView& param)
  468. {
  469. bool is_variable = param.length() > 1 && param[0] == '$';
  470. if (!is_variable)
  471. return { param };
  472. String variable_name = String(param.substring_view(1, param.length() - 1));
  473. if (variable_name == "?")
  474. return { String::number(g.last_return_code) };
  475. else if (variable_name == "$")
  476. return { String::number(getpid()) };
  477. char* env_value = getenv(variable_name.characters());
  478. if (env_value == nullptr)
  479. return { "" };
  480. Vector<String> res;
  481. String str_env_value = String(env_value);
  482. const auto& split_text = str_env_value.split_view(' ');
  483. for (auto& part : split_text)
  484. res.append(part);
  485. return res;
  486. }
  487. static Vector<String> process_arguments(const Vector<String>& args)
  488. {
  489. Vector<String> argv_string;
  490. for (auto& arg : args) {
  491. // This will return the text passed in if it wasn't a variable
  492. // This lets us just loop over its values
  493. auto expanded_parameters = expand_parameters(arg);
  494. for (auto& exp_arg : expanded_parameters) {
  495. auto expanded_globs = expand_globs(exp_arg, "");
  496. for (auto& path : expanded_globs)
  497. argv_string.append(path);
  498. if (expanded_globs.is_empty())
  499. argv_string.append(exp_arg);
  500. }
  501. }
  502. return argv_string;
  503. }
  504. static int run_command(const String& cmd)
  505. {
  506. if (cmd.is_empty())
  507. return 0;
  508. if (cmd.starts_with("#"))
  509. return 0;
  510. auto commands = Parser(cmd).parse();
  511. #ifdef SH_DEBUG
  512. for (auto& command : commands) {
  513. for (int i = 0; i < command.subcommands.size(); ++i) {
  514. for (int j = 0; j < i; ++j)
  515. dbgprintf(" ");
  516. for (auto& arg : command.subcommands[i].args) {
  517. dbgprintf("<%s> ", arg.characters());
  518. }
  519. dbgprintf("\n");
  520. for (auto& redirecton : command.subcommands[i].redirections) {
  521. for (int j = 0; j < i; ++j)
  522. dbgprintf(" ");
  523. dbgprintf(" ");
  524. switch (redirecton.type) {
  525. case Redirection::Pipe:
  526. dbgprintf("Pipe\n");
  527. break;
  528. case Redirection::FileRead:
  529. dbgprintf("fd:%d = FileRead: %s\n", redirecton.fd, redirecton.path.characters());
  530. break;
  531. case Redirection::FileWrite:
  532. dbgprintf("fd:%d = FileWrite: %s\n", redirecton.fd, redirecton.path.characters());
  533. break;
  534. case Redirection::FileWriteAppend:
  535. dbgprintf("fd:%d = FileWriteAppend: %s\n", redirecton.fd, redirecton.path.characters());
  536. break;
  537. default:
  538. break;
  539. }
  540. }
  541. }
  542. dbgprintf("\n");
  543. }
  544. #endif
  545. struct termios trm;
  546. tcgetattr(0, &trm);
  547. struct SpawnedProcess {
  548. String name;
  549. pid_t pid;
  550. };
  551. int return_value = 0;
  552. for (auto& command : commands) {
  553. if (command.subcommands.is_empty())
  554. continue;
  555. FileDescriptionCollector fds;
  556. for (int i = 0; i < command.subcommands.size(); ++i) {
  557. auto& subcommand = command.subcommands[i];
  558. for (auto& redirection : subcommand.redirections) {
  559. switch (redirection.type) {
  560. case Redirection::Pipe: {
  561. int pipefd[2];
  562. int rc = pipe(pipefd);
  563. if (rc < 0) {
  564. perror("pipe");
  565. return 1;
  566. }
  567. subcommand.rewirings.append({ STDOUT_FILENO, pipefd[1] });
  568. auto& next_command = command.subcommands[i + 1];
  569. next_command.rewirings.append({ STDIN_FILENO, pipefd[0] });
  570. fds.add(pipefd[0]);
  571. fds.add(pipefd[1]);
  572. break;
  573. }
  574. case Redirection::FileWriteAppend: {
  575. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666);
  576. if (fd < 0) {
  577. perror("open");
  578. return 1;
  579. }
  580. subcommand.rewirings.append({ redirection.fd, fd });
  581. fds.add(fd);
  582. break;
  583. }
  584. case Redirection::FileWrite: {
  585. int fd = open(redirection.path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  586. if (fd < 0) {
  587. perror("open");
  588. return 1;
  589. }
  590. subcommand.rewirings.append({ redirection.fd, fd });
  591. fds.add(fd);
  592. break;
  593. }
  594. case Redirection::FileRead: {
  595. int fd = open(redirection.path.characters(), O_RDONLY);
  596. if (fd < 0) {
  597. perror("open");
  598. return 1;
  599. }
  600. subcommand.rewirings.append({ redirection.fd, fd });
  601. fds.add(fd);
  602. break;
  603. }
  604. }
  605. }
  606. }
  607. Vector<SpawnedProcess> children;
  608. CommandTimer timer;
  609. for (int i = 0; i < command.subcommands.size(); ++i) {
  610. auto& subcommand = command.subcommands[i];
  611. Vector<String> argv_string = process_arguments(subcommand.args);
  612. Vector<const char*> argv;
  613. argv.ensure_capacity(argv_string.size());
  614. for (const auto& s : argv_string) {
  615. argv.append(s.characters());
  616. }
  617. argv.append(nullptr);
  618. #ifdef SH_DEBUG
  619. for (auto& arg : argv) {
  620. dbgprintf("<%s> ", arg);
  621. }
  622. dbgprintf("\n");
  623. #endif
  624. int retval = 0;
  625. if (handle_builtin(argv.size() - 1, const_cast<char**>(argv.data()), retval))
  626. return retval;
  627. pid_t child = fork();
  628. if (!child) {
  629. setpgid(0, 0);
  630. tcsetpgrp(0, getpid());
  631. for (auto& rewiring : subcommand.rewirings) {
  632. #ifdef SH_DEBUG
  633. dbgprintf("in %s<%d>, dup2(%d, %d)\n", argv[0], getpid(), rewiring.rewire_fd, rewiring.fd);
  634. #endif
  635. int rc = dup2(rewiring.rewire_fd, rewiring.fd);
  636. if (rc < 0) {
  637. perror("dup2");
  638. return 1;
  639. }
  640. }
  641. fds.collect();
  642. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  643. if (rc < 0) {
  644. if (errno == ENOENT)
  645. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  646. else
  647. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(errno));
  648. exit(1);
  649. }
  650. ASSERT_NOT_REACHED();
  651. }
  652. children.append({ argv[0], child });
  653. }
  654. #ifdef SH_DEBUG
  655. dbgprintf("Closing fds in shell process:\n");
  656. #endif
  657. fds.collect();
  658. #ifdef SH_DEBUG
  659. dbgprintf("Now we gotta wait on children:\n");
  660. for (auto& child : children)
  661. dbgprintf(" %d\n", child);
  662. #endif
  663. int wstatus = 0;
  664. for (int i = 0; i < children.size(); ++i) {
  665. auto& child = children[i];
  666. do {
  667. int rc = waitpid(child.pid, &wstatus, WEXITED | WSTOPPED);
  668. if (rc < 0 && errno != EINTR) {
  669. if (errno != ECHILD)
  670. perror("waitpid");
  671. break;
  672. }
  673. if (WIFEXITED(wstatus)) {
  674. if (WEXITSTATUS(wstatus) != 0)
  675. dbg() << "Shell: " << child.name << ":" << child.pid << " exited with status " << WEXITSTATUS(wstatus);
  676. if (i == 0)
  677. return_value = WEXITSTATUS(wstatus);
  678. } else if (WIFSTOPPED(wstatus)) {
  679. printf("Shell: %s(%d) stopped.\n", child.name.characters(), child.pid);
  680. } else {
  681. if (WIFSIGNALED(wstatus)) {
  682. printf("Shell: %s(%d) exited due to signal '%s'\n", child.name.characters(), child.pid, strsignal(WTERMSIG(wstatus)));
  683. } else {
  684. printf("Shell: %s(%d) exited abnormally\n", child.name.characters(), child.pid);
  685. }
  686. }
  687. } while (errno == EINTR);
  688. }
  689. }
  690. g.last_return_code = return_value;
  691. // FIXME: Should I really have to tcsetpgrp() after my child has exited?
  692. // Is the terminal controlling pgrp really still the PGID of the dead process?
  693. tcsetpgrp(0, getpid());
  694. tcsetattr(0, TCSANOW, &trm);
  695. return return_value;
  696. }
  697. static String get_history_path()
  698. {
  699. StringBuilder builder;
  700. builder.append(g.home);
  701. builder.append("/.history");
  702. return builder.to_string();
  703. }
  704. void load_history()
  705. {
  706. auto history_file = CFile::construct(get_history_path());
  707. if (!history_file->open(CIODevice::ReadOnly))
  708. return;
  709. while (history_file->can_read_line()) {
  710. auto b = history_file->read_line(1024);
  711. // skip the newline and terminating bytes
  712. editor.add_to_history(String(reinterpret_cast<const char*>(b.data()), b.size() - 2));
  713. }
  714. }
  715. void save_history()
  716. {
  717. auto history_file = CFile::construct(get_history_path());
  718. if (!history_file->open(CIODevice::WriteOnly))
  719. return;
  720. for (const auto& line : editor.history()) {
  721. history_file->write(line);
  722. history_file->write("\n");
  723. }
  724. }
  725. int main(int argc, char** argv)
  726. {
  727. g.uid = getuid();
  728. g.sid = setsid();
  729. tcsetpgrp(0, getpgrp());
  730. tcgetattr(0, &g.termios);
  731. signal(SIGINT, [](int) {
  732. g.was_interrupted = true;
  733. });
  734. signal(SIGHUP, [](int) {
  735. save_history();
  736. });
  737. signal(SIGWINCH, [](int) {
  738. g.was_resized = true;
  739. });
  740. int rc = gethostname(g.hostname, sizeof(g.hostname));
  741. if (rc < 0)
  742. perror("gethostname");
  743. rc = ttyname_r(0, g.ttyname, sizeof(g.ttyname));
  744. if (rc < 0)
  745. perror("ttyname_r");
  746. {
  747. auto* pw = getpwuid(getuid());
  748. if (pw) {
  749. g.username = pw->pw_name;
  750. g.home = pw->pw_dir;
  751. setenv("HOME", pw->pw_dir, 1);
  752. }
  753. endpwent();
  754. }
  755. if (argc > 2 && !strcmp(argv[1], "-c")) {
  756. dbgprintf("sh -c '%s'\n", argv[2]);
  757. run_command(argv[2]);
  758. return 0;
  759. }
  760. if (argc == 2 && argv[1][0] != '-') {
  761. auto file = CFile::construct(argv[1]);
  762. if (!file->open(CIODevice::ReadOnly)) {
  763. fprintf(stderr, "Failed to open %s: %s\n", file->filename().characters(), file->error_string());
  764. return 1;
  765. }
  766. for (;;) {
  767. auto line = file->read_line(4096);
  768. if (line.is_null())
  769. break;
  770. run_command(String::copy(line, Chomp));
  771. }
  772. return 0;
  773. }
  774. {
  775. auto* cwd = getcwd(nullptr, 0);
  776. g.cwd = cwd;
  777. setenv("PWD", cwd, 1);
  778. free(cwd);
  779. }
  780. g.directory_stack.append(g.cwd);
  781. load_history();
  782. atexit(save_history);
  783. for (;;) {
  784. auto line = editor.get_line(prompt());
  785. if (line.is_empty())
  786. continue;
  787. run_command(line);
  788. editor.add_to_history(line);
  789. }
  790. return 0;
  791. }