Shell.h 11 KB

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