Shell.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  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. dbg() << "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. dbg() << "New frame '" << name << "' at " << &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. dbg() << "Frame destruction order violation near " << &frame << " (container = " << this << ") '" << frame.name << "'; current frames:";
  446. for (auto& frame : frames)
  447. dbg() << "- " << &frame << ": " << frame.name;
  448. ASSERT_NOT_REACHED();
  449. }
  450. frames.take_last();
  451. }
  452. String Shell::resolve_alias(const String& name) const
  453. {
  454. return m_aliases.get(name).value_or({});
  455. }
  456. bool Shell::is_runnable(const StringView& name)
  457. {
  458. if (access(name.to_string().characters(), X_OK) == 0)
  459. return true;
  460. return !!binary_search(cached_path.span(), name.to_string(), [](const String& name, const String& program) -> int {
  461. return strcmp(name.characters(), program.characters());
  462. });
  463. }
  464. int Shell::run_command(const StringView& cmd)
  465. {
  466. // The default-constructed mode of the shell
  467. // should not be used for execution!
  468. ASSERT(!m_default_constructed);
  469. if (cmd.is_empty())
  470. return 0;
  471. auto command = Parser(cmd).parse();
  472. if (!command)
  473. return 0;
  474. #ifdef SH_DEBUG
  475. dbg() << "Command follows";
  476. command->dump(0);
  477. #endif
  478. if (command->is_syntax_error()) {
  479. auto& error_node = command->syntax_error_node();
  480. auto& position = error_node.position();
  481. fprintf(stderr, "Shell: Syntax error in command: %s\n", error_node.error_text().characters());
  482. fprintf(stderr, "Around '%.*s' at %zu:%zu\n", (int)min(position.end_offset - position.start_offset, (size_t)10), cmd.characters_without_null_termination() + position.start_offset, position.start_offset, position.end_offset);
  483. return 1;
  484. }
  485. tcgetattr(0, &termios);
  486. command->run(*this);
  487. return last_return_code;
  488. }
  489. RefPtr<Job> Shell::run_command(const AST::Command& command)
  490. {
  491. FileDescriptionCollector fds;
  492. if (options.verbose)
  493. warnln("+ {}", command);
  494. // If the command is empty, store the redirections and apply them to all later commands.
  495. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  496. m_global_redirections.append(command.redirections);
  497. return nullptr;
  498. }
  499. // Resolve redirections.
  500. NonnullRefPtrVector<AST::Rewiring> rewirings;
  501. auto resolve_redirection = [&](auto& redirection) -> IterationDecision {
  502. auto rewiring_result = redirection.apply();
  503. if (rewiring_result.is_error()) {
  504. if (!rewiring_result.error().is_empty())
  505. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  506. return IterationDecision::Continue;
  507. }
  508. auto& rewiring = rewiring_result.value();
  509. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseNew)
  510. rewirings.append(*rewiring);
  511. if (rewiring->fd_action == AST::Rewiring::Close::Old) {
  512. fds.add(rewiring->old_fd);
  513. } else if (rewiring->fd_action == AST::Rewiring::Close::New) {
  514. if (rewiring->new_fd != -1)
  515. fds.add(rewiring->new_fd);
  516. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseNew) {
  517. fds.add(rewiring->new_fd);
  518. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshNew) {
  519. ASSERT(rewiring->other_pipe_end);
  520. int pipe_fd[2];
  521. int rc = pipe(pipe_fd);
  522. if (rc < 0) {
  523. perror("pipe(RedirRefresh)");
  524. return IterationDecision::Break;
  525. }
  526. rewiring->new_fd = pipe_fd[1];
  527. rewiring->other_pipe_end->new_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  528. fds.add(pipe_fd[1]);
  529. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshOld) {
  530. ASSERT(rewiring->other_pipe_end);
  531. int pipe_fd[2];
  532. int rc = pipe(pipe_fd);
  533. if (rc < 0) {
  534. perror("pipe(RedirRefresh)");
  535. return IterationDecision::Break;
  536. }
  537. rewiring->old_fd = pipe_fd[1];
  538. rewiring->other_pipe_end->old_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  539. fds.add(pipe_fd[1]);
  540. }
  541. return IterationDecision::Continue;
  542. };
  543. auto apply_rewirings = [&] {
  544. for (auto& rewiring : rewirings) {
  545. #ifdef SH_DEBUG
  546. dbgprintf("in %s<%d>, dup2(%d, %d)\n", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.old_fd, rewiring.new_fd);
  547. #endif
  548. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  549. if (rc < 0) {
  550. perror("dup2(run)");
  551. return IterationDecision::Break;
  552. }
  553. // {new,old}_fd is closed via the `fds` collector, but rewiring.other_pipe_end->{new,old}_fd
  554. // isn't yet in that collector when the first child spawns.
  555. if (rewiring.other_pipe_end) {
  556. if (rewiring.fd_action == AST::Rewiring::Close::RefreshNew) {
  557. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->new_fd) < 0)
  558. perror("close other pipe end");
  559. } else if (rewiring.fd_action == AST::Rewiring::Close::RefreshOld) {
  560. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->old_fd) < 0)
  561. perror("close other pipe end");
  562. }
  563. }
  564. }
  565. return IterationDecision::Continue;
  566. };
  567. for (auto& redirection : m_global_redirections) {
  568. if (resolve_redirection(redirection) == IterationDecision::Break)
  569. return nullptr;
  570. }
  571. for (auto& redirection : command.redirections) {
  572. if (resolve_redirection(redirection) == IterationDecision::Break)
  573. return nullptr;
  574. }
  575. if (command.should_wait && run_builtin(command, rewirings, last_return_code)) {
  576. for (auto& next_in_chain : command.next_chain)
  577. run_tail(command, next_in_chain, last_return_code);
  578. return nullptr;
  579. }
  580. auto can_be_run_in_current_process = command.should_wait && !command.pipeline;
  581. if (can_be_run_in_current_process && has_function(command.argv.first())) {
  582. SavedFileDescriptors fds { rewirings };
  583. for (auto& rewiring : rewirings) {
  584. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  585. if (rc < 0) {
  586. perror("dup2(run)");
  587. return nullptr;
  588. }
  589. }
  590. if (invoke_function(command, last_return_code)) {
  591. for (auto& next_in_chain : command.next_chain)
  592. run_tail(command, next_in_chain, last_return_code);
  593. return nullptr;
  594. }
  595. }
  596. Vector<const char*> argv;
  597. Vector<String> copy_argv = command.argv;
  598. argv.ensure_capacity(command.argv.size() + 1);
  599. for (auto& arg : copy_argv)
  600. argv.append(arg.characters());
  601. argv.append(nullptr);
  602. int sync_pipe[2];
  603. if (pipe(sync_pipe) < 0) {
  604. perror("pipe");
  605. return nullptr;
  606. }
  607. pid_t child = fork();
  608. if (child < 0) {
  609. perror("fork");
  610. return nullptr;
  611. }
  612. if (child == 0) {
  613. close(sync_pipe[1]);
  614. m_is_subshell = true;
  615. m_pid = getpid();
  616. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  617. if (apply_rewirings() == IterationDecision::Break)
  618. _exit(126);
  619. fds.collect();
  620. u8 c;
  621. while (read(sync_pipe[0], &c, 1) < 0) {
  622. if (errno != EINTR) {
  623. perror("read");
  624. // There's nothing interesting we can do here.
  625. break;
  626. }
  627. dbg() << "Oof";
  628. }
  629. #ifdef SH_DEBUG
  630. dbg() << "Synced up with parent, we're good to exec()";
  631. #endif
  632. close(sync_pipe[0]);
  633. if (!m_is_subshell && command.should_wait)
  634. tcsetattr(0, TCSANOW, &default_termios);
  635. Core::EventLoop mainloop;
  636. setup_signals();
  637. if (command.should_immediately_execute_next) {
  638. ASSERT(command.argv.is_empty());
  639. for (auto& next_in_chain : command.next_chain)
  640. run_tail(command, next_in_chain, 0);
  641. _exit(last_return_code);
  642. }
  643. if (run_builtin(command, {}, last_return_code))
  644. _exit(last_return_code);
  645. if (invoke_function(command, last_return_code))
  646. _exit(last_return_code);
  647. // We no longer need the jobs here.
  648. jobs.clear();
  649. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  650. if (rc < 0) {
  651. if (errno == ENOENT) {
  652. int shebang_fd = open(argv[0], O_RDONLY);
  653. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  654. char shebang[256] {};
  655. ssize_t num_read = -1;
  656. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  657. StringView shebang_path_view(&shebang[2], num_read - 2);
  658. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  659. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  660. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(ENOENT));
  661. } else
  662. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  663. } else {
  664. int saved_errno = errno;
  665. struct stat st;
  666. if (stat(argv[0], &st) == 0 && S_ISDIR(st.st_mode)) {
  667. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  668. _exit(126);
  669. }
  670. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  671. }
  672. _exit(126);
  673. }
  674. ASSERT_NOT_REACHED();
  675. }
  676. close(sync_pipe[0]);
  677. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  678. if (command.pipeline) {
  679. if (is_first) {
  680. command.pipeline->pgid = child;
  681. }
  682. }
  683. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  684. if ((!m_is_subshell && command.should_wait) || command.pipeline) {
  685. if (setpgid(child, pgid) < 0)
  686. perror("setpgid");
  687. if (!m_is_subshell) {
  688. if (tcsetpgrp(STDOUT_FILENO, pgid) != 0)
  689. perror("tcsetpgrp(OUT)");
  690. if (tcsetpgrp(STDIN_FILENO, pgid) != 0)
  691. perror("tcsetpgrp(IN)");
  692. }
  693. }
  694. while (write(sync_pipe[1], "x", 1) < 0) {
  695. if (errno != EINTR) {
  696. perror("write");
  697. // There's nothing interesting we can do here.
  698. break;
  699. }
  700. dbg() << "Oof";
  701. }
  702. close(sync_pipe[1]);
  703. StringBuilder cmd;
  704. cmd.join(" ", command.argv);
  705. auto command_copy = AST::Command(command);
  706. // Clear the next chain if it's to be immediately executed
  707. // as the child will run this chain.
  708. if (command.should_immediately_execute_next)
  709. command_copy.next_chain.clear();
  710. auto job = Job::create(child, pgid, cmd.build(), find_last_job_id() + 1, move(command_copy));
  711. jobs.set((u64)child, job);
  712. job->on_exit = [this](auto job) {
  713. if (!job->exited())
  714. return;
  715. if (job->is_running_in_background() && job->should_announce_exit())
  716. fprintf(stderr, "Shell: Job %" PRIu64 "(%s) exited\n", job->job_id(), job->cmd().characters());
  717. last_return_code = job->exit_code();
  718. job->disown();
  719. run_tail(job);
  720. };
  721. fds.collect();
  722. return *job;
  723. }
  724. void Shell::run_tail(const AST::Command& invoking_command, const AST::NodeWithAction& next_in_chain, int head_exit_code)
  725. {
  726. auto evaluate = [&] {
  727. if (next_in_chain.node->would_execute()) {
  728. next_in_chain.node->run(*this);
  729. return;
  730. }
  731. auto node = next_in_chain.node;
  732. if (!invoking_command.should_wait)
  733. node = adopt(static_cast<AST::Node&>(*new AST::Background(next_in_chain.node->position(), move(node))));
  734. adopt(static_cast<AST::Node&>(*new AST::Execute(next_in_chain.node->position(), move(node))))->run(*this);
  735. };
  736. switch (next_in_chain.action) {
  737. case AST::NodeWithAction::And:
  738. if (head_exit_code == 0)
  739. evaluate();
  740. break;
  741. case AST::NodeWithAction::Or:
  742. if (head_exit_code != 0)
  743. evaluate();
  744. break;
  745. case AST::NodeWithAction::Sequence:
  746. evaluate();
  747. break;
  748. }
  749. }
  750. void Shell::run_tail(RefPtr<Job> job)
  751. {
  752. if (auto cmd = job->command_ptr()) {
  753. deferred_invoke([=, this](auto&) {
  754. for (auto& next_in_chain : cmd->next_chain) {
  755. run_tail(*cmd, next_in_chain, job->exit_code());
  756. }
  757. });
  758. }
  759. }
  760. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  761. {
  762. NonnullRefPtrVector<Job> spawned_jobs;
  763. for (auto& command : commands) {
  764. #ifdef SH_DEBUG
  765. dbg() << "Command";
  766. for (auto& arg : command.argv)
  767. dbg() << "argv: " << arg;
  768. for (auto& redir : command.redirections) {
  769. if (redir.is_path_redirection()) {
  770. auto path_redir = (const AST::PathRedirection*)&redir;
  771. dbg() << "redir path " << (int)path_redir->direction << " " << path_redir->path << " <-> " << path_redir->fd;
  772. } else if (redir.is_fd_redirection()) {
  773. auto* fdredir = (const AST::FdRedirection*)&redir;
  774. dbg() << "redir fd " << fdredir->old_fd << " -> " << fdredir->new_fd;
  775. } else if (redir.is_close_redirection()) {
  776. auto close_redir = (const AST::CloseRedirection*)&redir;
  777. dbg() << "close fd " << close_redir->fd;
  778. } else {
  779. ASSERT_NOT_REACHED();
  780. }
  781. }
  782. #endif
  783. auto job = run_command(command);
  784. if (!job)
  785. continue;
  786. spawned_jobs.append(*job);
  787. if (command.should_wait) {
  788. block_on_job(job);
  789. } else {
  790. job->set_running_in_background(true);
  791. if (!command.is_pipe_source && command.should_notify_if_in_background)
  792. job->set_should_announce_exit(true);
  793. }
  794. }
  795. return spawned_jobs;
  796. }
  797. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  798. {
  799. TemporaryChange script_change { current_script, filename };
  800. TemporaryChange interactive_change { m_is_interactive, false };
  801. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  802. if (file_result.is_error()) {
  803. if (explicitly_invoked)
  804. fprintf(stderr, "Failed to open %s: %s\n", filename.characters(), file_result.error().characters());
  805. else
  806. dbg() << "open() failed for '" << filename << "' with " << file_result.error();
  807. return false;
  808. }
  809. auto file = file_result.value();
  810. auto data = file->read_all();
  811. run_command(data);
  812. return true;
  813. }
  814. void Shell::restore_ios()
  815. {
  816. if (m_is_subshell)
  817. return;
  818. tcsetattr(0, TCSANOW, &termios);
  819. tcsetpgrp(STDOUT_FILENO, m_pid);
  820. tcsetpgrp(STDIN_FILENO, m_pid);
  821. }
  822. void Shell::block_on_pipeline(RefPtr<AST::Pipeline> pipeline)
  823. {
  824. if (!pipeline)
  825. return;
  826. for (auto& it : jobs) {
  827. if (auto cmd = it.value->command_ptr(); cmd->pipeline == pipeline && cmd->is_pipe_source)
  828. block_on_job(it.value);
  829. }
  830. }
  831. void Shell::block_on_job(RefPtr<Job> job)
  832. {
  833. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  834. if (!job)
  835. return;
  836. if (job->is_suspended())
  837. return; // We cannot wait for a suspended job.
  838. ScopeGuard io_restorer { [&]() {
  839. if (job->exited() && !job->is_running_in_background()) {
  840. restore_ios();
  841. }
  842. } };
  843. Core::EventLoop loop;
  844. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  845. if (old_exit)
  846. old_exit(job);
  847. loop.quit(0);
  848. };
  849. if (job->exited())
  850. return;
  851. loop.exec();
  852. // If the job is part of a pipeline, wait for the rest of the members too.
  853. if (auto command = job->command_ptr())
  854. block_on_pipeline(command->pipeline);
  855. }
  856. String Shell::get_history_path()
  857. {
  858. if (auto histfile = getenv("HISTFILE"))
  859. return { histfile };
  860. return String::formatted("{}/.history", home);
  861. }
  862. String Shell::escape_token(const String& token)
  863. {
  864. StringBuilder builder;
  865. for (auto c : token) {
  866. switch (c) {
  867. case '\'':
  868. case '"':
  869. case '$':
  870. case '|':
  871. case '>':
  872. case '<':
  873. case '&':
  874. case '\\':
  875. case ' ':
  876. builder.append('\\');
  877. break;
  878. default:
  879. break;
  880. }
  881. builder.append(c);
  882. }
  883. return builder.build();
  884. }
  885. String Shell::unescape_token(const String& token)
  886. {
  887. StringBuilder builder;
  888. enum {
  889. Free,
  890. Escaped
  891. } state { Free };
  892. for (auto c : token) {
  893. switch (state) {
  894. case Escaped:
  895. builder.append(c);
  896. state = Free;
  897. break;
  898. case Free:
  899. if (c == '\\')
  900. state = Escaped;
  901. else
  902. builder.append(c);
  903. break;
  904. }
  905. }
  906. if (state == Escaped)
  907. builder.append('\\');
  908. return builder.build();
  909. }
  910. void Shell::cache_path()
  911. {
  912. if (!cached_path.is_empty())
  913. cached_path.clear_with_capacity();
  914. // Add shell builtins to the cache.
  915. for (const auto& builtin_name : builtin_names)
  916. cached_path.append(escape_token(builtin_name));
  917. // Add aliases to the cache.
  918. for (const auto& alias : m_aliases) {
  919. auto name = escape_token(alias.key);
  920. if (cached_path.contains_slow(name))
  921. continue;
  922. cached_path.append(name);
  923. }
  924. String path = getenv("PATH");
  925. if (!path.is_empty()) {
  926. auto directories = path.split(':');
  927. for (const auto& directory : directories) {
  928. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  929. while (programs.has_next()) {
  930. auto program = programs.next_path();
  931. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  932. auto escaped_name = escape_token(program);
  933. if (cached_path.contains_slow(escaped_name))
  934. continue;
  935. if (access(program_path.characters(), X_OK) == 0)
  936. cached_path.append(escaped_name);
  937. }
  938. }
  939. }
  940. quick_sort(cached_path);
  941. }
  942. void Shell::add_entry_to_cache(const String& entry)
  943. {
  944. size_t index = 0;
  945. auto match = binary_search(
  946. cached_path.span(), entry, [](const String& name, const String& program) -> int {
  947. return strcmp(name.characters(), program.characters());
  948. },
  949. &index);
  950. if (match)
  951. return;
  952. while (index < cached_path.size() && strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  953. index++;
  954. }
  955. cached_path.insert(index, entry);
  956. }
  957. void Shell::highlight(Line::Editor& editor) const
  958. {
  959. auto line = editor.line();
  960. Parser parser(line);
  961. auto ast = parser.parse();
  962. if (!ast)
  963. return;
  964. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  965. }
  966. Vector<Line::CompletionSuggestion> Shell::complete()
  967. {
  968. auto line = m_editor->line(m_editor->cursor());
  969. Parser parser(line);
  970. auto ast = parser.parse();
  971. if (!ast)
  972. return {};
  973. return ast->complete_for_editor(*this, line.length());
  974. }
  975. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  976. {
  977. auto token = offset ? part.substring_view(0, offset) : "";
  978. StringView original_token = token;
  979. String path;
  980. ssize_t last_slash = token.length() - 1;
  981. while (last_slash >= 0 && token[last_slash] != '/')
  982. --last_slash;
  983. StringBuilder path_builder;
  984. auto init_slash_part = token.substring_view(0, last_slash + 1);
  985. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  986. // Depending on the base, we will have to prepend cwd.
  987. if (base.is_empty()) {
  988. // '' /foo -> absolute
  989. // '' foo -> relative
  990. if (!token.starts_with('/'))
  991. path_builder.append(cwd);
  992. path_builder.append('/');
  993. path_builder.append(init_slash_part);
  994. } else {
  995. // /foo * -> absolute
  996. // foo * -> relative
  997. if (!base.starts_with('/'))
  998. path_builder.append(cwd);
  999. path_builder.append('/');
  1000. path_builder.append(base);
  1001. path_builder.append('/');
  1002. path_builder.append(init_slash_part);
  1003. }
  1004. path = path_builder.build();
  1005. token = last_slash_part;
  1006. // the invariant part of the token is actually just the last segment
  1007. // e. in `cd /foo/bar', 'bar' is the invariant
  1008. // since we are not suggesting anything starting with
  1009. // `/foo/', but rather just `bar...'
  1010. auto token_length = escape_token(token).length();
  1011. if (m_editor)
  1012. m_editor->suggest(token_length, original_token.length() - token_length);
  1013. // only suggest dot-files if path starts with a dot
  1014. Core::DirIterator files(path,
  1015. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1016. Vector<Line::CompletionSuggestion> suggestions;
  1017. while (files.has_next()) {
  1018. auto file = files.next_path();
  1019. if (file.starts_with(token)) {
  1020. struct stat program_status;
  1021. String file_path = String::format("%s/%s", path.characters(), file.characters());
  1022. int stat_error = stat(file_path.characters(), &program_status);
  1023. if (!stat_error) {
  1024. if (S_ISDIR(program_status.st_mode)) {
  1025. suggestions.append({ escape_token(file), "/" });
  1026. } else {
  1027. suggestions.append({ escape_token(file), " " });
  1028. }
  1029. suggestions.last().input_offset = token_length;
  1030. }
  1031. }
  1032. }
  1033. return suggestions;
  1034. }
  1035. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  1036. {
  1037. auto match = binary_search(cached_path.span(), name, [](const String& name, const String& program) -> int {
  1038. return strncmp(name.characters(), program.characters(), name.length());
  1039. });
  1040. if (!match)
  1041. return complete_path("", name, offset);
  1042. String completion = *match;
  1043. auto token_length = escape_token(name).length();
  1044. if (m_editor)
  1045. m_editor->suggest(token_length, 0);
  1046. // Now that we have a program name starting with our token, we look at
  1047. // other program names starting with our token and cut off any mismatching
  1048. // characters.
  1049. Vector<Line::CompletionSuggestion> suggestions;
  1050. int index = match - cached_path.data();
  1051. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  1052. suggestions.append({ cached_path[i], " " });
  1053. suggestions.last().input_offset = token_length;
  1054. }
  1055. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  1056. suggestions.append({ cached_path[i], " " });
  1057. suggestions.last().input_offset = token_length;
  1058. }
  1059. suggestions.append({ cached_path[index], " " });
  1060. suggestions.last().input_offset = token_length;
  1061. return suggestions;
  1062. }
  1063. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  1064. {
  1065. Vector<Line::CompletionSuggestion> suggestions;
  1066. auto pattern = offset ? name.substring_view(0, offset) : "";
  1067. if (m_editor)
  1068. m_editor->suggest(offset);
  1069. // Look at local variables.
  1070. for (auto& frame : m_local_frames) {
  1071. for (auto& variable : frame.local_variables) {
  1072. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1073. suggestions.append(variable.key);
  1074. }
  1075. }
  1076. // Look at the environment.
  1077. for (auto i = 0; environ[i]; ++i) {
  1078. auto entry = StringView { environ[i] };
  1079. if (entry.starts_with(pattern)) {
  1080. auto parts = entry.split_view('=');
  1081. if (parts.is_empty() || parts.first().is_empty())
  1082. continue;
  1083. String name = parts.first();
  1084. if (suggestions.contains_slow(name))
  1085. continue;
  1086. suggestions.append(move(name));
  1087. suggestions.last().input_offset = offset;
  1088. }
  1089. }
  1090. return suggestions;
  1091. }
  1092. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  1093. {
  1094. Vector<Line::CompletionSuggestion> suggestions;
  1095. auto pattern = offset ? name.substring_view(0, offset) : "";
  1096. if (m_editor)
  1097. m_editor->suggest(offset);
  1098. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1099. if (di.has_error())
  1100. return suggestions;
  1101. while (di.has_next()) {
  1102. String name = di.next_path();
  1103. if (name.starts_with(pattern)) {
  1104. suggestions.append(name);
  1105. suggestions.last().input_offset = offset;
  1106. }
  1107. }
  1108. return suggestions;
  1109. }
  1110. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  1111. {
  1112. size_t start = 0;
  1113. while (start < option.length() && option[start] == '-' && start < 2)
  1114. ++start;
  1115. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  1116. if (m_editor)
  1117. m_editor->suggest(offset);
  1118. Vector<Line::CompletionSuggestion> suggestions;
  1119. dbg() << "Shell::complete_option(" << program_name << ", " << option_pattern << ")";
  1120. // FIXME: Figure out how to do this stuff.
  1121. if (has_builtin(program_name)) {
  1122. // Complete builtins.
  1123. if (program_name == "setopt") {
  1124. bool negate = false;
  1125. if (option_pattern.starts_with("no_")) {
  1126. negate = true;
  1127. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  1128. }
  1129. auto maybe_negate = [&](const StringView& view) {
  1130. static StringBuilder builder;
  1131. builder.clear();
  1132. builder.append("--");
  1133. if (negate)
  1134. builder.append("no_");
  1135. builder.append(view);
  1136. return builder.to_string();
  1137. };
  1138. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  1139. if (StringView { #name }.starts_with(option_pattern)) { \
  1140. suggestions.append(maybe_negate(#name)); \
  1141. suggestions.last().input_offset = offset; \
  1142. }
  1143. ENUMERATE_SHELL_OPTIONS();
  1144. #undef __ENUMERATE_SHELL_OPTION
  1145. return suggestions;
  1146. }
  1147. }
  1148. return suggestions;
  1149. }
  1150. void Shell::bring_cursor_to_beginning_of_a_line() const
  1151. {
  1152. struct winsize ws;
  1153. if (m_editor) {
  1154. ws = m_editor->terminal_size();
  1155. } else {
  1156. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1157. // Very annoying assumptions.
  1158. ws.ws_col = 80;
  1159. ws.ws_row = 25;
  1160. }
  1161. }
  1162. // Black with Cyan background.
  1163. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1164. String eol_mark = getenv("PROMPT_EOL_MARK");
  1165. if (eol_mark.is_null())
  1166. eol_mark = default_mark;
  1167. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_lengths.last();
  1168. if (eol_mark_length >= ws.ws_col) {
  1169. eol_mark = default_mark;
  1170. eol_mark_length = 1;
  1171. }
  1172. fputs(eol_mark.characters(), stderr);
  1173. for (auto i = eol_mark_length; i < ws.ws_col; ++i)
  1174. putc(' ', stderr);
  1175. putc('\r', stderr);
  1176. }
  1177. bool Shell::read_single_line()
  1178. {
  1179. restore_ios();
  1180. bring_cursor_to_beginning_of_a_line();
  1181. auto line_result = m_editor->get_line(prompt());
  1182. if (line_result.is_error()) {
  1183. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1184. // Pretend the user tried to execute builtin_exit()
  1185. run_command("exit");
  1186. return read_single_line();
  1187. } else {
  1188. Core::EventLoop::current().quit(1);
  1189. return false;
  1190. }
  1191. }
  1192. auto& line = line_result.value();
  1193. if (line.is_empty())
  1194. return true;
  1195. run_command(line);
  1196. m_editor->add_to_history(line);
  1197. return true;
  1198. }
  1199. void Shell::custom_event(Core::CustomEvent& event)
  1200. {
  1201. if (event.custom_type() == ReadLine) {
  1202. if (read_single_line())
  1203. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1204. return;
  1205. }
  1206. }
  1207. void Shell::notify_child_event()
  1208. {
  1209. #ifdef ENSURE_WAITID_ONCE
  1210. static HashTable<pid_t> s_waited_for_pids;
  1211. #endif
  1212. Vector<u64> disowned_jobs;
  1213. // Workaround the fact that we can't receive *who* exactly changed state.
  1214. // The child might still be alive (and even running) when this signal is dispatched to us
  1215. // so just...repeat until we find a suitable child.
  1216. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1217. // until the next child event we can actually handle.
  1218. bool found_child = false;
  1219. do {
  1220. // Ignore stray SIGCHLD when there are no jobs.
  1221. if (jobs.is_empty())
  1222. return;
  1223. for (auto& it : jobs) {
  1224. auto job_id = it.key;
  1225. auto& job = *it.value;
  1226. #ifdef ENSURE_WAITID_ONCE
  1227. // Theoretically, this should never trip, as jobs are removed from
  1228. // the job table when waitpid() succeeds *and* the child is dead.
  1229. ASSERT(!s_waited_for_pids.contains(job.pid()));
  1230. #endif
  1231. int wstatus = 0;
  1232. #ifdef SH_DEBUG
  1233. dbgln("waitpid({}) = ...", job.pid());
  1234. #endif
  1235. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1236. #ifdef SH_DEBUG
  1237. dbgln("... = {} - {}", child_pid, wstatus);
  1238. #endif
  1239. if (child_pid < 0) {
  1240. if (errno == ECHILD) {
  1241. // The child process went away before we could process its death, just assume it exited all ok.
  1242. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1243. dbg() << "Child process gone, cannot get exit code for " << job_id;
  1244. child_pid = job.pid();
  1245. } else {
  1246. ASSERT_NOT_REACHED();
  1247. }
  1248. }
  1249. if (child_pid == 0) {
  1250. // If the child existed, but wasn't dead.
  1251. continue;
  1252. }
  1253. if (child_pid == job.pid()) {
  1254. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1255. job.set_signalled(WTERMSIG(wstatus));
  1256. } else if (WIFEXITED(wstatus)) {
  1257. job.set_has_exit(WEXITSTATUS(wstatus));
  1258. } else if (WIFSTOPPED(wstatus)) {
  1259. job.unblock();
  1260. job.set_is_suspended(true);
  1261. }
  1262. found_child = true;
  1263. #ifdef ENSURE_WAITID_ONCE
  1264. // NOTE: This check is here to find bugs about our assumptions about waitpid(),
  1265. // it does not hold in general, and it definitely does not hold in the long run.
  1266. // Reasons that we would call waitpid() more than once:
  1267. // - PID reuse/wraparound: This will simply fail the assertion, ignored here.
  1268. // - Non-terminating unblocks:
  1269. // - Suspension: (e.g. via ^Z)
  1270. // - ?
  1271. // - ?
  1272. if (job.exited())
  1273. s_waited_for_pids.set(child_pid);
  1274. #endif
  1275. }
  1276. if (job.should_be_disowned())
  1277. disowned_jobs.append(job_id);
  1278. }
  1279. for (auto job_id : disowned_jobs) {
  1280. jobs.remove(job_id);
  1281. }
  1282. } while (!found_child);
  1283. }
  1284. Shell::Shell()
  1285. : m_default_constructed(true)
  1286. {
  1287. push_frame("main").leak_frame();
  1288. int rc = gethostname(hostname, Shell::HostNameSize);
  1289. if (rc < 0)
  1290. perror("gethostname");
  1291. {
  1292. auto* pw = getpwuid(getuid());
  1293. if (pw) {
  1294. username = pw->pw_name;
  1295. home = pw->pw_dir;
  1296. setenv("HOME", pw->pw_dir, 1);
  1297. }
  1298. endpwent();
  1299. }
  1300. // For simplicity, start at the user's home directory.
  1301. this->cwd = home;
  1302. setenv("PWD", home.characters(), 1);
  1303. // Add the default PATH vars.
  1304. {
  1305. StringBuilder path;
  1306. path.append(getenv("PATH"));
  1307. if (path.length())
  1308. path.append(":");
  1309. path.append("/bin:/usr/bin:/usr/local/bin");
  1310. setenv("PATH", path.to_string().characters(), true);
  1311. }
  1312. cache_path();
  1313. }
  1314. Shell::Shell(Line::Editor& editor)
  1315. : m_editor(editor)
  1316. {
  1317. uid = getuid();
  1318. tcsetpgrp(0, getpgrp());
  1319. m_pid = getpid();
  1320. push_frame("main").leak_frame();
  1321. int rc = gethostname(hostname, Shell::HostNameSize);
  1322. if (rc < 0)
  1323. perror("gethostname");
  1324. auto istty = isatty(STDIN_FILENO);
  1325. m_is_interactive = istty;
  1326. if (istty) {
  1327. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1328. if (rc < 0)
  1329. perror("ttyname_r");
  1330. } else {
  1331. ttyname[0] = 0;
  1332. }
  1333. {
  1334. auto* cwd = getcwd(nullptr, 0);
  1335. this->cwd = cwd;
  1336. setenv("PWD", cwd, 1);
  1337. free(cwd);
  1338. }
  1339. {
  1340. auto* pw = getpwuid(getuid());
  1341. if (pw) {
  1342. username = pw->pw_name;
  1343. home = pw->pw_dir;
  1344. setenv("HOME", pw->pw_dir, 1);
  1345. }
  1346. endpwent();
  1347. }
  1348. directory_stack.append(cwd);
  1349. m_editor->load_history(get_history_path());
  1350. cache_path();
  1351. m_editor->register_key_input_callback('\n', [](Line::Editor& editor) {
  1352. auto ast = Parser(editor.line()).parse();
  1353. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1354. return true;
  1355. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1356. });
  1357. }
  1358. Shell::~Shell()
  1359. {
  1360. if (m_default_constructed)
  1361. return;
  1362. stop_all_jobs();
  1363. m_editor->save_history(get_history_path());
  1364. }
  1365. void Shell::stop_all_jobs()
  1366. {
  1367. if (!jobs.is_empty()) {
  1368. if (m_is_interactive && !m_is_subshell)
  1369. printf("Killing active jobs\n");
  1370. for (auto& entry : jobs) {
  1371. if (entry.value->is_suspended()) {
  1372. #ifdef SH_DEBUG
  1373. dbg() << "Job " << entry.value->pid() << " is suspended";
  1374. #endif
  1375. kill_job(entry.value, SIGCONT);
  1376. }
  1377. kill_job(entry.value, SIGHUP);
  1378. }
  1379. usleep(10000); // Wait for a bit before killing the job
  1380. for (auto& entry : jobs) {
  1381. #ifdef SH_DEBUG
  1382. dbg() << "Actively killing " << entry.value->pid() << "(" << entry.value->cmd() << ")";
  1383. #endif
  1384. kill_job(entry.value, SIGKILL);
  1385. }
  1386. jobs.clear();
  1387. }
  1388. }
  1389. u64 Shell::find_last_job_id() const
  1390. {
  1391. u64 job_id = 0;
  1392. for (auto& entry : jobs) {
  1393. if (entry.value->job_id() > job_id)
  1394. job_id = entry.value->job_id();
  1395. }
  1396. return job_id;
  1397. }
  1398. const Job* Shell::find_job(u64 id)
  1399. {
  1400. for (auto& entry : jobs) {
  1401. if (entry.value->job_id() == id)
  1402. return entry.value;
  1403. }
  1404. return nullptr;
  1405. }
  1406. void Shell::kill_job(const Job* job, int sig)
  1407. {
  1408. if (!job)
  1409. return;
  1410. if (killpg(job->pgid(), sig) < 0) {
  1411. if (kill(job->pid(), sig) < 0) {
  1412. perror("kill");
  1413. }
  1414. }
  1415. }
  1416. void Shell::save_to(JsonObject& object)
  1417. {
  1418. Core::Object::save_to(object);
  1419. object.set("working_directory", cwd);
  1420. object.set("username", username);
  1421. object.set("user_home_path", home);
  1422. object.set("user_id", uid);
  1423. object.set("directory_stack_size", directory_stack.size());
  1424. object.set("cd_history_size", cd_history.size());
  1425. // Jobs.
  1426. JsonArray job_objects;
  1427. for (auto& job_entry : jobs) {
  1428. JsonObject job_object;
  1429. job_object.set("pid", job_entry.value->pid());
  1430. job_object.set("pgid", job_entry.value->pgid());
  1431. job_object.set("running_time", job_entry.value->timer().elapsed());
  1432. job_object.set("command", job_entry.value->cmd());
  1433. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1434. job_objects.append(move(job_object));
  1435. }
  1436. object.set("jobs", move(job_objects));
  1437. }
  1438. void FileDescriptionCollector::collect()
  1439. {
  1440. for (auto fd : m_fds)
  1441. close(fd);
  1442. m_fds.clear();
  1443. }
  1444. FileDescriptionCollector::~FileDescriptionCollector()
  1445. {
  1446. collect();
  1447. }
  1448. void FileDescriptionCollector::add(int fd)
  1449. {
  1450. m_fds.append(fd);
  1451. }
  1452. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  1453. {
  1454. for (auto& rewiring : intended_rewirings) {
  1455. int new_fd = dup(rewiring.new_fd);
  1456. if (new_fd < 0) {
  1457. if (errno != EBADF)
  1458. perror("dup");
  1459. // The fd that will be overwritten isn't open right now,
  1460. // it will be cleaned up by the exec()-side collector
  1461. // and we have nothing to do here, so just ignore this error.
  1462. continue;
  1463. }
  1464. auto flags = fcntl(new_fd, F_GETFL);
  1465. auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC);
  1466. ASSERT(rc == 0);
  1467. m_saves.append({ rewiring.new_fd, new_fd });
  1468. m_collector.add(new_fd);
  1469. }
  1470. }
  1471. SavedFileDescriptors::~SavedFileDescriptors()
  1472. {
  1473. for (auto& save : m_saves) {
  1474. if (dup2(save.saved, save.original) < 0) {
  1475. perror("dup2(~SavedFileDescriptors)");
  1476. continue;
  1477. }
  1478. }
  1479. }
  1480. }