main.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Shell.h"
  7. #include <LibCore/ArgsParser.h>
  8. #include <LibCore/Event.h>
  9. #include <LibCore/EventLoop.h>
  10. #include <LibCore/File.h>
  11. #include <LibCore/System.h>
  12. #include <LibMain/Main.h>
  13. #include <signal.h>
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <unistd.h>
  17. RefPtr<Line::Editor> editor;
  18. Shell::Shell* s_shell;
  19. ErrorOr<int> serenity_main(Main::Arguments arguments)
  20. {
  21. Core::EventLoop loop;
  22. Core::EventLoop::register_signal(SIGINT, [](int) {
  23. s_shell->kill_job(s_shell->current_job(), SIGINT);
  24. });
  25. Core::EventLoop::register_signal(SIGWINCH, [](int) {
  26. s_shell->kill_job(s_shell->current_job(), SIGWINCH);
  27. });
  28. Core::EventLoop::register_signal(SIGTTIN, [](int) {});
  29. Core::EventLoop::register_signal(SIGTTOU, [](int) {});
  30. Core::EventLoop::register_signal(SIGHUP, [](int) {
  31. for (auto& it : s_shell->jobs)
  32. s_shell->kill_job(it.value.ptr(), SIGHUP);
  33. s_shell->editor()->save_history(s_shell->get_history_path());
  34. });
  35. #ifdef __serenity__
  36. TRY(Core::System::pledge("stdio rpath wpath cpath proc exec tty sigaction unix fattr", nullptr));
  37. #endif
  38. RefPtr<::Shell::Shell> shell;
  39. bool attempt_interactive = false;
  40. auto initialize = [&] {
  41. editor = Line::Editor::construct();
  42. editor->initialize();
  43. shell = Shell::Shell::construct(*editor, attempt_interactive);
  44. s_shell = shell.ptr();
  45. s_shell->setup_signals();
  46. #ifndef __serenity__
  47. sigset_t blocked;
  48. sigemptyset(&blocked);
  49. sigaddset(&blocked, SIGTTOU);
  50. sigaddset(&blocked, SIGTTIN);
  51. pthread_sigmask(SIG_BLOCK, &blocked, nullptr);
  52. #endif
  53. shell->termios = editor->termios();
  54. shell->default_termios = editor->default_termios();
  55. editor->on_display_refresh = [&](auto& editor) {
  56. editor.strip_styles();
  57. if (shell->should_format_live()) {
  58. auto line = editor.line();
  59. ssize_t cursor = editor.cursor();
  60. editor.clear_line();
  61. editor.insert(shell->format(line, cursor));
  62. if (cursor >= 0)
  63. editor.set_cursor(cursor);
  64. }
  65. shell->highlight(editor);
  66. };
  67. editor->on_tab_complete = [&](const Line::Editor&) {
  68. return shell->complete();
  69. };
  70. editor->on_paste = [&](Utf32View data, Line::Editor& editor) {
  71. auto line = editor.line(editor.cursor());
  72. Shell::Parser parser(line, false);
  73. auto ast = parser.parse();
  74. if (!ast) {
  75. editor.insert(data);
  76. return;
  77. }
  78. auto hit_test_result = ast->hit_test_position(editor.cursor());
  79. // If the argument isn't meant to be an entire command, escape it.
  80. // This allows copy-pasting entire commands where commands are expected, and otherwise escapes everything.
  81. auto should_escape = false;
  82. if (!hit_test_result.matching_node && hit_test_result.closest_command_node) {
  83. // There's *some* command, but our cursor is immediate after it
  84. should_escape = editor.cursor() >= hit_test_result.closest_command_node->position().end_offset;
  85. hit_test_result.matching_node = hit_test_result.closest_command_node;
  86. } else if (hit_test_result.matching_node && hit_test_result.closest_command_node) {
  87. // There's a command, and we're at the end of or in the middle of some node.
  88. auto leftmost_literal = hit_test_result.closest_command_node->leftmost_trivial_literal();
  89. if (leftmost_literal)
  90. should_escape = !hit_test_result.matching_node->position().contains(leftmost_literal->position().start_offset);
  91. }
  92. if (should_escape) {
  93. String escaped_string;
  94. Optional<char> trivia {};
  95. bool starting_trivia_already_provided = false;
  96. auto escape_mode = Shell::Shell::EscapeMode::Bareword;
  97. if (hit_test_result.matching_node->kind() == Shell::AST::Node::Kind::StringLiteral) {
  98. // If we're pasting in a string literal, make sure to only consider that specific escape mode
  99. auto* node = static_cast<Shell::AST::StringLiteral const*>(hit_test_result.matching_node.ptr());
  100. switch (node->enclosure_type()) {
  101. case Shell::AST::StringLiteral::EnclosureType::None:
  102. break;
  103. case Shell::AST::StringLiteral::EnclosureType::SingleQuotes:
  104. escape_mode = Shell::Shell::EscapeMode::SingleQuotedString;
  105. trivia = '\'';
  106. starting_trivia_already_provided = true;
  107. break;
  108. case Shell::AST::StringLiteral::EnclosureType::DoubleQuotes:
  109. escape_mode = Shell::Shell::EscapeMode::DoubleQuotedString;
  110. trivia = '"';
  111. starting_trivia_already_provided = true;
  112. break;
  113. }
  114. }
  115. if (starting_trivia_already_provided) {
  116. escaped_string = shell->escape_token(data, escape_mode);
  117. } else {
  118. escaped_string = shell->escape_token(data, Shell::Shell::EscapeMode::Bareword);
  119. if (auto string = shell->escape_token(data, Shell::Shell::EscapeMode::SingleQuotedString); string.length() + 2 < escaped_string.length()) {
  120. escaped_string = move(string);
  121. trivia = '\'';
  122. }
  123. if (auto string = shell->escape_token(data, Shell::Shell::EscapeMode::DoubleQuotedString); string.length() + 2 < escaped_string.length()) {
  124. escaped_string = move(string);
  125. trivia = '"';
  126. }
  127. }
  128. if (trivia.has_value() && !starting_trivia_already_provided)
  129. editor.insert(*trivia);
  130. editor.insert(escaped_string);
  131. if (trivia.has_value())
  132. editor.insert(*trivia);
  133. } else {
  134. editor.insert(data);
  135. }
  136. };
  137. };
  138. const char* command_to_run = nullptr;
  139. const char* file_to_read_from = nullptr;
  140. Vector<const char*> script_args;
  141. bool skip_rc_files = false;
  142. const char* format = nullptr;
  143. bool should_format_live = false;
  144. bool keep_open = false;
  145. Core::ArgsParser parser;
  146. parser.add_option(command_to_run, "String to read commands from", "command-string", 'c', "command-string");
  147. parser.add_option(skip_rc_files, "Skip running shellrc files", "skip-shellrc", 0);
  148. parser.add_option(format, "Format the given file into stdout and exit", "format", 0, "file");
  149. parser.add_option(should_format_live, "Enable live formatting", "live-formatting", 'f');
  150. parser.add_option(keep_open, "Keep the shell open after running the specified command or file", "keep-open", 0);
  151. parser.add_positional_argument(file_to_read_from, "File to read commands from", "file", Core::ArgsParser::Required::No);
  152. parser.add_positional_argument(script_args, "Extra arguments to pass to the script (via $* and co)", "argument", Core::ArgsParser::Required::No);
  153. parser.parse(arguments);
  154. if (format) {
  155. auto file = TRY(Core::File::open(format, Core::OpenMode::ReadOnly));
  156. initialize();
  157. ssize_t cursor = -1;
  158. puts(shell->format(file->read_all(), cursor).characters());
  159. return 0;
  160. }
  161. auto pid = getpid();
  162. if (auto sid = getsid(pid); sid == 0) {
  163. if (auto res = Core::System::setsid(); res.is_error())
  164. dbgln("{}", res.release_error());
  165. } else if (sid != pid) {
  166. if (getpgid(pid) != pid) {
  167. if (auto res = Core::System::setpgid(pid, sid); res.is_error())
  168. dbgln("{}", res.release_error());
  169. if (auto res = Core::System::setsid(); res.is_error())
  170. dbgln("{}", res.release_error());
  171. }
  172. }
  173. auto execute_file = file_to_read_from && "-"sv != file_to_read_from;
  174. attempt_interactive = !execute_file;
  175. if (keep_open && !command_to_run && !execute_file) {
  176. warnln("Option --keep-open can only be used in combination with -c or when specifying a file to execute.");
  177. return 1;
  178. }
  179. initialize();
  180. shell->set_live_formatting(should_format_live);
  181. shell->current_script = arguments.strings[0];
  182. if (!skip_rc_files) {
  183. auto run_rc_file = [&](auto& name) {
  184. String file_path = name;
  185. if (file_path.starts_with('~'))
  186. file_path = shell->expand_tilde(file_path);
  187. if (Core::File::exists(file_path)) {
  188. shell->run_file(file_path, false);
  189. }
  190. };
  191. run_rc_file(Shell::Shell::global_init_file_path);
  192. run_rc_file(Shell::Shell::local_init_file_path);
  193. }
  194. {
  195. Vector<String> args;
  196. for (auto* arg : script_args)
  197. args.empend(arg);
  198. shell->set_local_variable("ARGV", adopt_ref(*new Shell::AST::ListValue(move(args))));
  199. }
  200. if (command_to_run) {
  201. dbgln("sh -c '{}'\n", command_to_run);
  202. auto result = shell->run_command(command_to_run);
  203. if (!keep_open)
  204. return result;
  205. }
  206. if (execute_file) {
  207. auto result = shell->run_file(file_to_read_from);
  208. if (!keep_open) {
  209. if (result)
  210. return 0;
  211. return 1;
  212. }
  213. }
  214. shell->add_child(*editor);
  215. Core::EventLoop::current().post_event(*shell, make<Core::CustomEvent>(Shell::Shell::ShellEventType::ReadLine));
  216. return loop.exec();
  217. }