main.cpp 11 KB

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