main.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Execution.h"
  27. #include "Shell.h"
  28. #include <LibCore/ArgsParser.h>
  29. #include <LibCore/Event.h>
  30. #include <LibCore/EventLoop.h>
  31. #include <LibCore/File.h>
  32. #include <signal.h>
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <sys/wait.h>
  37. RefPtr<Line::Editor> editor;
  38. Shell* s_shell;
  39. void FileDescriptionCollector::collect()
  40. {
  41. for (auto fd : m_fds)
  42. close(fd);
  43. m_fds.clear();
  44. }
  45. FileDescriptionCollector::~FileDescriptionCollector()
  46. {
  47. collect();
  48. }
  49. void FileDescriptionCollector::add(int fd)
  50. {
  51. m_fds.append(fd);
  52. }
  53. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  54. {
  55. for (auto& rewiring : intended_rewirings) {
  56. int new_fd = dup(rewiring.source_fd);
  57. if (new_fd < 0) {
  58. if (errno != EBADF)
  59. perror("dup");
  60. // The fd that will be overwritten isn't open right now,
  61. // it will be cleaned up by the exec()-side collector
  62. // and we have nothing to do here, so just ignore this error.
  63. continue;
  64. }
  65. auto flags = fcntl(new_fd, F_GETFL);
  66. auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC);
  67. ASSERT(rc == 0);
  68. m_saves.append({ rewiring.source_fd, new_fd });
  69. m_collector.add(new_fd);
  70. }
  71. }
  72. SavedFileDescriptors::~SavedFileDescriptors()
  73. {
  74. for (auto& save : m_saves) {
  75. if (dup2(save.saved, save.original) < 0) {
  76. perror("dup2(~SavedFileDescriptors)");
  77. continue;
  78. }
  79. }
  80. }
  81. int main(int argc, char** argv)
  82. {
  83. Core::EventLoop loop;
  84. Core::EventLoop::register_signal(SIGINT, [](int) {
  85. editor->interrupted();
  86. s_shell->kill_job(s_shell->current_job(), SIGINT);
  87. });
  88. Core::EventLoop::register_signal(SIGWINCH, [](int) {
  89. editor->resized();
  90. s_shell->kill_job(s_shell->current_job(), SIGWINCH);
  91. });
  92. Core::EventLoop::register_signal(SIGTTIN, [](int) {});
  93. Core::EventLoop::register_signal(SIGTTOU, [](int) {});
  94. Core::EventLoop::register_signal(SIGHUP, [](int) {
  95. for (auto& it : s_shell->jobs)
  96. s_shell->kill_job(it.value.ptr(), SIGHUP);
  97. s_shell->save_history();
  98. });
  99. Core::EventLoop::register_signal(SIGCHLD, [](int) {
  100. auto& jobs = s_shell->jobs;
  101. Vector<u64> disowned_jobs;
  102. for (auto& it : jobs) {
  103. auto job_id = it.key;
  104. auto& job = *it.value;
  105. int wstatus = 0;
  106. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  107. if (child_pid < 0) {
  108. if (errno == ECHILD) {
  109. // The child process went away before we could process its death, just assume it exited all ok.
  110. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  111. dbg() << "Child process gone, cannot get exit code for " << job_id;
  112. child_pid = job.pid();
  113. } else {
  114. ASSERT_NOT_REACHED();
  115. }
  116. }
  117. #ifndef __serenity__
  118. if (child_pid == 0) {
  119. // Linux: if child didn't "change state", but existed.
  120. continue;
  121. }
  122. #endif
  123. if (child_pid == job.pid()) {
  124. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  125. job.set_signalled(WTERMSIG(wstatus));
  126. } else if (WIFEXITED(wstatus)) {
  127. job.set_has_exit(WEXITSTATUS(wstatus));
  128. } else if (WIFSTOPPED(wstatus)) {
  129. job.unblock();
  130. job.set_is_suspended(true);
  131. }
  132. }
  133. if (job.should_be_disowned())
  134. disowned_jobs.append(job_id);
  135. }
  136. for (auto job_id : disowned_jobs)
  137. jobs.remove(job_id);
  138. });
  139. Core::EventLoop::register_signal(SIGTSTP, [](auto) {
  140. auto job = s_shell->current_job();
  141. s_shell->kill_job(job, SIGTSTP);
  142. if (job) {
  143. job->set_is_suspended(true);
  144. job->unblock();
  145. }
  146. });
  147. #ifndef __serenity__
  148. sigset_t blocked;
  149. sigemptyset(&blocked);
  150. sigaddset(&blocked, SIGTTOU);
  151. sigaddset(&blocked, SIGTTIN);
  152. pthread_sigmask(SIG_BLOCK, &blocked, NULL);
  153. #endif
  154. #ifdef __serenity__
  155. if (pledge("stdio rpath wpath cpath proc exec tty accept sigaction", nullptr) < 0) {
  156. perror("pledge");
  157. return 1;
  158. }
  159. #endif
  160. editor = Line::Editor::construct();
  161. auto shell = Shell::construct();
  162. s_shell = shell.ptr();
  163. editor->initialize();
  164. shell->termios = editor->termios();
  165. shell->default_termios = editor->default_termios();
  166. editor->on_display_refresh = [&](auto& editor) {
  167. editor.strip_styles();
  168. shell->highlight(editor);
  169. };
  170. editor->on_tab_complete = [&](const Line::Editor& editor) {
  171. return shell->complete(editor);
  172. };
  173. const char* command_to_run = nullptr;
  174. const char* file_to_read_from = nullptr;
  175. Vector<const char*> script_args;
  176. bool skip_rc_files = false;
  177. Core::ArgsParser parser;
  178. parser.add_option(command_to_run, "String to read commands from", "command-string", 'c', "command-string");
  179. parser.add_option(skip_rc_files, "Skip running shellrc files", "skip-shellrc", 0);
  180. parser.add_positional_argument(file_to_read_from, "File to read commands from", "file", Core::ArgsParser::Required::No);
  181. parser.add_positional_argument(script_args, "Extra argumets to pass to the script (via $* and co)", "argument", Core::ArgsParser::Required::No);
  182. parser.parse(argc, argv);
  183. if (!skip_rc_files) {
  184. auto run_rc_file = [&](auto& name) {
  185. String file_path = name;
  186. if (file_path.starts_with('~'))
  187. file_path = shell->expand_tilde(file_path);
  188. if (Core::File::exists(file_path)) {
  189. shell->run_file(file_path, false);
  190. }
  191. };
  192. run_rc_file(Shell::global_init_file_path);
  193. run_rc_file(Shell::local_init_file_path);
  194. }
  195. {
  196. Vector<String> args;
  197. for (auto* arg : script_args)
  198. args.empend(arg);
  199. shell->set_local_variable("ARGV", adopt(*new AST::ListValue(move(args))));
  200. }
  201. if (command_to_run) {
  202. dbgprintf("sh -c '%s'\n", command_to_run);
  203. shell->run_command(command_to_run);
  204. return 0;
  205. }
  206. if (file_to_read_from && StringView { "-" } != file_to_read_from) {
  207. if (shell->run_file(file_to_read_from))
  208. return 0;
  209. return 1;
  210. }
  211. editor->on_interrupt_handled = [&] {
  212. editor->finish();
  213. };
  214. shell->add_child(*editor);
  215. Core::EventLoop::current().post_event(*shell, make<Core::CustomEvent>(Shell::ShellEventType::ReadLine));
  216. return loop.exec();
  217. }