Shell.h 13 KB

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