Shell.cpp 53 KB

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