Shell.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /*
  2. * Copyright (c) 2020-2022, 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/Array.h>
  10. #include <AK/CircularQueue.h>
  11. #include <AK/DeprecatedString.h>
  12. #include <AK/HashMap.h>
  13. #include <AK/NonnullOwnPtrVector.h>
  14. #include <AK/StackInfo.h>
  15. #include <AK/StringBuilder.h>
  16. #include <AK/StringView.h>
  17. #include <AK/Types.h>
  18. #include <AK/Vector.h>
  19. #include <LibCore/Notifier.h>
  20. #include <LibCore/Object.h>
  21. #include <LibLine/Editor.h>
  22. #include <termios.h>
  23. #define ENUMERATE_SHELL_BUILTINS() \
  24. __ENUMERATE_SHELL_BUILTIN(alias) \
  25. __ENUMERATE_SHELL_BUILTIN(where) \
  26. __ENUMERATE_SHELL_BUILTIN(cd) \
  27. __ENUMERATE_SHELL_BUILTIN(cdh) \
  28. __ENUMERATE_SHELL_BUILTIN(pwd) \
  29. __ENUMERATE_SHELL_BUILTIN(type) \
  30. __ENUMERATE_SHELL_BUILTIN(exec) \
  31. __ENUMERATE_SHELL_BUILTIN(exit) \
  32. __ENUMERATE_SHELL_BUILTIN(export) \
  33. __ENUMERATE_SHELL_BUILTIN(glob) \
  34. __ENUMERATE_SHELL_BUILTIN(unalias) \
  35. __ENUMERATE_SHELL_BUILTIN(unset) \
  36. __ENUMERATE_SHELL_BUILTIN(history) \
  37. __ENUMERATE_SHELL_BUILTIN(umask) \
  38. __ENUMERATE_SHELL_BUILTIN(not ) \
  39. __ENUMERATE_SHELL_BUILTIN(dirs) \
  40. __ENUMERATE_SHELL_BUILTIN(pushd) \
  41. __ENUMERATE_SHELL_BUILTIN(popd) \
  42. __ENUMERATE_SHELL_BUILTIN(setopt) \
  43. __ENUMERATE_SHELL_BUILTIN(shift) \
  44. __ENUMERATE_SHELL_BUILTIN(source) \
  45. __ENUMERATE_SHELL_BUILTIN(time) \
  46. __ENUMERATE_SHELL_BUILTIN(jobs) \
  47. __ENUMERATE_SHELL_BUILTIN(disown) \
  48. __ENUMERATE_SHELL_BUILTIN(fg) \
  49. __ENUMERATE_SHELL_BUILTIN(bg) \
  50. __ENUMERATE_SHELL_BUILTIN(wait) \
  51. __ENUMERATE_SHELL_BUILTIN(dump) \
  52. __ENUMERATE_SHELL_BUILTIN(kill) \
  53. __ENUMERATE_SHELL_BUILTIN(noop) \
  54. __ENUMERATE_SHELL_BUILTIN(argsparser_parse)
  55. #define ENUMERATE_SHELL_OPTIONS() \
  56. __ENUMERATE_SHELL_OPTION(inline_exec_keep_empty_segments, false, "Keep empty segments in inline execute $(...)") \
  57. __ENUMERATE_SHELL_OPTION(verbose, false, "Announce every command that is about to be executed") \
  58. __ENUMERATE_SHELL_OPTION(invoke_program_for_autocomplete, false, "Attempt to use the program being completed itself for autocompletion via --complete")
  59. #define ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS() \
  60. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(concat_lists) \
  61. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(length) \
  62. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(length_across) \
  63. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(remove_suffix) \
  64. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(remove_prefix) \
  65. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(regex_replace) \
  66. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(filter_glob) \
  67. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(split) \
  68. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(join) \
  69. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(value_or_default) \
  70. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(assign_default) \
  71. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(error_if_empty) \
  72. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(null_or_alternative) \
  73. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(defined_value_or_default) \
  74. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(assign_defined_default) \
  75. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(error_if_unset) \
  76. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(null_if_unset_or_alternative) \
  77. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(length_of_variable) \
  78. __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(reexpand)
  79. namespace Shell {
  80. class Shell;
  81. class Shell : public Core::Object {
  82. C_OBJECT(Shell);
  83. public:
  84. constexpr static auto local_init_file_path = "~/.shellrc";
  85. constexpr static auto global_init_file_path = "/etc/shellrc";
  86. bool should_format_live() const { return m_should_format_live; }
  87. void set_live_formatting(bool value) { m_should_format_live = value; }
  88. void setup_signals();
  89. struct SourcePosition {
  90. DeprecatedString source_file;
  91. DeprecatedString literal_source_text;
  92. Optional<AST::Position> position;
  93. };
  94. struct RunnablePath {
  95. enum class Kind {
  96. Builtin,
  97. Function,
  98. Alias,
  99. Executable,
  100. };
  101. Kind kind;
  102. DeprecatedString path;
  103. bool operator<(RunnablePath const& other) const
  104. {
  105. return path < other.path;
  106. }
  107. bool operator==(RunnablePath const&) const = default;
  108. };
  109. struct RunnablePathComparator {
  110. int operator()(RunnablePath const& lhs, RunnablePath const& rhs)
  111. {
  112. if (lhs.path > rhs.path)
  113. return 1;
  114. if (lhs.path < rhs.path)
  115. return -1;
  116. return 0;
  117. }
  118. int operator()(StringView lhs, RunnablePath const& rhs)
  119. {
  120. if (lhs > rhs.path)
  121. return 1;
  122. if (lhs < rhs.path)
  123. return -1;
  124. return 0;
  125. }
  126. };
  127. int run_command(StringView, Optional<SourcePosition> = {});
  128. Optional<RunnablePath> runnable_path_for(StringView);
  129. Optional<DeprecatedString> help_path_for(Vector<RunnablePath> visited, RunnablePath const& runnable_path);
  130. ErrorOr<RefPtr<Job>> run_command(const AST::Command&);
  131. NonnullRefPtrVector<Job> run_commands(Vector<AST::Command>&);
  132. bool run_file(DeprecatedString const&, bool explicitly_invoked = true);
  133. bool run_builtin(const AST::Command&, NonnullRefPtrVector<AST::Rewiring> const&, int& retval);
  134. bool has_builtin(StringView) const;
  135. RefPtr<AST::Node> run_immediate_function(StringView name, AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const&);
  136. static bool has_immediate_function(StringView);
  137. void block_on_job(RefPtr<Job>);
  138. void block_on_pipeline(RefPtr<AST::Pipeline>);
  139. DeprecatedString prompt() const;
  140. static DeprecatedString expand_tilde(StringView expression);
  141. static Vector<DeprecatedString> expand_globs(StringView path, StringView base);
  142. static Vector<DeprecatedString> expand_globs(Vector<StringView> path_segments, StringView base);
  143. Vector<AST::Command> expand_aliases(Vector<AST::Command>);
  144. DeprecatedString resolve_path(DeprecatedString) const;
  145. DeprecatedString resolve_alias(StringView) const;
  146. static bool has_history_event(StringView);
  147. RefPtr<AST::Value const> get_argument(size_t) const;
  148. RefPtr<AST::Value const> lookup_local_variable(StringView) const;
  149. DeprecatedString local_variable_or(StringView, DeprecatedString const&) const;
  150. void set_local_variable(DeprecatedString const&, RefPtr<AST::Value>, bool only_in_current_frame = false);
  151. void unset_local_variable(StringView, bool only_in_current_frame = false);
  152. void define_function(DeprecatedString name, Vector<DeprecatedString> argnames, RefPtr<AST::Node> body);
  153. bool has_function(StringView);
  154. bool invoke_function(const AST::Command&, int& retval);
  155. DeprecatedString format(StringView, ssize_t& cursor) const;
  156. RefPtr<Line::Editor> editor() const { return m_editor; }
  157. struct LocalFrame {
  158. LocalFrame(DeprecatedString name, HashMap<DeprecatedString, RefPtr<AST::Value>> variables)
  159. : name(move(name))
  160. , local_variables(move(variables))
  161. {
  162. }
  163. DeprecatedString name;
  164. HashMap<DeprecatedString, RefPtr<AST::Value>> local_variables;
  165. };
  166. struct Frame {
  167. Frame(NonnullOwnPtrVector<LocalFrame>& frames, LocalFrame const& frame)
  168. : frames(frames)
  169. , frame(frame)
  170. {
  171. }
  172. ~Frame();
  173. void leak_frame() { should_destroy_frame = false; }
  174. private:
  175. NonnullOwnPtrVector<LocalFrame>& frames;
  176. LocalFrame const& frame;
  177. bool should_destroy_frame { true };
  178. };
  179. [[nodiscard]] Frame push_frame(DeprecatedString name);
  180. void pop_frame();
  181. struct Promise {
  182. struct Data {
  183. struct Unveil {
  184. DeprecatedString path;
  185. DeprecatedString access;
  186. };
  187. DeprecatedString exec_promises;
  188. Vector<Unveil> unveils;
  189. } data;
  190. IntrusiveListNode<Promise> node;
  191. using List = IntrusiveList<&Promise::node>;
  192. };
  193. struct ScopedPromise {
  194. ScopedPromise(Promise::List& promises, Promise&& promise)
  195. : promises(promises)
  196. , promise(move(promise))
  197. {
  198. promises.append(this->promise);
  199. }
  200. ~ScopedPromise()
  201. {
  202. promises.remove(promise);
  203. }
  204. Promise::List& promises;
  205. Promise promise;
  206. };
  207. [[nodiscard]] ScopedPromise promise(Promise::Data data)
  208. {
  209. return { m_active_promises, { move(data), {} } };
  210. }
  211. enum class EscapeMode {
  212. Bareword,
  213. SingleQuotedString,
  214. DoubleQuotedString,
  215. };
  216. static DeprecatedString escape_token_for_double_quotes(StringView token);
  217. static DeprecatedString escape_token_for_single_quotes(StringView token);
  218. static DeprecatedString escape_token(StringView token, EscapeMode = EscapeMode::Bareword);
  219. static DeprecatedString escape_token(Utf32View token, EscapeMode = EscapeMode::Bareword);
  220. static DeprecatedString unescape_token(StringView token);
  221. enum class SpecialCharacterEscapeMode {
  222. Untouched,
  223. Escaped,
  224. QuotedAsEscape,
  225. QuotedAsHex,
  226. };
  227. static SpecialCharacterEscapeMode special_character_escape_mode(u32 c, EscapeMode);
  228. static bool is_glob(StringView);
  229. static Vector<StringView> split_path(StringView);
  230. enum class ExecutableOnly {
  231. Yes,
  232. No
  233. };
  234. void highlight(Line::Editor&) const;
  235. Vector<Line::CompletionSuggestion> complete();
  236. Vector<Line::CompletionSuggestion> complete(StringView);
  237. Vector<Line::CompletionSuggestion> complete_program_name(StringView, size_t offset, EscapeMode = EscapeMode::Bareword);
  238. Vector<Line::CompletionSuggestion> complete_variable(StringView, size_t offset);
  239. Vector<Line::CompletionSuggestion> complete_user(StringView, size_t offset);
  240. Vector<Line::CompletionSuggestion> complete_immediate_function_name(StringView, size_t offset);
  241. Vector<Line::CompletionSuggestion> complete_path(StringView base, StringView, size_t offset, ExecutableOnly executable_only, AST::Node const* command_node, AST::Node const*, EscapeMode = EscapeMode::Bareword);
  242. Vector<Line::CompletionSuggestion> complete_option(StringView, StringView, size_t offset, AST::Node const* command_node, AST::Node const*);
  243. ErrorOr<Vector<Line::CompletionSuggestion>> complete_via_program_itself(size_t offset, AST::Node const* command_node, AST::Node const*, EscapeMode escape_mode, StringView known_program_name);
  244. void restore_ios();
  245. u64 find_last_job_id() const;
  246. Job* find_job(u64 id, bool is_pid = false);
  247. Job* current_job() const { return m_current_job; }
  248. void kill_job(Job const*, int sig);
  249. DeprecatedString get_history_path();
  250. void print_path(StringView path);
  251. void cache_path();
  252. bool read_single_line();
  253. void notify_child_event();
  254. struct termios termios;
  255. struct termios default_termios;
  256. bool was_interrupted { false };
  257. bool was_resized { false };
  258. DeprecatedString cwd;
  259. DeprecatedString username;
  260. DeprecatedString home;
  261. constexpr static auto TTYNameSize = 32;
  262. constexpr static auto HostNameSize = 64;
  263. char ttyname[TTYNameSize];
  264. char hostname[HostNameSize];
  265. uid_t uid;
  266. Optional<int> last_return_code;
  267. Vector<DeprecatedString> directory_stack;
  268. CircularQueue<DeprecatedString, 8> cd_history; // FIXME: have a configurable cd history length
  269. HashMap<u64, NonnullRefPtr<Job>> jobs;
  270. Vector<RunnablePath, 256> cached_path;
  271. DeprecatedString current_script;
  272. enum ShellEventType {
  273. ReadLine,
  274. };
  275. enum class ShellError {
  276. None,
  277. InternalControlFlowBreak,
  278. InternalControlFlowContinue,
  279. InternalControlFlowInterrupted,
  280. InternalControlFlowKilled,
  281. EvaluatedSyntaxError,
  282. NonExhaustiveMatchRules,
  283. InvalidGlobError,
  284. InvalidSliceContentsError,
  285. OpenFailure,
  286. OutOfMemory,
  287. LaunchError,
  288. PipeFailure,
  289. WriteFailure,
  290. };
  291. void raise_error(ShellError kind, DeprecatedString description, Optional<AST::Position> position = {})
  292. {
  293. m_error = kind;
  294. m_error_description = move(description);
  295. if (m_source_position.has_value() && position.has_value())
  296. m_source_position.value().position = position.release_value();
  297. }
  298. bool has_error(ShellError err) const { return m_error == err; }
  299. bool has_any_error() const { return !has_error(ShellError::None); }
  300. DeprecatedString const& error_description() const { return m_error_description; }
  301. ShellError take_error()
  302. {
  303. auto err = m_error;
  304. m_error = ShellError::None;
  305. m_error_description = {};
  306. return err;
  307. }
  308. void possibly_print_error() const;
  309. static bool is_control_flow(ShellError error)
  310. {
  311. switch (error) {
  312. case ShellError::InternalControlFlowBreak:
  313. case ShellError::InternalControlFlowContinue:
  314. case ShellError::InternalControlFlowInterrupted:
  315. case ShellError::InternalControlFlowKilled:
  316. return true;
  317. default:
  318. return false;
  319. }
  320. }
  321. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  322. bool name { default_ };
  323. struct Options {
  324. ENUMERATE_SHELL_OPTIONS();
  325. } options;
  326. #undef __ENUMERATE_SHELL_OPTION
  327. private:
  328. Shell(Line::Editor&, bool attempt_interactive, bool posix_mode = false);
  329. Shell();
  330. virtual ~Shell() override;
  331. RefPtr<AST::Node> parse(StringView, bool interactive = false, bool as_command = true) const;
  332. void timer_event(Core::TimerEvent&) override;
  333. bool is_allowed_to_modify_termios(const AST::Command&) const;
  334. // FIXME: Port to Core::Property
  335. void save_to(JsonObject&);
  336. void bring_cursor_to_beginning_of_a_line() const;
  337. Optional<int> resolve_job_spec(StringView);
  338. void add_entry_to_cache(RunnablePath const&);
  339. void remove_entry_from_cache(StringView);
  340. void stop_all_jobs();
  341. Job* m_current_job { nullptr };
  342. LocalFrame* find_frame_containing_local_variable(StringView name);
  343. LocalFrame const* find_frame_containing_local_variable(StringView name) const
  344. {
  345. return const_cast<Shell*>(this)->find_frame_containing_local_variable(name);
  346. }
  347. void run_tail(RefPtr<Job>);
  348. void run_tail(const AST::Command&, const AST::NodeWithAction&, int head_exit_code);
  349. [[noreturn]] void execute_process(Vector<char const*>&& argv);
  350. virtual void custom_event(Core::CustomEvent&) override;
  351. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(name) \
  352. RefPtr<AST::Node> immediate_##name(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const&);
  353. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  354. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  355. RefPtr<AST::Node> immediate_length_impl(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const&, bool across);
  356. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  357. int builtin_##builtin(int argc, char const** argv);
  358. ENUMERATE_SHELL_BUILTINS();
  359. #undef __ENUMERATE_SHELL_BUILTIN
  360. static constexpr Array builtin_names = {
  361. #define __ENUMERATE_SHELL_BUILTIN(builtin) #builtin##sv,
  362. ENUMERATE_SHELL_BUILTINS()
  363. #undef __ENUMERATE_SHELL_BUILTIN
  364. ":"sv, // POSIX-y name for "noop".
  365. };
  366. bool m_should_ignore_jobs_on_next_exit { false };
  367. pid_t m_pid { 0 };
  368. struct ShellFunction {
  369. DeprecatedString name;
  370. Vector<DeprecatedString> arguments;
  371. RefPtr<AST::Node> body;
  372. };
  373. HashMap<DeprecatedString, ShellFunction> m_functions;
  374. NonnullOwnPtrVector<LocalFrame> m_local_frames;
  375. Promise::List m_active_promises;
  376. NonnullRefPtrVector<AST::Redirection> m_global_redirections;
  377. HashMap<DeprecatedString, DeprecatedString> m_aliases;
  378. bool m_is_interactive { true };
  379. bool m_is_subshell { false };
  380. bool m_should_reinstall_signal_handlers { true };
  381. bool m_in_posix_mode { false };
  382. ShellError m_error { ShellError::None };
  383. DeprecatedString m_error_description;
  384. Optional<SourcePosition> m_source_position;
  385. bool m_should_format_live { false };
  386. RefPtr<Line::Editor> m_editor;
  387. bool m_default_constructed { false };
  388. mutable bool m_last_continuation_state { false }; // false == not needed.
  389. Optional<size_t> m_history_autosave_time;
  390. StackInfo m_completion_stack_info;
  391. };
  392. [[maybe_unused]] static constexpr bool is_word_character(char c)
  393. {
  394. return c == '_' || (c <= 'Z' && c >= 'A') || (c <= 'z' && c >= 'a') || (c <= '9' && c >= '0');
  395. }
  396. inline size_t find_offset_into_node(StringView unescaped_text, size_t escaped_offset, Shell::EscapeMode escape_mode)
  397. {
  398. size_t unescaped_offset = 0;
  399. size_t offset = 0;
  400. auto do_find_offset = [&](auto& unescaped_text) {
  401. for (auto c : unescaped_text) {
  402. if (offset == escaped_offset)
  403. return unescaped_offset;
  404. switch (Shell::special_character_escape_mode(c, escape_mode)) {
  405. case Shell::SpecialCharacterEscapeMode::Untouched:
  406. break;
  407. case Shell::SpecialCharacterEscapeMode::Escaped:
  408. ++offset; // X -> \X
  409. break;
  410. case Shell::SpecialCharacterEscapeMode::QuotedAsEscape:
  411. switch (escape_mode) {
  412. case Shell::EscapeMode::Bareword:
  413. offset += 3; // X -> "\Y"
  414. break;
  415. case Shell::EscapeMode::SingleQuotedString:
  416. offset += 5; // X -> '"\Y"'
  417. break;
  418. case Shell::EscapeMode::DoubleQuotedString:
  419. offset += 1; // X -> \Y
  420. break;
  421. }
  422. break;
  423. case Shell::SpecialCharacterEscapeMode::QuotedAsHex:
  424. switch (escape_mode) {
  425. case Shell::EscapeMode::Bareword:
  426. offset += 2; // X -> "\..."
  427. break;
  428. case Shell::EscapeMode::SingleQuotedString:
  429. offset += 4; // X -> '"\..."'
  430. break;
  431. case Shell::EscapeMode::DoubleQuotedString:
  432. // X -> \...
  433. break;
  434. }
  435. if (c > NumericLimits<u8>::max())
  436. offset += 8; // X -> "\uhhhhhhhh"
  437. else
  438. offset += 3; // X -> "\xhh"
  439. break;
  440. }
  441. ++offset;
  442. ++unescaped_offset;
  443. }
  444. return unescaped_offset;
  445. };
  446. Utf8View view { unescaped_text };
  447. if (view.validate())
  448. return do_find_offset(view);
  449. return do_find_offset(unescaped_text);
  450. }
  451. }
  452. namespace AK {
  453. template<>
  454. struct Traits<Shell::Shell::RunnablePath> : public GenericTraits<Shell::Shell::RunnablePath> {
  455. static constexpr bool is_trivial() { return false; }
  456. static bool equals(Shell::Shell::RunnablePath const& self, Shell::Shell::RunnablePath const& other)
  457. {
  458. return self == other;
  459. }
  460. static bool equals(Shell::Shell::RunnablePath const& self, StringView other)
  461. {
  462. return self.path == other;
  463. }
  464. static bool equals(Shell::Shell::RunnablePath const& self, DeprecatedString const& other)
  465. {
  466. return self.path == other;
  467. }
  468. };
  469. }