Shell.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include "Job.h"
  8. #include "Parser.h"
  9. #include <AK/CircularQueue.h>
  10. #include <AK/HashMap.h>
  11. #include <AK/NonnullOwnPtrVector.h>
  12. #include <AK/String.h>
  13. #include <AK/StringBuilder.h>
  14. #include <AK/Types.h>
  15. #include <AK/Vector.h>
  16. #include <LibCore/Notifier.h>
  17. #include <LibCore/Object.h>
  18. #include <LibLine/Editor.h>
  19. #include <termios.h>
  20. #define ENUMERATE_SHELL_BUILTINS() \
  21. __ENUMERATE_SHELL_BUILTIN(alias) \
  22. __ENUMERATE_SHELL_BUILTIN(cd) \
  23. __ENUMERATE_SHELL_BUILTIN(cdh) \
  24. __ENUMERATE_SHELL_BUILTIN(pwd) \
  25. __ENUMERATE_SHELL_BUILTIN(type) \
  26. __ENUMERATE_SHELL_BUILTIN(exec) \
  27. __ENUMERATE_SHELL_BUILTIN(exit) \
  28. __ENUMERATE_SHELL_BUILTIN(export) \
  29. __ENUMERATE_SHELL_BUILTIN(glob) \
  30. __ENUMERATE_SHELL_BUILTIN(unalias) \
  31. __ENUMERATE_SHELL_BUILTIN(unset) \
  32. __ENUMERATE_SHELL_BUILTIN(history) \
  33. __ENUMERATE_SHELL_BUILTIN(umask) \
  34. __ENUMERATE_SHELL_BUILTIN(not ) \
  35. __ENUMERATE_SHELL_BUILTIN(dirs) \
  36. __ENUMERATE_SHELL_BUILTIN(pushd) \
  37. __ENUMERATE_SHELL_BUILTIN(popd) \
  38. __ENUMERATE_SHELL_BUILTIN(setopt) \
  39. __ENUMERATE_SHELL_BUILTIN(shift) \
  40. __ENUMERATE_SHELL_BUILTIN(source) \
  41. __ENUMERATE_SHELL_BUILTIN(time) \
  42. __ENUMERATE_SHELL_BUILTIN(jobs) \
  43. __ENUMERATE_SHELL_BUILTIN(disown) \
  44. __ENUMERATE_SHELL_BUILTIN(fg) \
  45. __ENUMERATE_SHELL_BUILTIN(bg) \
  46. __ENUMERATE_SHELL_BUILTIN(wait) \
  47. __ENUMERATE_SHELL_BUILTIN(dump) \
  48. __ENUMERATE_SHELL_BUILTIN(kill)
  49. #define ENUMERATE_SHELL_OPTIONS() \
  50. __ENUMERATE_SHELL_OPTION(inline_exec_keep_empty_segments, false, "Keep empty segments in inline execute $(...)") \
  51. __ENUMERATE_SHELL_OPTION(verbose, false, "Announce every command that is about to be executed")
  52. #define ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS() \
  53. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(concat_lists) \
  54. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(length) \
  55. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(length_across) \
  56. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(remove_suffix) \
  57. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(remove_prefix) \
  58. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(regex_replace) \
  59. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(split)
  60. namespace Shell {
  61. class Shell;
  62. class Shell : public Core::Object {
  63. C_OBJECT(Shell);
  64. public:
  65. constexpr static auto local_init_file_path = "~/.shellrc";
  66. constexpr static auto global_init_file_path = "/etc/shellrc";
  67. bool should_format_live() const { return m_should_format_live; }
  68. void set_live_formatting(bool value) { m_should_format_live = value; }
  69. void setup_signals();
  70. struct SourcePosition {
  71. String source_file;
  72. String literal_source_text;
  73. Optional<AST::Position> position;
  74. };
  75. int run_command(StringView, Optional<SourcePosition> = {});
  76. bool is_runnable(StringView);
  77. ErrorOr<RefPtr<Job>> run_command(const AST::Command&);
  78. NonnullRefPtrVector<Job> run_commands(Vector<AST::Command>&);
  79. bool run_file(const String&, bool explicitly_invoked = true);
  80. bool run_builtin(const AST::Command&, const NonnullRefPtrVector<AST::Rewiring>&, int& retval);
  81. bool has_builtin(StringView) const;
  82. RefPtr<AST::Node> run_immediate_function(StringView name, AST::ImmediateExpression& invoking_node, const NonnullRefPtrVector<AST::Node>&);
  83. static bool has_immediate_function(StringView);
  84. void block_on_job(RefPtr<Job>);
  85. void block_on_pipeline(RefPtr<AST::Pipeline>);
  86. String prompt() const;
  87. static String expand_tilde(const String&);
  88. static Vector<String> expand_globs(StringView path, StringView base);
  89. static Vector<String> expand_globs(Vector<StringView> path_segments, StringView base);
  90. Vector<AST::Command> expand_aliases(Vector<AST::Command>);
  91. String resolve_path(String) const;
  92. String resolve_alias(const String&) const;
  93. static String find_in_path(StringView program_name);
  94. static bool has_history_event(StringView);
  95. RefPtr<AST::Value> get_argument(size_t) const;
  96. RefPtr<AST::Value> lookup_local_variable(const String&) const;
  97. String local_variable_or(const String&, const String&) const;
  98. void set_local_variable(const String&, RefPtr<AST::Value>, bool only_in_current_frame = false);
  99. void unset_local_variable(const String&, bool only_in_current_frame = false);
  100. void define_function(String name, Vector<String> argnames, RefPtr<AST::Node> body);
  101. bool has_function(const String&);
  102. bool invoke_function(const AST::Command&, int& retval);
  103. String format(StringView, ssize_t& cursor) const;
  104. RefPtr<Line::Editor> editor() const { return m_editor; }
  105. struct LocalFrame {
  106. LocalFrame(String name, HashMap<String, RefPtr<AST::Value>> variables)
  107. : name(move(name))
  108. , local_variables(move(variables))
  109. {
  110. }
  111. String name;
  112. HashMap<String, RefPtr<AST::Value>> local_variables;
  113. };
  114. struct Frame {
  115. Frame(NonnullOwnPtrVector<LocalFrame>& frames, const LocalFrame& frame)
  116. : frames(frames)
  117. , frame(frame)
  118. {
  119. }
  120. ~Frame();
  121. void leak_frame() { should_destroy_frame = false; }
  122. private:
  123. NonnullOwnPtrVector<LocalFrame>& frames;
  124. const LocalFrame& frame;
  125. bool should_destroy_frame { true };
  126. };
  127. [[nodiscard]] Frame push_frame(String name);
  128. void pop_frame();
  129. static String escape_token_for_double_quotes(const String& token);
  130. static String escape_token_for_single_quotes(const String& token);
  131. static String escape_token(const String& token);
  132. static String unescape_token(const String& token);
  133. enum class SpecialCharacterEscapeMode {
  134. Untouched,
  135. Escaped,
  136. QuotedAsEscape,
  137. QuotedAsHex,
  138. };
  139. static SpecialCharacterEscapeMode special_character_escape_mode(u32 c);
  140. static bool is_glob(StringView);
  141. static Vector<StringView> split_path(StringView);
  142. enum class ExecutableOnly {
  143. Yes,
  144. No
  145. };
  146. void highlight(Line::Editor&) const;
  147. Vector<Line::CompletionSuggestion> complete();
  148. Vector<Line::CompletionSuggestion> complete_path(const String& base, const String&, size_t offset, ExecutableOnly executable_only);
  149. Vector<Line::CompletionSuggestion> complete_program_name(const String&, size_t offset);
  150. Vector<Line::CompletionSuggestion> complete_variable(const String&, size_t offset);
  151. Vector<Line::CompletionSuggestion> complete_user(const String&, size_t offset);
  152. Vector<Line::CompletionSuggestion> complete_option(const String&, const String&, size_t offset);
  153. Vector<Line::CompletionSuggestion> complete_immediate_function_name(const String&, size_t offset);
  154. void restore_ios();
  155. u64 find_last_job_id() const;
  156. const Job* find_job(u64 id, bool is_pid = false);
  157. const Job* current_job() const { return m_current_job; }
  158. void kill_job(const Job*, int sig);
  159. String get_history_path();
  160. void print_path(const String& path);
  161. bool read_single_line();
  162. void notify_child_event();
  163. struct termios termios;
  164. struct termios default_termios;
  165. bool was_interrupted { false };
  166. bool was_resized { false };
  167. String cwd;
  168. String username;
  169. String home;
  170. constexpr static auto TTYNameSize = 32;
  171. constexpr static auto HostNameSize = 64;
  172. char ttyname[TTYNameSize];
  173. char hostname[HostNameSize];
  174. uid_t uid;
  175. int last_return_code { 0 };
  176. Vector<String> directory_stack;
  177. CircularQueue<String, 8> cd_history; // FIXME: have a configurable cd history length
  178. HashMap<u64, NonnullRefPtr<Job>> jobs;
  179. Vector<String, 256> cached_path;
  180. String current_script;
  181. enum ShellEventType {
  182. ReadLine,
  183. };
  184. enum class ShellError {
  185. None,
  186. InternalControlFlowBreak,
  187. InternalControlFlowContinue,
  188. EvaluatedSyntaxError,
  189. NonExhaustiveMatchRules,
  190. InvalidGlobError,
  191. InvalidSliceContentsError,
  192. OpenFailure,
  193. OutOfMemory,
  194. LaunchError,
  195. };
  196. void raise_error(ShellError kind, String description, Optional<AST::Position> position = {})
  197. {
  198. m_error = kind;
  199. m_error_description = move(description);
  200. if (m_source_position.has_value() && position.has_value())
  201. m_source_position.value().position = position.release_value();
  202. }
  203. bool has_error(ShellError err) const { return m_error == err; }
  204. bool has_any_error() const { return !has_error(ShellError::None); }
  205. const String& error_description() const { return m_error_description; }
  206. ShellError take_error()
  207. {
  208. auto err = m_error;
  209. m_error = ShellError::None;
  210. m_error_description = {};
  211. return err;
  212. }
  213. void possibly_print_error() const;
  214. static bool is_control_flow(ShellError error)
  215. {
  216. switch (error) {
  217. case ShellError::InternalControlFlowBreak:
  218. case ShellError::InternalControlFlowContinue:
  219. return true;
  220. default:
  221. return false;
  222. }
  223. }
  224. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  225. bool name { default_ };
  226. struct Options {
  227. ENUMERATE_SHELL_OPTIONS();
  228. } options;
  229. #undef __ENUMERATE_SHELL_OPTION
  230. private:
  231. Shell(Line::Editor&, bool attempt_interactive);
  232. Shell();
  233. virtual ~Shell() override;
  234. void timer_event(Core::TimerEvent&) override;
  235. bool is_allowed_to_modify_termios(const AST::Command&) const;
  236. // FIXME: Port to Core::Property
  237. void save_to(JsonObject&);
  238. void bring_cursor_to_beginning_of_a_line() const;
  239. Optional<int> resolve_job_spec(const String&);
  240. void cache_path();
  241. void add_entry_to_cache(const String&);
  242. void remove_entry_from_cache(const String&);
  243. void stop_all_jobs();
  244. const Job* m_current_job { nullptr };
  245. LocalFrame* find_frame_containing_local_variable(const String& name);
  246. const LocalFrame* find_frame_containing_local_variable(const String& name) const
  247. {
  248. return const_cast<Shell*>(this)->find_frame_containing_local_variable(name);
  249. }
  250. void run_tail(RefPtr<Job>);
  251. void run_tail(const AST::Command&, const AST::NodeWithAction&, int head_exit_code);
  252. [[noreturn]] void execute_process(Vector<const char*>&& argv);
  253. virtual void custom_event(Core::CustomEvent&) override;
  254. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(name) \
  255. RefPtr<AST::Node> immediate_##name(AST::ImmediateExpression& invoking_node, const NonnullRefPtrVector<AST::Node>&);
  256. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  257. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  258. RefPtr<AST::Node> immediate_length_impl(AST::ImmediateExpression& invoking_node, const NonnullRefPtrVector<AST::Node>&, bool across);
  259. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  260. int builtin_##builtin(int argc, const char** argv);
  261. ENUMERATE_SHELL_BUILTINS();
  262. #undef __ENUMERATE_SHELL_BUILTIN
  263. constexpr static const char* builtin_names[] = {
  264. #define __ENUMERATE_SHELL_BUILTIN(builtin) #builtin,
  265. ENUMERATE_SHELL_BUILTINS()
  266. #undef __ENUMERATE_SHELL_BUILTIN
  267. };
  268. bool m_should_ignore_jobs_on_next_exit { false };
  269. pid_t m_pid { 0 };
  270. struct ShellFunction {
  271. String name;
  272. Vector<String> arguments;
  273. RefPtr<AST::Node> body;
  274. };
  275. HashMap<String, ShellFunction> m_functions;
  276. NonnullOwnPtrVector<LocalFrame> m_local_frames;
  277. NonnullRefPtrVector<AST::Redirection> m_global_redirections;
  278. HashMap<String, String> m_aliases;
  279. bool m_is_interactive { true };
  280. bool m_is_subshell { false };
  281. bool m_should_reinstall_signal_handlers { true };
  282. ShellError m_error { ShellError::None };
  283. String m_error_description;
  284. Optional<SourcePosition> m_source_position;
  285. bool m_should_format_live { false };
  286. RefPtr<Line::Editor> m_editor;
  287. bool m_default_constructed { false };
  288. mutable bool m_last_continuation_state { false }; // false == not needed.
  289. Optional<size_t> m_history_autosave_time;
  290. };
  291. [[maybe_unused]] static constexpr bool is_word_character(char c)
  292. {
  293. return c == '_' || (c <= 'Z' && c >= 'A') || (c <= 'z' && c >= 'a') || (c <= '9' && c >= '0');
  294. }
  295. inline size_t find_offset_into_node(const String& unescaped_text, size_t escaped_offset)
  296. {
  297. size_t unescaped_offset = 0;
  298. size_t offset = 0;
  299. auto do_find_offset = [&](auto& unescaped_text) {
  300. for (auto c : unescaped_text) {
  301. if (offset == escaped_offset)
  302. return unescaped_offset;
  303. switch (Shell::special_character_escape_mode(c)) {
  304. case Shell::SpecialCharacterEscapeMode::Untouched:
  305. break;
  306. case Shell::SpecialCharacterEscapeMode::Escaped:
  307. ++offset; // X -> \X
  308. break;
  309. case Shell::SpecialCharacterEscapeMode::QuotedAsEscape:
  310. offset += 3; // X -> "\Y"
  311. break;
  312. case Shell::SpecialCharacterEscapeMode::QuotedAsHex:
  313. if (c > NumericLimits<u8>::max())
  314. offset += 11; // X -> "\uhhhhhhhh"
  315. else
  316. offset += 5; // X -> "\xhh"
  317. break;
  318. }
  319. ++offset;
  320. ++unescaped_offset;
  321. }
  322. return unescaped_offset;
  323. };
  324. Utf8View view { unescaped_text };
  325. if (view.validate())
  326. return do_find_offset(view);
  327. return do_find_offset(unescaped_text);
  328. }
  329. }