Shell.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995
  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. #include "Shell.h"
  27. #include "Execution.h"
  28. #include "Formatter.h"
  29. #include <AK/Debug.h>
  30. #include <AK/Function.h>
  31. #include <AK/LexicalPath.h>
  32. #include <AK/ScopeGuard.h>
  33. #include <AK/StringBuilder.h>
  34. #include <AK/TemporaryChange.h>
  35. #include <LibCore/ArgsParser.h>
  36. #include <LibCore/DirIterator.h>
  37. #include <LibCore/Event.h>
  38. #include <LibCore/EventLoop.h>
  39. #include <LibCore/File.h>
  40. #include <LibLine/Editor.h>
  41. #include <errno.h>
  42. #include <fcntl.h>
  43. #include <inttypes.h>
  44. #include <pwd.h>
  45. #include <signal.h>
  46. #include <stdio.h>
  47. #include <stdlib.h>
  48. #include <string.h>
  49. #include <sys/mman.h>
  50. #include <sys/stat.h>
  51. #include <sys/utsname.h>
  52. #include <sys/wait.h>
  53. #include <termios.h>
  54. #include <unistd.h>
  55. static bool s_disable_hyperlinks = false;
  56. extern char** environ;
  57. namespace Shell {
  58. void Shell::setup_signals()
  59. {
  60. if (m_should_reinstall_signal_handlers) {
  61. Core::EventLoop::register_signal(SIGCHLD, [this](int) {
  62. #if SH_DEBUG
  63. dbgln("SIGCHLD!");
  64. #endif
  65. notify_child_event();
  66. });
  67. Core::EventLoop::register_signal(SIGTSTP, [this](auto) {
  68. auto job = current_job();
  69. kill_job(job, SIGTSTP);
  70. if (job) {
  71. job->set_is_suspended(true);
  72. job->unblock();
  73. }
  74. });
  75. }
  76. }
  77. void Shell::print_path(const String& path)
  78. {
  79. if (s_disable_hyperlinks || !m_is_interactive) {
  80. printf("%s", path.characters());
  81. return;
  82. }
  83. printf("\033]8;;file://%s%s\033\\%s\033]8;;\033\\", hostname, path.characters(), path.characters());
  84. }
  85. String Shell::prompt() const
  86. {
  87. auto build_prompt = [&]() -> String {
  88. auto* ps1 = getenv("PROMPT");
  89. if (!ps1) {
  90. if (uid == 0)
  91. return "# ";
  92. StringBuilder builder;
  93. builder.appendf("\033]0;%s@%s:%s\007", username.characters(), hostname, cwd.characters());
  94. builder.appendf("\033[31;1m%s\033[0m@\033[37;1m%s\033[0m:\033[32;1m%s\033[0m$> ", username.characters(), hostname, cwd.characters());
  95. return builder.to_string();
  96. }
  97. StringBuilder builder;
  98. for (char* ptr = ps1; *ptr; ++ptr) {
  99. if (*ptr == '\\') {
  100. ++ptr;
  101. if (!*ptr)
  102. break;
  103. switch (*ptr) {
  104. case 'X':
  105. builder.append("\033]0;");
  106. break;
  107. case 'a':
  108. builder.append(0x07);
  109. break;
  110. case 'e':
  111. builder.append(0x1b);
  112. break;
  113. case 'u':
  114. builder.append(username);
  115. break;
  116. case 'h':
  117. builder.append(hostname);
  118. break;
  119. case 'w': {
  120. String home_path = getenv("HOME");
  121. if (cwd.starts_with(home_path)) {
  122. builder.append('~');
  123. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  124. } else {
  125. builder.append(cwd);
  126. }
  127. break;
  128. }
  129. case 'p':
  130. builder.append(uid == 0 ? '#' : '$');
  131. break;
  132. }
  133. continue;
  134. }
  135. builder.append(*ptr);
  136. }
  137. return builder.to_string();
  138. };
  139. return build_prompt();
  140. }
  141. String Shell::expand_tilde(const String& expression)
  142. {
  143. VERIFY(expression.starts_with('~'));
  144. StringBuilder login_name;
  145. size_t first_slash_index = expression.length();
  146. for (size_t i = 1; i < expression.length(); ++i) {
  147. if (expression[i] == '/') {
  148. first_slash_index = i;
  149. break;
  150. }
  151. login_name.append(expression[i]);
  152. }
  153. StringBuilder path;
  154. for (size_t i = first_slash_index; i < expression.length(); ++i)
  155. path.append(expression[i]);
  156. if (login_name.is_empty()) {
  157. const char* home = getenv("HOME");
  158. if (!home) {
  159. auto passwd = getpwuid(getuid());
  160. VERIFY(passwd && passwd->pw_dir);
  161. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  162. }
  163. return String::format("%s/%s", home, path.to_string().characters());
  164. }
  165. auto passwd = getpwnam(login_name.to_string().characters());
  166. if (!passwd)
  167. return expression;
  168. VERIFY(passwd->pw_dir);
  169. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  170. }
  171. bool Shell::is_glob(const StringView& s)
  172. {
  173. for (size_t i = 0; i < s.length(); i++) {
  174. char c = s.characters_without_null_termination()[i];
  175. if (c == '*' || c == '?')
  176. return true;
  177. }
  178. return false;
  179. }
  180. Vector<StringView> Shell::split_path(const StringView& path)
  181. {
  182. Vector<StringView> parts;
  183. size_t substart = 0;
  184. for (size_t i = 0; i < path.length(); i++) {
  185. char ch = path[i];
  186. if (ch != '/')
  187. continue;
  188. size_t sublen = i - substart;
  189. if (sublen != 0)
  190. parts.append(path.substring_view(substart, sublen));
  191. substart = i + 1;
  192. }
  193. size_t taillen = path.length() - substart;
  194. if (taillen != 0)
  195. parts.append(path.substring_view(substart, taillen));
  196. return parts;
  197. }
  198. Vector<String> Shell::expand_globs(const StringView& path, StringView base)
  199. {
  200. auto explicitly_set_base = false;
  201. if (path.starts_with('/')) {
  202. base = "/";
  203. explicitly_set_base = true;
  204. }
  205. auto parts = split_path(path);
  206. String base_string = base;
  207. struct stat statbuf;
  208. if (lstat(base_string.characters(), &statbuf) < 0) {
  209. perror("lstat");
  210. return {};
  211. }
  212. StringBuilder resolved_base_path_builder;
  213. resolved_base_path_builder.append(Core::File::real_path_for(base));
  214. if (S_ISDIR(statbuf.st_mode))
  215. resolved_base_path_builder.append('/');
  216. auto resolved_base = resolved_base_path_builder.string_view();
  217. auto results = expand_globs(move(parts), resolved_base);
  218. if (explicitly_set_base && base == "/")
  219. resolved_base = resolved_base.substring_view(1, resolved_base.length() - 1);
  220. for (auto& entry : results) {
  221. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  222. if (entry.is_empty())
  223. entry = ".";
  224. }
  225. // Make the output predictable and nice.
  226. quick_sort(results);
  227. return results;
  228. }
  229. Vector<String> Shell::expand_globs(Vector<StringView> path_segments, const StringView& base)
  230. {
  231. if (path_segments.is_empty()) {
  232. String base_str = base;
  233. struct stat statbuf;
  234. if (lstat(base_str.characters(), &statbuf) < 0)
  235. return {};
  236. return { move(base_str) };
  237. }
  238. auto first_segment = path_segments.take_first();
  239. if (is_glob(first_segment)) {
  240. Vector<String> result;
  241. Core::DirIterator di(base, Core::DirIterator::SkipParentAndBaseDir);
  242. if (di.has_error())
  243. return {};
  244. while (di.has_next()) {
  245. String path = di.next_path();
  246. // Dotfiles have to be explicitly requested
  247. if (path[0] == '.' && first_segment[0] != '.')
  248. continue;
  249. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  250. StringBuilder builder;
  251. builder.append(base);
  252. if (!base.ends_with('/'))
  253. builder.append('/');
  254. builder.append(path);
  255. result.append(expand_globs(path_segments, builder.string_view()));
  256. }
  257. }
  258. return result;
  259. } else {
  260. StringBuilder builder;
  261. builder.append(base);
  262. if (!base.ends_with('/'))
  263. builder.append('/');
  264. builder.append(first_segment);
  265. return expand_globs(move(path_segments), builder.string_view());
  266. }
  267. }
  268. Vector<AST::Command> Shell::expand_aliases(Vector<AST::Command> initial_commands)
  269. {
  270. Vector<AST::Command> commands;
  271. Function<void(AST::Command&)> resolve_aliases_and_append = [&](auto& command) {
  272. if (!command.argv.is_empty()) {
  273. auto alias = resolve_alias(command.argv[0]);
  274. if (!alias.is_null()) {
  275. auto argv0 = command.argv.take_first();
  276. auto subcommand_ast = Parser { alias }.parse();
  277. if (subcommand_ast) {
  278. while (subcommand_ast->is_execute()) {
  279. auto* ast = static_cast<AST::Execute*>(subcommand_ast.ptr());
  280. subcommand_ast = ast->command();
  281. }
  282. auto subcommand_nonnull = subcommand_ast.release_nonnull();
  283. NonnullRefPtr<AST::Node> substitute = adopt(*new AST::Join(subcommand_nonnull->position(),
  284. subcommand_nonnull,
  285. adopt(*new AST::CommandLiteral(subcommand_nonnull->position(), command))));
  286. auto res = substitute->run(*this);
  287. for (auto& subst_command : res->resolve_as_commands(*this)) {
  288. if (!subst_command.argv.is_empty() && subst_command.argv.first() == argv0) // Disallow an alias resolving to itself.
  289. commands.append(subst_command);
  290. else
  291. resolve_aliases_and_append(subst_command);
  292. }
  293. } else {
  294. commands.append(command);
  295. }
  296. } else {
  297. commands.append(command);
  298. }
  299. } else {
  300. commands.append(command);
  301. }
  302. };
  303. for (auto& command : initial_commands)
  304. resolve_aliases_and_append(command);
  305. return commands;
  306. }
  307. String Shell::resolve_path(String path) const
  308. {
  309. if (!path.starts_with('/'))
  310. path = String::format("%s/%s", cwd.characters(), path.characters());
  311. return Core::File::real_path_for(path);
  312. }
  313. Shell::LocalFrame* Shell::find_frame_containing_local_variable(const String& name)
  314. {
  315. for (size_t i = m_local_frames.size(); i > 0; --i) {
  316. auto& frame = m_local_frames[i - 1];
  317. if (frame.local_variables.contains(name))
  318. return &frame;
  319. }
  320. return nullptr;
  321. }
  322. RefPtr<AST::Value> Shell::lookup_local_variable(const String& name)
  323. {
  324. if (auto* frame = find_frame_containing_local_variable(name))
  325. return frame->local_variables.get(name).value();
  326. if (auto index = name.to_uint(); index.has_value())
  327. return get_argument(index.value());
  328. return nullptr;
  329. }
  330. RefPtr<AST::Value> Shell::get_argument(size_t index)
  331. {
  332. if (index == 0)
  333. return adopt(*new AST::StringValue(current_script));
  334. --index;
  335. if (auto argv = lookup_local_variable("ARGV")) {
  336. if (argv->is_list_without_resolution()) {
  337. AST::ListValue* list = static_cast<AST::ListValue*>(argv.ptr());
  338. if (list->values().size() <= index)
  339. return nullptr;
  340. return list->values().at(index);
  341. }
  342. if (index != 0)
  343. return nullptr;
  344. return argv;
  345. }
  346. return nullptr;
  347. }
  348. String Shell::local_variable_or(const String& name, const String& replacement)
  349. {
  350. auto value = lookup_local_variable(name);
  351. if (value) {
  352. StringBuilder builder;
  353. builder.join(" ", value->resolve_as_list(*this));
  354. return builder.to_string();
  355. }
  356. return replacement;
  357. }
  358. void Shell::set_local_variable(const String& name, RefPtr<AST::Value> value, bool only_in_current_frame)
  359. {
  360. if (!only_in_current_frame) {
  361. if (auto* frame = find_frame_containing_local_variable(name)) {
  362. frame->local_variables.set(name, move(value));
  363. return;
  364. }
  365. }
  366. m_local_frames.last().local_variables.set(name, move(value));
  367. }
  368. void Shell::unset_local_variable(const String& name, bool only_in_current_frame)
  369. {
  370. if (!only_in_current_frame) {
  371. if (auto* frame = find_frame_containing_local_variable(name))
  372. frame->local_variables.remove(name);
  373. return;
  374. }
  375. m_local_frames.last().local_variables.remove(name);
  376. }
  377. void Shell::define_function(String name, Vector<String> argnames, RefPtr<AST::Node> body)
  378. {
  379. add_entry_to_cache(name);
  380. m_functions.set(name, { name, move(argnames), move(body) });
  381. }
  382. bool Shell::has_function(const String& name)
  383. {
  384. return m_functions.contains(name);
  385. }
  386. bool Shell::invoke_function(const AST::Command& command, int& retval)
  387. {
  388. if (command.argv.is_empty())
  389. return false;
  390. StringView name = command.argv.first();
  391. TemporaryChange<String> script_change { current_script, name };
  392. auto function_option = m_functions.get(name);
  393. if (!function_option.has_value())
  394. return false;
  395. auto& function = function_option.value();
  396. if (!function.body) {
  397. retval = 0;
  398. return true;
  399. }
  400. if (command.argv.size() - 1 < function.arguments.size()) {
  401. raise_error(ShellError::EvaluatedSyntaxError, String::formatted("Expected at least {} arguments to {}, but got {}", function.arguments.size(), function.name, command.argv.size() - 1), command.position);
  402. retval = 1;
  403. return true;
  404. }
  405. auto frame = push_frame(String::formatted("function {}", function.name));
  406. size_t index = 0;
  407. for (auto& arg : function.arguments) {
  408. ++index;
  409. set_local_variable(arg, adopt(*new AST::StringValue(command.argv[index])), true);
  410. }
  411. auto argv = command.argv;
  412. argv.take_first();
  413. set_local_variable("ARGV", adopt(*new AST::ListValue(move(argv))), true);
  414. Core::EventLoop loop;
  415. setup_signals();
  416. function.body->run(*this);
  417. retval = last_return_code;
  418. return true;
  419. }
  420. String Shell::format(const StringView& source, ssize_t& cursor) const
  421. {
  422. Formatter formatter(source, cursor);
  423. auto result = formatter.format();
  424. cursor = formatter.cursor();
  425. return result;
  426. }
  427. Shell::Frame Shell::push_frame(String name)
  428. {
  429. m_local_frames.append(make<LocalFrame>(name, decltype(LocalFrame::local_variables) {}));
  430. #if SH_DEBUG
  431. dbgln("New frame '{}' at {:p}", name, &m_local_frames.last());
  432. #endif
  433. return { m_local_frames, m_local_frames.last() };
  434. }
  435. void Shell::pop_frame()
  436. {
  437. VERIFY(m_local_frames.size() > 1);
  438. m_local_frames.take_last();
  439. }
  440. Shell::Frame::~Frame()
  441. {
  442. if (!should_destroy_frame)
  443. return;
  444. if (&frames.last() != &frame) {
  445. dbgln("Frame destruction order violation near {:p} (container = {:p}) in '{}'", &frame, this, frame.name);
  446. dbgln("Current frames:");
  447. for (auto& frame : frames)
  448. dbgln("- {:p}: {}", &frame, frame.name);
  449. VERIFY_NOT_REACHED();
  450. }
  451. frames.take_last();
  452. }
  453. String Shell::resolve_alias(const String& name) const
  454. {
  455. return m_aliases.get(name).value_or({});
  456. }
  457. bool Shell::is_runnable(const StringView& name)
  458. {
  459. if (access(name.to_string().characters(), X_OK) == 0)
  460. return true;
  461. return binary_search(
  462. cached_path.span(),
  463. name.to_string(),
  464. nullptr,
  465. [](auto& name, auto& program) { return strcmp(name.characters(), program.characters()); });
  466. }
  467. int Shell::run_command(const StringView& cmd, Optional<SourcePosition> source_position_override)
  468. {
  469. // The default-constructed mode of the shell
  470. // should not be used for execution!
  471. VERIFY(!m_default_constructed);
  472. take_error();
  473. ScopedValueRollback source_position_rollback { m_source_position };
  474. if (source_position_override.has_value())
  475. m_source_position = move(source_position_override);
  476. if (!m_source_position.has_value())
  477. m_source_position = SourcePosition { .source_file = {}, .literal_source_text = cmd, .position = {} };
  478. if (cmd.is_empty())
  479. return 0;
  480. auto command = Parser(cmd, m_is_interactive).parse();
  481. if (!command)
  482. return 0;
  483. #if SH_DEBUG
  484. dbgln("Command follows");
  485. command->dump(0);
  486. #endif
  487. if (command->is_syntax_error()) {
  488. auto& error_node = command->syntax_error_node();
  489. auto& position = error_node.position();
  490. raise_error(ShellError::EvaluatedSyntaxError, error_node.error_text(), position);
  491. }
  492. if (!has_error(ShellError::None)) {
  493. possibly_print_error();
  494. take_error();
  495. return 1;
  496. }
  497. tcgetattr(0, &termios);
  498. command->run(*this);
  499. if (!has_error(ShellError::None)) {
  500. possibly_print_error();
  501. take_error();
  502. return 1;
  503. }
  504. return last_return_code;
  505. }
  506. RefPtr<Job> Shell::run_command(const AST::Command& command)
  507. {
  508. FileDescriptionCollector fds;
  509. if (options.verbose)
  510. warnln("+ {}", command);
  511. // If the command is empty, store the redirections and apply them to all later commands.
  512. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  513. m_global_redirections.append(command.redirections);
  514. for (auto& next_in_chain : command.next_chain)
  515. run_tail(command, next_in_chain, last_return_code);
  516. return nullptr;
  517. }
  518. // Resolve redirections.
  519. NonnullRefPtrVector<AST::Rewiring> rewirings;
  520. auto resolve_redirection = [&](auto& redirection) -> IterationDecision {
  521. auto rewiring_result = redirection.apply();
  522. if (rewiring_result.is_error()) {
  523. if (!rewiring_result.error().is_empty())
  524. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  525. return IterationDecision::Break;
  526. }
  527. auto& rewiring = rewiring_result.value();
  528. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseNew)
  529. rewirings.append(*rewiring);
  530. if (rewiring->fd_action == AST::Rewiring::Close::Old) {
  531. fds.add(rewiring->old_fd);
  532. } else if (rewiring->fd_action == AST::Rewiring::Close::New) {
  533. if (rewiring->new_fd != -1)
  534. fds.add(rewiring->new_fd);
  535. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseNew) {
  536. fds.add(rewiring->new_fd);
  537. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshNew) {
  538. VERIFY(rewiring->other_pipe_end);
  539. int pipe_fd[2];
  540. int rc = pipe(pipe_fd);
  541. if (rc < 0) {
  542. perror("pipe(RedirRefresh)");
  543. return IterationDecision::Break;
  544. }
  545. rewiring->new_fd = pipe_fd[1];
  546. rewiring->other_pipe_end->new_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  547. fds.add(pipe_fd[1]);
  548. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshOld) {
  549. VERIFY(rewiring->other_pipe_end);
  550. int pipe_fd[2];
  551. int rc = pipe(pipe_fd);
  552. if (rc < 0) {
  553. perror("pipe(RedirRefresh)");
  554. return IterationDecision::Break;
  555. }
  556. rewiring->old_fd = pipe_fd[1];
  557. rewiring->other_pipe_end->old_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  558. fds.add(pipe_fd[1]);
  559. }
  560. return IterationDecision::Continue;
  561. };
  562. auto apply_rewirings = [&] {
  563. for (auto& rewiring : rewirings) {
  564. #if SH_DEBUG
  565. dbgln("in {}<{}>, dup2({}, {})", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.old_fd, rewiring.new_fd);
  566. #endif
  567. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  568. if (rc < 0) {
  569. perror("dup2(run)");
  570. return IterationDecision::Break;
  571. }
  572. // {new,old}_fd is closed via the `fds` collector, but rewiring.other_pipe_end->{new,old}_fd
  573. // isn't yet in that collector when the first child spawns.
  574. if (rewiring.other_pipe_end) {
  575. if (rewiring.fd_action == AST::Rewiring::Close::RefreshNew) {
  576. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->new_fd) < 0)
  577. perror("close other pipe end");
  578. } else if (rewiring.fd_action == AST::Rewiring::Close::RefreshOld) {
  579. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->old_fd) < 0)
  580. perror("close other pipe end");
  581. }
  582. }
  583. }
  584. return IterationDecision::Continue;
  585. };
  586. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, false };
  587. for (auto& redirection : m_global_redirections) {
  588. if (resolve_redirection(redirection) == IterationDecision::Break)
  589. return nullptr;
  590. }
  591. for (auto& redirection : command.redirections) {
  592. if (resolve_redirection(redirection) == IterationDecision::Break)
  593. return nullptr;
  594. }
  595. if (command.should_wait && run_builtin(command, rewirings, last_return_code)) {
  596. for (auto& next_in_chain : command.next_chain)
  597. run_tail(command, next_in_chain, last_return_code);
  598. return nullptr;
  599. }
  600. auto can_be_run_in_current_process = command.should_wait && !command.pipeline && !command.argv.is_empty();
  601. if (can_be_run_in_current_process && has_function(command.argv.first())) {
  602. SavedFileDescriptors fds { rewirings };
  603. for (auto& rewiring : rewirings) {
  604. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  605. if (rc < 0) {
  606. perror("dup2(run)");
  607. return nullptr;
  608. }
  609. }
  610. if (invoke_function(command, last_return_code)) {
  611. for (auto& next_in_chain : command.next_chain)
  612. run_tail(command, next_in_chain, last_return_code);
  613. return nullptr;
  614. }
  615. }
  616. if (command.argv.is_empty()
  617. && !command.next_chain.is_empty()
  618. && command.should_immediately_execute_next
  619. && command.redirections.is_empty()
  620. && command.next_chain.first().node->should_override_execution_in_current_process()) {
  621. for (auto& next_in_chain : command.next_chain)
  622. run_tail(command, next_in_chain, last_return_code);
  623. return nullptr;
  624. }
  625. Vector<const char*> argv;
  626. Vector<String> copy_argv = command.argv;
  627. argv.ensure_capacity(command.argv.size() + 1);
  628. for (auto& arg : copy_argv)
  629. argv.append(arg.characters());
  630. argv.append(nullptr);
  631. int sync_pipe[2];
  632. if (pipe(sync_pipe) < 0) {
  633. perror("pipe");
  634. return nullptr;
  635. }
  636. pid_t child = fork();
  637. if (child < 0) {
  638. perror("fork");
  639. return nullptr;
  640. }
  641. if (child == 0) {
  642. close(sync_pipe[1]);
  643. m_is_subshell = true;
  644. m_pid = getpid();
  645. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  646. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, true };
  647. if (apply_rewirings() == IterationDecision::Break)
  648. _exit(126);
  649. fds.collect();
  650. u8 c;
  651. while (read(sync_pipe[0], &c, 1) < 0) {
  652. if (errno != EINTR) {
  653. perror("read");
  654. // There's nothing interesting we can do here.
  655. break;
  656. }
  657. }
  658. #if SH_DEBUG
  659. dbgln("Synced up with parent, we're good to exec()");
  660. #endif
  661. close(sync_pipe[0]);
  662. if (!m_is_subshell && command.should_wait)
  663. tcsetattr(0, TCSANOW, &default_termios);
  664. if (command.should_immediately_execute_next) {
  665. VERIFY(command.argv.is_empty());
  666. Core::EventLoop mainloop;
  667. setup_signals();
  668. for (auto& next_in_chain : command.next_chain)
  669. run_tail(command, next_in_chain, 0);
  670. _exit(last_return_code);
  671. }
  672. if (run_builtin(command, {}, last_return_code))
  673. _exit(last_return_code);
  674. if (invoke_function(command, last_return_code))
  675. _exit(last_return_code);
  676. // We no longer need the jobs here.
  677. jobs.clear();
  678. execute_process(move(argv));
  679. VERIFY_NOT_REACHED();
  680. }
  681. close(sync_pipe[0]);
  682. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  683. if (command.pipeline) {
  684. if (is_first) {
  685. command.pipeline->pgid = child;
  686. }
  687. }
  688. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  689. if (!m_is_subshell || command.pipeline) {
  690. if (setpgid(child, pgid) < 0 && m_is_interactive)
  691. perror("setpgid");
  692. if (!m_is_subshell) {
  693. if (tcsetpgrp(STDOUT_FILENO, pgid) != 0 && m_is_interactive)
  694. perror("tcsetpgrp(OUT)");
  695. if (tcsetpgrp(STDIN_FILENO, pgid) != 0 && m_is_interactive)
  696. perror("tcsetpgrp(IN)");
  697. }
  698. }
  699. while (write(sync_pipe[1], "x", 1) < 0) {
  700. if (errno != EINTR) {
  701. perror("write");
  702. // There's nothing interesting we can do here.
  703. break;
  704. }
  705. }
  706. close(sync_pipe[1]);
  707. StringBuilder cmd;
  708. cmd.join(" ", command.argv);
  709. auto command_copy = AST::Command(command);
  710. // Clear the next chain if it's to be immediately executed
  711. // as the child will run this chain.
  712. if (command.should_immediately_execute_next)
  713. command_copy.next_chain.clear();
  714. auto job = Job::create(child, pgid, cmd.build(), find_last_job_id() + 1, move(command_copy));
  715. jobs.set((u64)child, job);
  716. job->on_exit = [this](auto job) {
  717. if (!job->exited())
  718. return;
  719. restore_ios();
  720. if (job->is_running_in_background() && job->should_announce_exit())
  721. warnln("Shell: Job {} ({}) exited\n", job->job_id(), job->cmd().characters());
  722. else if (job->signaled() && job->should_announce_signal())
  723. warnln("Shell: Job {} ({}) {}\n", job->job_id(), job->cmd().characters(), strsignal(job->termination_signal()));
  724. last_return_code = job->exit_code();
  725. job->disown();
  726. run_tail(job);
  727. };
  728. fds.collect();
  729. return *job;
  730. }
  731. void Shell::execute_process(Vector<const char*>&& argv)
  732. {
  733. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  734. if (rc < 0) {
  735. int saved_errno = errno;
  736. struct stat st;
  737. if (stat(argv[0], &st)) {
  738. fprintf(stderr, "stat(%s): %s\n", argv[0], strerror(errno));
  739. // Return code 127 on command not found.
  740. _exit(127);
  741. }
  742. if (!(st.st_mode & S_IXUSR)) {
  743. fprintf(stderr, "%s: Not executable\n", argv[0]);
  744. // Return code 126 when file is not executable.
  745. _exit(126);
  746. }
  747. if (saved_errno == ENOENT) {
  748. int shebang_fd = open(argv[0], O_RDONLY);
  749. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  750. char shebang[256] {};
  751. ssize_t num_read = -1;
  752. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  753. StringView shebang_path_view(&shebang[2], num_read - 2);
  754. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  755. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  756. argv[0] = shebang;
  757. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  758. if (rc < 0)
  759. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(errno));
  760. } else
  761. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  762. } else {
  763. if (S_ISDIR(st.st_mode)) {
  764. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  765. _exit(126);
  766. }
  767. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  768. }
  769. _exit(126);
  770. }
  771. VERIFY_NOT_REACHED();
  772. }
  773. void Shell::run_tail(const AST::Command& invoking_command, const AST::NodeWithAction& next_in_chain, int head_exit_code)
  774. {
  775. if (m_error != ShellError::None) {
  776. possibly_print_error();
  777. if (!is_control_flow(m_error))
  778. take_error();
  779. return;
  780. }
  781. auto evaluate = [&] {
  782. if (next_in_chain.node->would_execute()) {
  783. next_in_chain.node->run(*this);
  784. return;
  785. }
  786. auto node = next_in_chain.node;
  787. if (!invoking_command.should_wait)
  788. node = adopt(static_cast<AST::Node&>(*new AST::Background(next_in_chain.node->position(), move(node))));
  789. adopt(static_cast<AST::Node&>(*new AST::Execute(next_in_chain.node->position(), move(node))))->run(*this);
  790. };
  791. switch (next_in_chain.action) {
  792. case AST::NodeWithAction::And:
  793. if (head_exit_code == 0)
  794. evaluate();
  795. break;
  796. case AST::NodeWithAction::Or:
  797. if (head_exit_code != 0)
  798. evaluate();
  799. break;
  800. case AST::NodeWithAction::Sequence:
  801. evaluate();
  802. break;
  803. }
  804. }
  805. void Shell::run_tail(RefPtr<Job> job)
  806. {
  807. if (auto cmd = job->command_ptr()) {
  808. deferred_invoke([=, this](auto&) {
  809. for (auto& next_in_chain : cmd->next_chain) {
  810. run_tail(*cmd, next_in_chain, job->exit_code());
  811. }
  812. });
  813. }
  814. }
  815. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  816. {
  817. if (m_error != ShellError::None) {
  818. possibly_print_error();
  819. if (!is_control_flow(m_error))
  820. take_error();
  821. return {};
  822. }
  823. NonnullRefPtrVector<Job> spawned_jobs;
  824. for (auto& command : commands) {
  825. #if SH_DEBUG
  826. dbgln("Command");
  827. for (auto& arg : command.argv)
  828. dbgln("argv: {}", arg);
  829. for (auto& redir : command.redirections) {
  830. if (redir.is_path_redirection()) {
  831. auto path_redir = (const AST::PathRedirection*)&redir;
  832. dbgln("redir path '{}' <-({})-> {}", path_redir->path, (int)path_redir->direction, path_redir->fd);
  833. } else if (redir.is_fd_redirection()) {
  834. auto* fdredir = (const AST::FdRedirection*)&redir;
  835. dbgln("redir fd {} -> {}", fdredir->old_fd, fdredir->new_fd);
  836. } else if (redir.is_close_redirection()) {
  837. auto close_redir = (const AST::CloseRedirection*)&redir;
  838. dbgln("close fd {}", close_redir->fd);
  839. } else {
  840. VERIFY_NOT_REACHED();
  841. }
  842. }
  843. #endif
  844. auto job = run_command(command);
  845. if (!job)
  846. continue;
  847. spawned_jobs.append(*job);
  848. if (command.should_wait) {
  849. block_on_job(job);
  850. } else {
  851. job->set_running_in_background(true);
  852. if (!command.is_pipe_source && command.should_notify_if_in_background)
  853. job->set_should_announce_exit(true);
  854. }
  855. }
  856. if (m_error != ShellError::None) {
  857. possibly_print_error();
  858. if (!is_control_flow(m_error))
  859. take_error();
  860. }
  861. return spawned_jobs;
  862. }
  863. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  864. {
  865. TemporaryChange script_change { current_script, filename };
  866. TemporaryChange interactive_change { m_is_interactive, false };
  867. TemporaryChange<Optional<SourcePosition>> source_change { m_source_position, SourcePosition { .source_file = filename, .literal_source_text = {}, .position = {} } };
  868. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  869. if (file_result.is_error()) {
  870. auto error = String::formatted("'{}': {}", escape_token_for_single_quotes(filename), file_result.error());
  871. if (explicitly_invoked)
  872. raise_error(ShellError::OpenFailure, error);
  873. else
  874. dbgln("open() failed for {}", error);
  875. return false;
  876. }
  877. auto file = file_result.value();
  878. auto data = file->read_all();
  879. return run_command(data) == 0;
  880. }
  881. void Shell::restore_ios()
  882. {
  883. if (m_is_subshell)
  884. return;
  885. tcsetattr(0, TCSANOW, &termios);
  886. tcsetpgrp(STDOUT_FILENO, m_pid);
  887. tcsetpgrp(STDIN_FILENO, m_pid);
  888. }
  889. void Shell::block_on_pipeline(RefPtr<AST::Pipeline> pipeline)
  890. {
  891. if (!pipeline)
  892. return;
  893. for (auto& it : jobs) {
  894. if (auto cmd = it.value->command_ptr(); cmd->pipeline == pipeline && cmd->is_pipe_source)
  895. block_on_job(it.value);
  896. }
  897. }
  898. void Shell::block_on_job(RefPtr<Job> job)
  899. {
  900. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  901. if (!job)
  902. return;
  903. if (job->is_suspended())
  904. return; // We cannot wait for a suspended job.
  905. ScopeGuard io_restorer { [&]() {
  906. if (job->exited() && !job->is_running_in_background()) {
  907. restore_ios();
  908. }
  909. } };
  910. bool job_exited { false };
  911. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  912. if (old_exit)
  913. old_exit(job);
  914. job_exited = true;
  915. };
  916. if (job->exited())
  917. return;
  918. while (!job_exited)
  919. Core::EventLoop::current().pump();
  920. // If the job is part of a pipeline, wait for the rest of the members too.
  921. if (auto command = job->command_ptr())
  922. block_on_pipeline(command->pipeline);
  923. }
  924. String Shell::get_history_path()
  925. {
  926. if (auto histfile = getenv("HISTFILE"))
  927. return { histfile };
  928. return String::formatted("{}/.history", home);
  929. }
  930. String Shell::escape_token_for_single_quotes(const String& token)
  931. {
  932. // `foo bar \n '` -> `'foo bar \n '"'"`
  933. StringBuilder builder;
  934. builder.append("'");
  935. auto started_single_quote = true;
  936. for (auto c : token) {
  937. switch (c) {
  938. case '\'':
  939. builder.append("\"'\"");
  940. started_single_quote = false;
  941. continue;
  942. default:
  943. builder.append(c);
  944. if (!started_single_quote) {
  945. started_single_quote = true;
  946. builder.append("'");
  947. }
  948. break;
  949. }
  950. }
  951. if (started_single_quote)
  952. builder.append("'");
  953. return builder.build();
  954. }
  955. String Shell::escape_token_for_double_quotes(const String& token)
  956. {
  957. // `foo bar \n $x 'blah "hello` -> `"foo bar \\n $x 'blah \"hello"`
  958. StringBuilder builder;
  959. builder.append('"');
  960. for (auto c : token) {
  961. switch (c) {
  962. case '\"':
  963. builder.append("\\\"");
  964. continue;
  965. case '\\':
  966. builder.append("\\\\");
  967. continue;
  968. default:
  969. builder.append(c);
  970. break;
  971. }
  972. }
  973. builder.append('"');
  974. return builder.build();
  975. }
  976. bool Shell::is_special(char c)
  977. {
  978. switch (c) {
  979. case '\'':
  980. case '"':
  981. case '$':
  982. case '|':
  983. case '>':
  984. case '<':
  985. case '(':
  986. case ')':
  987. case '{':
  988. case '}':
  989. case '&':
  990. case '\\':
  991. case ' ':
  992. return true;
  993. default:
  994. return false;
  995. }
  996. }
  997. String Shell::escape_token(const String& token)
  998. {
  999. StringBuilder builder;
  1000. for (auto c : token) {
  1001. if (is_special(c))
  1002. builder.append('\\');
  1003. builder.append(c);
  1004. }
  1005. return builder.build();
  1006. }
  1007. String Shell::unescape_token(const String& token)
  1008. {
  1009. StringBuilder builder;
  1010. enum {
  1011. Free,
  1012. Escaped
  1013. } state { Free };
  1014. for (auto c : token) {
  1015. switch (state) {
  1016. case Escaped:
  1017. builder.append(c);
  1018. state = Free;
  1019. break;
  1020. case Free:
  1021. if (c == '\\')
  1022. state = Escaped;
  1023. else
  1024. builder.append(c);
  1025. break;
  1026. }
  1027. }
  1028. if (state == Escaped)
  1029. builder.append('\\');
  1030. return builder.build();
  1031. }
  1032. void Shell::cache_path()
  1033. {
  1034. if (!m_is_interactive)
  1035. return;
  1036. if (!cached_path.is_empty())
  1037. cached_path.clear_with_capacity();
  1038. // Add shell builtins to the cache.
  1039. for (const auto& builtin_name : builtin_names)
  1040. cached_path.append(escape_token(builtin_name));
  1041. // Add functions to the cache.
  1042. for (auto& function : m_functions) {
  1043. auto name = escape_token(function.key);
  1044. if (cached_path.contains_slow(name))
  1045. continue;
  1046. cached_path.append(name);
  1047. }
  1048. // Add aliases to the cache.
  1049. for (const auto& alias : m_aliases) {
  1050. auto name = escape_token(alias.key);
  1051. if (cached_path.contains_slow(name))
  1052. continue;
  1053. cached_path.append(name);
  1054. }
  1055. String path = getenv("PATH");
  1056. if (!path.is_empty()) {
  1057. auto directories = path.split(':');
  1058. for (const auto& directory : directories) {
  1059. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1060. while (programs.has_next()) {
  1061. auto program = programs.next_path();
  1062. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  1063. auto escaped_name = escape_token(program);
  1064. if (cached_path.contains_slow(escaped_name))
  1065. continue;
  1066. if (access(program_path.characters(), X_OK) == 0)
  1067. cached_path.append(escaped_name);
  1068. }
  1069. }
  1070. }
  1071. quick_sort(cached_path);
  1072. }
  1073. void Shell::add_entry_to_cache(const String& entry)
  1074. {
  1075. size_t index = 0;
  1076. auto match = binary_search(
  1077. cached_path.span(),
  1078. entry,
  1079. &index,
  1080. [](auto& name, auto& program) { return strcmp(name.characters(), program.characters()); });
  1081. if (match)
  1082. return;
  1083. while (index < cached_path.size() && strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  1084. index++;
  1085. }
  1086. cached_path.insert(index, entry);
  1087. }
  1088. void Shell::highlight(Line::Editor& editor) const
  1089. {
  1090. auto line = editor.line();
  1091. Parser parser(line, m_is_interactive);
  1092. auto ast = parser.parse();
  1093. if (!ast)
  1094. return;
  1095. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  1096. }
  1097. Vector<Line::CompletionSuggestion> Shell::complete()
  1098. {
  1099. auto line = m_editor->line(m_editor->cursor());
  1100. Parser parser(line, m_is_interactive);
  1101. auto ast = parser.parse();
  1102. if (!ast)
  1103. return {};
  1104. return ast->complete_for_editor(*this, line.length());
  1105. }
  1106. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  1107. {
  1108. auto token = offset ? part.substring_view(0, offset) : "";
  1109. String path;
  1110. ssize_t last_slash = token.length() - 1;
  1111. while (last_slash >= 0 && token[last_slash] != '/')
  1112. --last_slash;
  1113. StringBuilder path_builder;
  1114. auto init_slash_part = token.substring_view(0, last_slash + 1);
  1115. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  1116. // Depending on the base, we will have to prepend cwd.
  1117. if (base.is_empty()) {
  1118. // '' /foo -> absolute
  1119. // '' foo -> relative
  1120. if (!token.starts_with('/'))
  1121. path_builder.append(cwd);
  1122. path_builder.append('/');
  1123. path_builder.append(init_slash_part);
  1124. } else {
  1125. // /foo * -> absolute
  1126. // foo * -> relative
  1127. if (!base.starts_with('/'))
  1128. path_builder.append(cwd);
  1129. path_builder.append('/');
  1130. path_builder.append(base);
  1131. path_builder.append('/');
  1132. path_builder.append(init_slash_part);
  1133. }
  1134. path = path_builder.build();
  1135. token = last_slash_part;
  1136. // the invariant part of the token is actually just the last segment
  1137. // e. in `cd /foo/bar', 'bar' is the invariant
  1138. // since we are not suggesting anything starting with
  1139. // `/foo/', but rather just `bar...'
  1140. auto token_length = escape_token(token).length();
  1141. if (m_editor)
  1142. m_editor->suggest(token_length, last_slash + 1);
  1143. // only suggest dot-files if path starts with a dot
  1144. Core::DirIterator files(path,
  1145. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1146. Vector<Line::CompletionSuggestion> suggestions;
  1147. while (files.has_next()) {
  1148. auto file = files.next_path();
  1149. if (file.starts_with(token)) {
  1150. struct stat program_status;
  1151. String file_path = String::format("%s/%s", path.characters(), file.characters());
  1152. int stat_error = stat(file_path.characters(), &program_status);
  1153. if (!stat_error) {
  1154. if (S_ISDIR(program_status.st_mode)) {
  1155. suggestions.append({ escape_token(file), "/" });
  1156. } else {
  1157. suggestions.append({ escape_token(file), " " });
  1158. }
  1159. suggestions.last().input_offset = token_length;
  1160. }
  1161. }
  1162. }
  1163. return suggestions;
  1164. }
  1165. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  1166. {
  1167. auto match = binary_search(
  1168. cached_path.span(),
  1169. name,
  1170. nullptr,
  1171. [](auto& name, auto& program) { return strncmp(name.characters(), program.characters(), name.length()); });
  1172. if (!match)
  1173. return complete_path("", name, offset);
  1174. String completion = *match;
  1175. auto token_length = escape_token(name).length();
  1176. if (m_editor)
  1177. m_editor->suggest(token_length, 0);
  1178. // Now that we have a program name starting with our token, we look at
  1179. // other program names starting with our token and cut off any mismatching
  1180. // characters.
  1181. Vector<Line::CompletionSuggestion> suggestions;
  1182. int index = match - cached_path.data();
  1183. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  1184. suggestions.append({ cached_path[i], " " });
  1185. suggestions.last().input_offset = token_length;
  1186. }
  1187. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  1188. suggestions.append({ cached_path[i], " " });
  1189. suggestions.last().input_offset = token_length;
  1190. }
  1191. suggestions.append({ cached_path[index], " " });
  1192. suggestions.last().input_offset = token_length;
  1193. return suggestions;
  1194. }
  1195. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  1196. {
  1197. Vector<Line::CompletionSuggestion> suggestions;
  1198. auto pattern = offset ? name.substring_view(0, offset) : "";
  1199. if (m_editor)
  1200. m_editor->suggest(offset);
  1201. // Look at local variables.
  1202. for (auto& frame : m_local_frames) {
  1203. for (auto& variable : frame.local_variables) {
  1204. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1205. suggestions.append(variable.key);
  1206. }
  1207. }
  1208. // Look at the environment.
  1209. for (auto i = 0; environ[i]; ++i) {
  1210. auto entry = StringView { environ[i] };
  1211. if (entry.starts_with(pattern)) {
  1212. auto parts = entry.split_view('=');
  1213. if (parts.is_empty() || parts.first().is_empty())
  1214. continue;
  1215. String name = parts.first();
  1216. if (suggestions.contains_slow(name))
  1217. continue;
  1218. suggestions.append(move(name));
  1219. suggestions.last().input_offset = offset;
  1220. }
  1221. }
  1222. return suggestions;
  1223. }
  1224. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  1225. {
  1226. Vector<Line::CompletionSuggestion> suggestions;
  1227. auto pattern = offset ? name.substring_view(0, offset) : "";
  1228. if (m_editor)
  1229. m_editor->suggest(offset);
  1230. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1231. if (di.has_error())
  1232. return suggestions;
  1233. while (di.has_next()) {
  1234. String name = di.next_path();
  1235. if (name.starts_with(pattern)) {
  1236. suggestions.append(name);
  1237. suggestions.last().input_offset = offset;
  1238. }
  1239. }
  1240. return suggestions;
  1241. }
  1242. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  1243. {
  1244. size_t start = 0;
  1245. while (start < option.length() && option[start] == '-' && start < 2)
  1246. ++start;
  1247. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  1248. if (m_editor)
  1249. m_editor->suggest(offset);
  1250. Vector<Line::CompletionSuggestion> suggestions;
  1251. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1252. // FIXME: Figure out how to do this stuff.
  1253. if (has_builtin(program_name)) {
  1254. // Complete builtins.
  1255. if (program_name == "setopt") {
  1256. bool negate = false;
  1257. if (option_pattern.starts_with("no_")) {
  1258. negate = true;
  1259. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  1260. }
  1261. auto maybe_negate = [&](const StringView& view) {
  1262. static StringBuilder builder;
  1263. builder.clear();
  1264. builder.append("--");
  1265. if (negate)
  1266. builder.append("no_");
  1267. builder.append(view);
  1268. return builder.to_string();
  1269. };
  1270. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  1271. if (StringView { #name }.starts_with(option_pattern)) { \
  1272. suggestions.append(maybe_negate(#name)); \
  1273. suggestions.last().input_offset = offset; \
  1274. }
  1275. ENUMERATE_SHELL_OPTIONS();
  1276. #undef __ENUMERATE_SHELL_OPTION
  1277. return suggestions;
  1278. }
  1279. }
  1280. return suggestions;
  1281. }
  1282. void Shell::bring_cursor_to_beginning_of_a_line() const
  1283. {
  1284. struct winsize ws;
  1285. if (m_editor) {
  1286. ws = m_editor->terminal_size();
  1287. } else {
  1288. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1289. // Very annoying assumptions.
  1290. ws.ws_col = 80;
  1291. ws.ws_row = 25;
  1292. }
  1293. }
  1294. // Black with Cyan background.
  1295. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1296. String eol_mark = getenv("PROMPT_EOL_MARK");
  1297. if (eol_mark.is_null())
  1298. eol_mark = default_mark;
  1299. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1300. if (eol_mark_length >= ws.ws_col) {
  1301. eol_mark = default_mark;
  1302. eol_mark_length = 1;
  1303. }
  1304. fputs(eol_mark.characters(), stderr);
  1305. for (auto i = eol_mark_length; i < ws.ws_col; ++i)
  1306. putc(' ', stderr);
  1307. putc('\r', stderr);
  1308. }
  1309. bool Shell::has_history_event(StringView source)
  1310. {
  1311. struct : public AST::NodeVisitor {
  1312. virtual void visit(const AST::HistoryEvent* node)
  1313. {
  1314. has_history_event = true;
  1315. AST::NodeVisitor::visit(node);
  1316. }
  1317. bool has_history_event { false };
  1318. } visitor;
  1319. Parser { source, true }.parse()->visit(visitor);
  1320. return visitor.has_history_event;
  1321. }
  1322. bool Shell::read_single_line()
  1323. {
  1324. restore_ios();
  1325. bring_cursor_to_beginning_of_a_line();
  1326. auto line_result = m_editor->get_line(prompt());
  1327. if (line_result.is_error()) {
  1328. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1329. // Pretend the user tried to execute builtin_exit()
  1330. run_command("exit");
  1331. return read_single_line();
  1332. } else {
  1333. Core::EventLoop::current().quit(1);
  1334. return false;
  1335. }
  1336. }
  1337. auto& line = line_result.value();
  1338. if (line.is_empty())
  1339. return true;
  1340. run_command(line);
  1341. if (!has_history_event(line))
  1342. m_editor->add_to_history(line);
  1343. return true;
  1344. }
  1345. void Shell::custom_event(Core::CustomEvent& event)
  1346. {
  1347. if (event.custom_type() == ReadLine) {
  1348. if (read_single_line())
  1349. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1350. return;
  1351. }
  1352. }
  1353. void Shell::notify_child_event()
  1354. {
  1355. Vector<u64> disowned_jobs;
  1356. // Workaround the fact that we can't receive *who* exactly changed state.
  1357. // The child might still be alive (and even running) when this signal is dispatched to us
  1358. // so just...repeat until we find a suitable child.
  1359. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1360. // until the next child event we can actually handle.
  1361. bool found_child = false;
  1362. do {
  1363. // Ignore stray SIGCHLD when there are no jobs.
  1364. if (jobs.is_empty())
  1365. return;
  1366. for (auto& it : jobs) {
  1367. auto job_id = it.key;
  1368. auto& job = *it.value;
  1369. int wstatus = 0;
  1370. #if SH_DEBUG
  1371. dbgln("waitpid({}) = ...", job.pid());
  1372. #endif
  1373. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1374. #if SH_DEBUG
  1375. dbgln("... = {} - {}", child_pid, wstatus);
  1376. #endif
  1377. if (child_pid < 0) {
  1378. if (errno == ECHILD) {
  1379. // The child process went away before we could process its death, just assume it exited all ok.
  1380. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1381. child_pid = job.pid();
  1382. } else {
  1383. VERIFY_NOT_REACHED();
  1384. }
  1385. }
  1386. if (child_pid == 0) {
  1387. // If the child existed, but wasn't dead.
  1388. continue;
  1389. }
  1390. if (child_pid == job.pid()) {
  1391. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1392. job.set_signalled(WTERMSIG(wstatus));
  1393. } else if (WIFEXITED(wstatus)) {
  1394. job.set_has_exit(WEXITSTATUS(wstatus));
  1395. } else if (WIFSTOPPED(wstatus)) {
  1396. job.unblock();
  1397. job.set_is_suspended(true);
  1398. }
  1399. found_child = true;
  1400. }
  1401. if (job.should_be_disowned())
  1402. disowned_jobs.append(job_id);
  1403. }
  1404. for (auto job_id : disowned_jobs) {
  1405. jobs.remove(job_id);
  1406. }
  1407. } while (!found_child);
  1408. }
  1409. Shell::Shell()
  1410. : m_default_constructed(true)
  1411. {
  1412. push_frame("main").leak_frame();
  1413. int rc = gethostname(hostname, Shell::HostNameSize);
  1414. if (rc < 0)
  1415. perror("gethostname");
  1416. {
  1417. auto* pw = getpwuid(getuid());
  1418. if (pw) {
  1419. username = pw->pw_name;
  1420. home = pw->pw_dir;
  1421. setenv("HOME", pw->pw_dir, 1);
  1422. }
  1423. endpwent();
  1424. }
  1425. // For simplicity, start at the user's home directory.
  1426. this->cwd = home;
  1427. setenv("PWD", home.characters(), 1);
  1428. // Add the default PATH vars.
  1429. {
  1430. StringBuilder path;
  1431. path.append(getenv("PATH"));
  1432. if (path.length())
  1433. path.append(":");
  1434. path.append("/bin:/usr/bin:/usr/local/bin");
  1435. setenv("PATH", path.to_string().characters(), true);
  1436. }
  1437. cache_path();
  1438. }
  1439. Shell::Shell(Line::Editor& editor, bool attempt_interactive)
  1440. : m_editor(editor)
  1441. {
  1442. uid = getuid();
  1443. tcsetpgrp(0, getpgrp());
  1444. m_pid = getpid();
  1445. push_frame("main").leak_frame();
  1446. int rc = gethostname(hostname, Shell::HostNameSize);
  1447. if (rc < 0)
  1448. perror("gethostname");
  1449. auto istty = isatty(STDIN_FILENO);
  1450. m_is_interactive = attempt_interactive && istty;
  1451. if (istty) {
  1452. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1453. if (rc < 0)
  1454. perror("ttyname_r");
  1455. } else {
  1456. ttyname[0] = 0;
  1457. }
  1458. {
  1459. auto* cwd = getcwd(nullptr, 0);
  1460. this->cwd = cwd;
  1461. setenv("PWD", cwd, 1);
  1462. free(cwd);
  1463. }
  1464. {
  1465. auto* pw = getpwuid(getuid());
  1466. if (pw) {
  1467. username = pw->pw_name;
  1468. home = pw->pw_dir;
  1469. setenv("HOME", pw->pw_dir, 1);
  1470. }
  1471. endpwent();
  1472. }
  1473. directory_stack.append(cwd);
  1474. if (m_is_interactive) {
  1475. m_editor->load_history(get_history_path());
  1476. cache_path();
  1477. }
  1478. m_editor->register_key_input_callback('\n', [](Line::Editor& editor) {
  1479. auto ast = Parser(editor.line()).parse();
  1480. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1481. return true;
  1482. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1483. });
  1484. }
  1485. Shell::~Shell()
  1486. {
  1487. if (m_default_constructed)
  1488. return;
  1489. stop_all_jobs();
  1490. if (!m_is_interactive)
  1491. return;
  1492. m_editor->save_history(get_history_path());
  1493. }
  1494. void Shell::stop_all_jobs()
  1495. {
  1496. if (!jobs.is_empty()) {
  1497. if (m_is_interactive && !m_is_subshell)
  1498. printf("Killing active jobs\n");
  1499. for (auto& entry : jobs) {
  1500. if (entry.value->is_suspended()) {
  1501. #if SH_DEBUG
  1502. dbgln("Job {} is suspended", entry.value->pid());
  1503. #endif
  1504. kill_job(entry.value, SIGCONT);
  1505. }
  1506. kill_job(entry.value, SIGHUP);
  1507. }
  1508. usleep(10000); // Wait for a bit before killing the job
  1509. for (auto& entry : jobs) {
  1510. #if SH_DEBUG
  1511. dbgln("Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1512. #endif
  1513. kill_job(entry.value, SIGKILL);
  1514. }
  1515. jobs.clear();
  1516. }
  1517. }
  1518. u64 Shell::find_last_job_id() const
  1519. {
  1520. u64 job_id = 0;
  1521. for (auto& entry : jobs) {
  1522. if (entry.value->job_id() > job_id)
  1523. job_id = entry.value->job_id();
  1524. }
  1525. return job_id;
  1526. }
  1527. const Job* Shell::find_job(u64 id)
  1528. {
  1529. for (auto& entry : jobs) {
  1530. if (entry.value->job_id() == id)
  1531. return entry.value;
  1532. }
  1533. return nullptr;
  1534. }
  1535. void Shell::kill_job(const Job* job, int sig)
  1536. {
  1537. if (!job)
  1538. return;
  1539. if (killpg(job->pgid(), sig) < 0) {
  1540. if (kill(job->pid(), sig) < 0) {
  1541. if (errno != ESRCH)
  1542. perror("kill");
  1543. }
  1544. }
  1545. }
  1546. void Shell::save_to(JsonObject& object)
  1547. {
  1548. Core::Object::save_to(object);
  1549. object.set("working_directory", cwd);
  1550. object.set("username", username);
  1551. object.set("user_home_path", home);
  1552. object.set("user_id", uid);
  1553. object.set("directory_stack_size", directory_stack.size());
  1554. object.set("cd_history_size", cd_history.size());
  1555. // Jobs.
  1556. JsonArray job_objects;
  1557. for (auto& job_entry : jobs) {
  1558. JsonObject job_object;
  1559. job_object.set("pid", job_entry.value->pid());
  1560. job_object.set("pgid", job_entry.value->pgid());
  1561. job_object.set("running_time", job_entry.value->timer().elapsed());
  1562. job_object.set("command", job_entry.value->cmd());
  1563. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1564. job_objects.append(move(job_object));
  1565. }
  1566. object.set("jobs", move(job_objects));
  1567. }
  1568. void Shell::possibly_print_error() const
  1569. {
  1570. switch (m_error) {
  1571. case ShellError::EvaluatedSyntaxError:
  1572. warnln("Shell Syntax Error: {}", m_error_description);
  1573. break;
  1574. case ShellError::InvalidGlobError:
  1575. case ShellError::NonExhaustiveMatchRules:
  1576. warnln("Shell: {}", m_error_description);
  1577. break;
  1578. case ShellError::OpenFailure:
  1579. warnln("Shell: Open failed for {}", m_error_description);
  1580. break;
  1581. case ShellError::InternalControlFlowBreak:
  1582. case ShellError::InternalControlFlowContinue:
  1583. return;
  1584. case ShellError::None:
  1585. return;
  1586. }
  1587. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  1588. auto& source_position = m_source_position.value();
  1589. auto do_line = [&](auto line, auto& current_line) {
  1590. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  1591. warnln("{:>3}| {}", line, current_line);
  1592. if (is_in_range) {
  1593. warn("\x1b[31m");
  1594. size_t length_written_so_far = 0;
  1595. if (line == (i64)source_position.position->start_line.line_number) {
  1596. warn(StringView { "{:~>{}}" }, "", 5 + source_position.position->start_line.line_column);
  1597. length_written_so_far += source_position.position->start_line.line_column;
  1598. } else {
  1599. warn(StringView { "{:~>{}}" }, "", 5);
  1600. }
  1601. if (line == (i64)source_position.position->end_line.line_number) {
  1602. warn(StringView { "{:^>{}}" }, "", source_position.position->end_line.line_column - length_written_so_far);
  1603. length_written_so_far += source_position.position->start_line.line_column;
  1604. } else {
  1605. warn(StringView { "{:^>{}}" }, "", current_line.length() - length_written_so_far);
  1606. }
  1607. warnln("\x1b[0m");
  1608. }
  1609. };
  1610. int line = -1;
  1611. String current_line;
  1612. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  1613. if (!source_position.source_file.is_null()) {
  1614. auto file = Core::File::open(source_position.source_file, Core::IODevice::OpenMode::ReadOnly);
  1615. if (file.is_error()) {
  1616. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file.error(), source_position.source_file);
  1617. return;
  1618. }
  1619. while (line < line_to_skip_to) {
  1620. if (file.value()->eof())
  1621. return;
  1622. current_line = file.value()->read_line();
  1623. ++line;
  1624. }
  1625. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1626. do_line(line, current_line);
  1627. if (file.value()->eof())
  1628. current_line = "";
  1629. else
  1630. current_line = file.value()->read_line();
  1631. }
  1632. } else if (!source_position.literal_source_text.is_empty()) {
  1633. GenericLexer lexer { source_position.literal_source_text };
  1634. while (line < line_to_skip_to) {
  1635. if (lexer.is_eof())
  1636. return;
  1637. current_line = lexer.consume_line();
  1638. ++line;
  1639. }
  1640. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1641. do_line(line, current_line);
  1642. if (lexer.is_eof())
  1643. current_line = "";
  1644. else
  1645. current_line = lexer.consume_line();
  1646. }
  1647. }
  1648. }
  1649. warnln();
  1650. }
  1651. void FileDescriptionCollector::collect()
  1652. {
  1653. for (auto fd : m_fds)
  1654. close(fd);
  1655. m_fds.clear();
  1656. }
  1657. FileDescriptionCollector::~FileDescriptionCollector()
  1658. {
  1659. collect();
  1660. }
  1661. void FileDescriptionCollector::add(int fd)
  1662. {
  1663. m_fds.append(fd);
  1664. }
  1665. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  1666. {
  1667. for (auto& rewiring : intended_rewirings) {
  1668. int new_fd = dup(rewiring.new_fd);
  1669. if (new_fd < 0) {
  1670. if (errno != EBADF)
  1671. perror("dup");
  1672. // The fd that will be overwritten isn't open right now,
  1673. // it will be cleaned up by the exec()-side collector
  1674. // and we have nothing to do here, so just ignore this error.
  1675. continue;
  1676. }
  1677. auto flags = fcntl(new_fd, F_GETFL);
  1678. auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC);
  1679. VERIFY(rc == 0);
  1680. m_saves.append({ rewiring.new_fd, new_fd });
  1681. m_collector.add(new_fd);
  1682. }
  1683. }
  1684. SavedFileDescriptors::~SavedFileDescriptors()
  1685. {
  1686. for (auto& save : m_saves) {
  1687. if (dup2(save.saved, save.original) < 0) {
  1688. perror("dup2(~SavedFileDescriptors)");
  1689. continue;
  1690. }
  1691. }
  1692. }
  1693. }