main.cpp 26 KB

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