Shell.h 13 KB

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