main.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. void Shell::setup_signals()
  82. {
  83. Core::EventLoop::register_signal(SIGCHLD, [](int) {
  84. auto& jobs = s_shell->jobs;
  85. Vector<u64> disowned_jobs;
  86. for (auto& it : jobs) {
  87. auto job_id = it.key;
  88. auto& job = *it.value;
  89. int wstatus = 0;
  90. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  91. if (child_pid < 0) {
  92. if (errno == ECHILD) {
  93. // The child process went away before we could process its death, just assume it exited all ok.
  94. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  95. dbg() << "Child process gone, cannot get exit code for " << job_id;
  96. child_pid = job.pid();
  97. } else {
  98. ASSERT_NOT_REACHED();
  99. }
  100. }
  101. #ifndef __serenity__
  102. if (child_pid == 0) {
  103. // Linux: if child didn't "change state", but existed.
  104. continue;
  105. }
  106. #endif
  107. if (child_pid == job.pid()) {
  108. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  109. job.set_signalled(WTERMSIG(wstatus));
  110. } else if (WIFEXITED(wstatus)) {
  111. job.set_has_exit(WEXITSTATUS(wstatus));
  112. } else if (WIFSTOPPED(wstatus)) {
  113. job.unblock();
  114. job.set_is_suspended(true);
  115. }
  116. }
  117. if (job.should_be_disowned())
  118. disowned_jobs.append(job_id);
  119. }
  120. for (auto job_id : disowned_jobs)
  121. jobs.remove(job_id);
  122. });
  123. Core::EventLoop::register_signal(SIGTSTP, [](auto) {
  124. auto job = s_shell->current_job();
  125. s_shell->kill_job(job, SIGTSTP);
  126. if (job) {
  127. job->set_is_suspended(true);
  128. job->unblock();
  129. }
  130. });
  131. }
  132. int main(int argc, char** argv)
  133. {
  134. Core::EventLoop loop;
  135. Core::EventLoop::register_signal(SIGINT, [](int) {
  136. s_shell->kill_job(s_shell->current_job(), SIGINT);
  137. });
  138. Core::EventLoop::register_signal(SIGWINCH, [](int) {
  139. s_shell->kill_job(s_shell->current_job(), SIGWINCH);
  140. });
  141. Core::EventLoop::register_signal(SIGTTIN, [](int) {});
  142. Core::EventLoop::register_signal(SIGTTOU, [](int) {});
  143. Core::EventLoop::register_signal(SIGHUP, [](int) {
  144. for (auto& it : s_shell->jobs)
  145. s_shell->kill_job(it.value.ptr(), SIGHUP);
  146. s_shell->save_history();
  147. });
  148. s_shell->setup_signals();
  149. #ifndef __serenity__
  150. sigset_t blocked;
  151. sigemptyset(&blocked);
  152. sigaddset(&blocked, SIGTTOU);
  153. sigaddset(&blocked, SIGTTIN);
  154. pthread_sigmask(SIG_BLOCK, &blocked, NULL);
  155. #endif
  156. #ifdef __serenity__
  157. if (pledge("stdio rpath wpath cpath proc exec tty accept sigaction unix fattr", nullptr) < 0) {
  158. perror("pledge");
  159. return 1;
  160. }
  161. #endif
  162. editor = Line::Editor::construct();
  163. auto shell = Shell::construct();
  164. s_shell = shell.ptr();
  165. editor->initialize();
  166. shell->termios = editor->termios();
  167. shell->default_termios = editor->default_termios();
  168. editor->on_display_refresh = [&](auto& editor) {
  169. editor.strip_styles();
  170. if (shell->should_format_live()) {
  171. auto line = editor.line();
  172. ssize_t cursor = editor.cursor();
  173. editor.clear_line();
  174. editor.insert(shell->format(line, cursor));
  175. if (cursor >= 0)
  176. editor.set_cursor(cursor);
  177. }
  178. shell->highlight(editor);
  179. };
  180. editor->on_tab_complete = [&](const Line::Editor& editor) {
  181. return shell->complete(editor);
  182. };
  183. const char* command_to_run = nullptr;
  184. const char* file_to_read_from = nullptr;
  185. Vector<const char*> script_args;
  186. bool skip_rc_files = false;
  187. const char* format = nullptr;
  188. bool should_format_live = false;
  189. Core::ArgsParser parser;
  190. parser.add_option(command_to_run, "String to read commands from", "command-string", 'c', "command-string");
  191. parser.add_option(skip_rc_files, "Skip running shellrc files", "skip-shellrc", 0);
  192. parser.add_option(format, "File to format", "format", 0, "file");
  193. parser.add_option(should_format_live, "Enable live formatting", "live-formatting", 'f');
  194. parser.add_positional_argument(file_to_read_from, "File to read commands from", "file", Core::ArgsParser::Required::No);
  195. parser.add_positional_argument(script_args, "Extra argumets to pass to the script (via $* and co)", "argument", Core::ArgsParser::Required::No);
  196. parser.parse(argc, argv);
  197. shell->set_live_formatting(should_format_live);
  198. if (format) {
  199. auto file = Core::File::open(format, Core::IODevice::ReadOnly);
  200. if (file.is_error()) {
  201. fprintf(stderr, "Error: %s", file.error().characters());
  202. return 1;
  203. }
  204. ssize_t cursor = -1;
  205. puts(shell->format(file.value()->read_all(), cursor).characters());
  206. return 0;
  207. }
  208. if (getsid(getpid()) == 0) {
  209. if (setsid() < 0) {
  210. perror("setsid");
  211. // Let's just hope that it's ok.
  212. }
  213. }
  214. shell->current_script = argv[0];
  215. if (!skip_rc_files) {
  216. auto run_rc_file = [&](auto& name) {
  217. String file_path = name;
  218. if (file_path.starts_with('~'))
  219. file_path = shell->expand_tilde(file_path);
  220. if (Core::File::exists(file_path)) {
  221. shell->run_file(file_path, false);
  222. }
  223. };
  224. run_rc_file(Shell::global_init_file_path);
  225. run_rc_file(Shell::local_init_file_path);
  226. }
  227. {
  228. Vector<String> args;
  229. for (auto* arg : script_args)
  230. args.empend(arg);
  231. shell->set_local_variable("ARGV", adopt(*new AST::ListValue(move(args))));
  232. }
  233. if (command_to_run) {
  234. dbgprintf("sh -c '%s'\n", command_to_run);
  235. shell->run_command(command_to_run);
  236. return 0;
  237. }
  238. if (file_to_read_from && StringView { "-" } != file_to_read_from) {
  239. if (shell->run_file(file_to_read_from))
  240. return 0;
  241. return 1;
  242. }
  243. shell->add_child(*editor);
  244. Core::EventLoop::current().post_event(*shell, make<Core::CustomEvent>(Shell::ShellEventType::ReadLine));
  245. return loop.exec();
  246. }