Shell.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  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. fprintf(stderr, "Shell: Job %" PRIu64 "(%s) exited\n", job->job_id(), job->cmd().characters());
  720. last_return_code = job->exit_code();
  721. job->disown();
  722. run_tail(job);
  723. };
  724. fds.collect();
  725. return *job;
  726. }
  727. void Shell::run_tail(const AST::Command& invoking_command, const AST::NodeWithAction& next_in_chain, int head_exit_code)
  728. {
  729. auto evaluate = [&] {
  730. if (next_in_chain.node->would_execute()) {
  731. next_in_chain.node->run(*this);
  732. return;
  733. }
  734. auto node = next_in_chain.node;
  735. if (!invoking_command.should_wait)
  736. node = adopt(static_cast<AST::Node&>(*new AST::Background(next_in_chain.node->position(), move(node))));
  737. adopt(static_cast<AST::Node&>(*new AST::Execute(next_in_chain.node->position(), move(node))))->run(*this);
  738. };
  739. switch (next_in_chain.action) {
  740. case AST::NodeWithAction::And:
  741. if (head_exit_code == 0)
  742. evaluate();
  743. break;
  744. case AST::NodeWithAction::Or:
  745. if (head_exit_code != 0)
  746. evaluate();
  747. break;
  748. case AST::NodeWithAction::Sequence:
  749. evaluate();
  750. break;
  751. }
  752. }
  753. void Shell::run_tail(RefPtr<Job> job)
  754. {
  755. if (auto cmd = job->command_ptr()) {
  756. deferred_invoke([=, this](auto&) {
  757. for (auto& next_in_chain : cmd->next_chain) {
  758. run_tail(*cmd, next_in_chain, job->exit_code());
  759. }
  760. });
  761. }
  762. }
  763. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  764. {
  765. NonnullRefPtrVector<Job> spawned_jobs;
  766. for (auto& command : commands) {
  767. #ifdef SH_DEBUG
  768. dbgln("Command");
  769. for (auto& arg : command.argv)
  770. dbgln("argv: {}", arg);
  771. for (auto& redir : command.redirections) {
  772. if (redir.is_path_redirection()) {
  773. auto path_redir = (const AST::PathRedirection*)&redir;
  774. dbgln("redir path '{}' <-({})-> {}", path_redir->path, (int)path_redir->direction, path_redir->fd);
  775. } else if (redir.is_fd_redirection()) {
  776. auto* fdredir = (const AST::FdRedirection*)&redir;
  777. dbgln("redir fd {} -> {}", fdredir->old_fd, fdredir->new_fd);
  778. } else if (redir.is_close_redirection()) {
  779. auto close_redir = (const AST::CloseRedirection*)&redir;
  780. dbgln("close fd {}", close_redir->fd);
  781. } else {
  782. ASSERT_NOT_REACHED();
  783. }
  784. }
  785. #endif
  786. auto job = run_command(command);
  787. if (!job)
  788. continue;
  789. spawned_jobs.append(*job);
  790. if (command.should_wait) {
  791. block_on_job(job);
  792. } else {
  793. job->set_running_in_background(true);
  794. if (!command.is_pipe_source && command.should_notify_if_in_background)
  795. job->set_should_announce_exit(true);
  796. }
  797. }
  798. return spawned_jobs;
  799. }
  800. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  801. {
  802. TemporaryChange script_change { current_script, filename };
  803. TemporaryChange interactive_change { m_is_interactive, false };
  804. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  805. if (file_result.is_error()) {
  806. if (explicitly_invoked)
  807. fprintf(stderr, "Failed to open %s: %s\n", filename.characters(), file_result.error().characters());
  808. else
  809. dbgln("open() failed for '{}' with {}", filename, file_result.error());
  810. return false;
  811. }
  812. auto file = file_result.value();
  813. auto data = file->read_all();
  814. run_command(data);
  815. return true;
  816. }
  817. void Shell::restore_ios()
  818. {
  819. if (m_is_subshell)
  820. return;
  821. tcsetattr(0, TCSANOW, &termios);
  822. tcsetpgrp(STDOUT_FILENO, m_pid);
  823. tcsetpgrp(STDIN_FILENO, m_pid);
  824. }
  825. void Shell::block_on_pipeline(RefPtr<AST::Pipeline> pipeline)
  826. {
  827. if (!pipeline)
  828. return;
  829. for (auto& it : jobs) {
  830. if (auto cmd = it.value->command_ptr(); cmd->pipeline == pipeline && cmd->is_pipe_source)
  831. block_on_job(it.value);
  832. }
  833. }
  834. void Shell::block_on_job(RefPtr<Job> job)
  835. {
  836. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  837. if (!job)
  838. return;
  839. if (job->is_suspended())
  840. return; // We cannot wait for a suspended job.
  841. ScopeGuard io_restorer { [&]() {
  842. if (job->exited() && !job->is_running_in_background()) {
  843. restore_ios();
  844. }
  845. } };
  846. Core::EventLoop loop;
  847. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  848. if (old_exit)
  849. old_exit(job);
  850. loop.quit(0);
  851. };
  852. if (job->exited())
  853. return;
  854. loop.exec();
  855. // If the job is part of a pipeline, wait for the rest of the members too.
  856. if (auto command = job->command_ptr())
  857. block_on_pipeline(command->pipeline);
  858. }
  859. String Shell::get_history_path()
  860. {
  861. if (auto histfile = getenv("HISTFILE"))
  862. return { histfile };
  863. return String::formatted("{}/.history", home);
  864. }
  865. String Shell::escape_token(const String& token)
  866. {
  867. StringBuilder builder;
  868. for (auto c : token) {
  869. switch (c) {
  870. case '\'':
  871. case '"':
  872. case '$':
  873. case '|':
  874. case '>':
  875. case '<':
  876. case '&':
  877. case '\\':
  878. case ' ':
  879. builder.append('\\');
  880. break;
  881. default:
  882. break;
  883. }
  884. builder.append(c);
  885. }
  886. return builder.build();
  887. }
  888. String Shell::unescape_token(const String& token)
  889. {
  890. StringBuilder builder;
  891. enum {
  892. Free,
  893. Escaped
  894. } state { Free };
  895. for (auto c : token) {
  896. switch (state) {
  897. case Escaped:
  898. builder.append(c);
  899. state = Free;
  900. break;
  901. case Free:
  902. if (c == '\\')
  903. state = Escaped;
  904. else
  905. builder.append(c);
  906. break;
  907. }
  908. }
  909. if (state == Escaped)
  910. builder.append('\\');
  911. return builder.build();
  912. }
  913. void Shell::cache_path()
  914. {
  915. if (!cached_path.is_empty())
  916. cached_path.clear_with_capacity();
  917. // Add shell builtins to the cache.
  918. for (const auto& builtin_name : builtin_names)
  919. cached_path.append(escape_token(builtin_name));
  920. // Add aliases to the cache.
  921. for (const auto& alias : m_aliases) {
  922. auto name = escape_token(alias.key);
  923. if (cached_path.contains_slow(name))
  924. continue;
  925. cached_path.append(name);
  926. }
  927. String path = getenv("PATH");
  928. if (!path.is_empty()) {
  929. auto directories = path.split(':');
  930. for (const auto& directory : directories) {
  931. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  932. while (programs.has_next()) {
  933. auto program = programs.next_path();
  934. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  935. auto escaped_name = escape_token(program);
  936. if (cached_path.contains_slow(escaped_name))
  937. continue;
  938. if (access(program_path.characters(), X_OK) == 0)
  939. cached_path.append(escaped_name);
  940. }
  941. }
  942. }
  943. quick_sort(cached_path);
  944. }
  945. void Shell::add_entry_to_cache(const String& entry)
  946. {
  947. size_t index = 0;
  948. auto match = binary_search(
  949. cached_path.span(), entry, [](const String& name, const String& program) -> int {
  950. return strcmp(name.characters(), program.characters());
  951. },
  952. &index);
  953. if (match)
  954. return;
  955. while (index < cached_path.size() && strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  956. index++;
  957. }
  958. cached_path.insert(index, entry);
  959. }
  960. void Shell::highlight(Line::Editor& editor) const
  961. {
  962. auto line = editor.line();
  963. Parser parser(line);
  964. auto ast = parser.parse();
  965. if (!ast)
  966. return;
  967. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  968. }
  969. Vector<Line::CompletionSuggestion> Shell::complete()
  970. {
  971. auto line = m_editor->line(m_editor->cursor());
  972. Parser parser(line);
  973. auto ast = parser.parse();
  974. if (!ast)
  975. return {};
  976. return ast->complete_for_editor(*this, line.length());
  977. }
  978. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  979. {
  980. auto token = offset ? part.substring_view(0, offset) : "";
  981. StringView original_token = token;
  982. String path;
  983. ssize_t last_slash = token.length() - 1;
  984. while (last_slash >= 0 && token[last_slash] != '/')
  985. --last_slash;
  986. StringBuilder path_builder;
  987. auto init_slash_part = token.substring_view(0, last_slash + 1);
  988. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  989. // Depending on the base, we will have to prepend cwd.
  990. if (base.is_empty()) {
  991. // '' /foo -> absolute
  992. // '' foo -> relative
  993. if (!token.starts_with('/'))
  994. path_builder.append(cwd);
  995. path_builder.append('/');
  996. path_builder.append(init_slash_part);
  997. } else {
  998. // /foo * -> absolute
  999. // foo * -> relative
  1000. if (!base.starts_with('/'))
  1001. path_builder.append(cwd);
  1002. path_builder.append('/');
  1003. path_builder.append(base);
  1004. path_builder.append('/');
  1005. path_builder.append(init_slash_part);
  1006. }
  1007. path = path_builder.build();
  1008. token = last_slash_part;
  1009. // the invariant part of the token is actually just the last segment
  1010. // e. in `cd /foo/bar', 'bar' is the invariant
  1011. // since we are not suggesting anything starting with
  1012. // `/foo/', but rather just `bar...'
  1013. auto token_length = escape_token(token).length();
  1014. if (m_editor)
  1015. m_editor->suggest(token_length, original_token.length() - token_length);
  1016. // only suggest dot-files if path starts with a dot
  1017. Core::DirIterator files(path,
  1018. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1019. Vector<Line::CompletionSuggestion> suggestions;
  1020. while (files.has_next()) {
  1021. auto file = files.next_path();
  1022. if (file.starts_with(token)) {
  1023. struct stat program_status;
  1024. String file_path = String::format("%s/%s", path.characters(), file.characters());
  1025. int stat_error = stat(file_path.characters(), &program_status);
  1026. if (!stat_error) {
  1027. if (S_ISDIR(program_status.st_mode)) {
  1028. suggestions.append({ escape_token(file), "/" });
  1029. } else {
  1030. suggestions.append({ escape_token(file), " " });
  1031. }
  1032. suggestions.last().input_offset = token_length;
  1033. }
  1034. }
  1035. }
  1036. return suggestions;
  1037. }
  1038. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  1039. {
  1040. auto match = binary_search(cached_path.span(), name, [](const String& name, const String& program) -> int {
  1041. return strncmp(name.characters(), program.characters(), name.length());
  1042. });
  1043. if (!match)
  1044. return complete_path("", name, offset);
  1045. String completion = *match;
  1046. auto token_length = escape_token(name).length();
  1047. if (m_editor)
  1048. m_editor->suggest(token_length, 0);
  1049. // Now that we have a program name starting with our token, we look at
  1050. // other program names starting with our token and cut off any mismatching
  1051. // characters.
  1052. Vector<Line::CompletionSuggestion> suggestions;
  1053. int index = match - cached_path.data();
  1054. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  1055. suggestions.append({ cached_path[i], " " });
  1056. suggestions.last().input_offset = token_length;
  1057. }
  1058. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  1059. suggestions.append({ cached_path[i], " " });
  1060. suggestions.last().input_offset = token_length;
  1061. }
  1062. suggestions.append({ cached_path[index], " " });
  1063. suggestions.last().input_offset = token_length;
  1064. return suggestions;
  1065. }
  1066. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  1067. {
  1068. Vector<Line::CompletionSuggestion> suggestions;
  1069. auto pattern = offset ? name.substring_view(0, offset) : "";
  1070. if (m_editor)
  1071. m_editor->suggest(offset);
  1072. // Look at local variables.
  1073. for (auto& frame : m_local_frames) {
  1074. for (auto& variable : frame.local_variables) {
  1075. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1076. suggestions.append(variable.key);
  1077. }
  1078. }
  1079. // Look at the environment.
  1080. for (auto i = 0; environ[i]; ++i) {
  1081. auto entry = StringView { environ[i] };
  1082. if (entry.starts_with(pattern)) {
  1083. auto parts = entry.split_view('=');
  1084. if (parts.is_empty() || parts.first().is_empty())
  1085. continue;
  1086. String name = parts.first();
  1087. if (suggestions.contains_slow(name))
  1088. continue;
  1089. suggestions.append(move(name));
  1090. suggestions.last().input_offset = offset;
  1091. }
  1092. }
  1093. return suggestions;
  1094. }
  1095. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  1096. {
  1097. Vector<Line::CompletionSuggestion> suggestions;
  1098. auto pattern = offset ? name.substring_view(0, offset) : "";
  1099. if (m_editor)
  1100. m_editor->suggest(offset);
  1101. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1102. if (di.has_error())
  1103. return suggestions;
  1104. while (di.has_next()) {
  1105. String name = di.next_path();
  1106. if (name.starts_with(pattern)) {
  1107. suggestions.append(name);
  1108. suggestions.last().input_offset = offset;
  1109. }
  1110. }
  1111. return suggestions;
  1112. }
  1113. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  1114. {
  1115. size_t start = 0;
  1116. while (start < option.length() && option[start] == '-' && start < 2)
  1117. ++start;
  1118. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  1119. if (m_editor)
  1120. m_editor->suggest(offset);
  1121. Vector<Line::CompletionSuggestion> suggestions;
  1122. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1123. // FIXME: Figure out how to do this stuff.
  1124. if (has_builtin(program_name)) {
  1125. // Complete builtins.
  1126. if (program_name == "setopt") {
  1127. bool negate = false;
  1128. if (option_pattern.starts_with("no_")) {
  1129. negate = true;
  1130. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  1131. }
  1132. auto maybe_negate = [&](const StringView& view) {
  1133. static StringBuilder builder;
  1134. builder.clear();
  1135. builder.append("--");
  1136. if (negate)
  1137. builder.append("no_");
  1138. builder.append(view);
  1139. return builder.to_string();
  1140. };
  1141. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  1142. if (StringView { #name }.starts_with(option_pattern)) { \
  1143. suggestions.append(maybe_negate(#name)); \
  1144. suggestions.last().input_offset = offset; \
  1145. }
  1146. ENUMERATE_SHELL_OPTIONS();
  1147. #undef __ENUMERATE_SHELL_OPTION
  1148. return suggestions;
  1149. }
  1150. }
  1151. return suggestions;
  1152. }
  1153. void Shell::bring_cursor_to_beginning_of_a_line() const
  1154. {
  1155. struct winsize ws;
  1156. if (m_editor) {
  1157. ws = m_editor->terminal_size();
  1158. } else {
  1159. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1160. // Very annoying assumptions.
  1161. ws.ws_col = 80;
  1162. ws.ws_row = 25;
  1163. }
  1164. }
  1165. // Black with Cyan background.
  1166. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1167. String eol_mark = getenv("PROMPT_EOL_MARK");
  1168. if (eol_mark.is_null())
  1169. eol_mark = default_mark;
  1170. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_lengths.last();
  1171. if (eol_mark_length >= ws.ws_col) {
  1172. eol_mark = default_mark;
  1173. eol_mark_length = 1;
  1174. }
  1175. fputs(eol_mark.characters(), stderr);
  1176. for (auto i = eol_mark_length; i < ws.ws_col; ++i)
  1177. putc(' ', stderr);
  1178. putc('\r', stderr);
  1179. }
  1180. bool Shell::read_single_line()
  1181. {
  1182. restore_ios();
  1183. bring_cursor_to_beginning_of_a_line();
  1184. auto line_result = m_editor->get_line(prompt());
  1185. if (line_result.is_error()) {
  1186. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1187. // Pretend the user tried to execute builtin_exit()
  1188. run_command("exit");
  1189. return read_single_line();
  1190. } else {
  1191. Core::EventLoop::current().quit(1);
  1192. return false;
  1193. }
  1194. }
  1195. auto& line = line_result.value();
  1196. if (line.is_empty())
  1197. return true;
  1198. run_command(line);
  1199. m_editor->add_to_history(line);
  1200. return true;
  1201. }
  1202. void Shell::custom_event(Core::CustomEvent& event)
  1203. {
  1204. if (event.custom_type() == ReadLine) {
  1205. if (read_single_line())
  1206. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1207. return;
  1208. }
  1209. }
  1210. void Shell::notify_child_event()
  1211. {
  1212. #ifdef ENSURE_WAITID_ONCE
  1213. static HashTable<pid_t> s_waited_for_pids;
  1214. #endif
  1215. Vector<u64> disowned_jobs;
  1216. // Workaround the fact that we can't receive *who* exactly changed state.
  1217. // The child might still be alive (and even running) when this signal is dispatched to us
  1218. // so just...repeat until we find a suitable child.
  1219. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1220. // until the next child event we can actually handle.
  1221. bool found_child = false;
  1222. do {
  1223. // Ignore stray SIGCHLD when there are no jobs.
  1224. if (jobs.is_empty())
  1225. return;
  1226. for (auto& it : jobs) {
  1227. auto job_id = it.key;
  1228. auto& job = *it.value;
  1229. #ifdef ENSURE_WAITID_ONCE
  1230. // Theoretically, this should never trip, as jobs are removed from
  1231. // the job table when waitpid() succeeds *and* the child is dead.
  1232. ASSERT(!s_waited_for_pids.contains(job.pid()));
  1233. #endif
  1234. int wstatus = 0;
  1235. #ifdef SH_DEBUG
  1236. dbgln("waitpid({}) = ...", job.pid());
  1237. #endif
  1238. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1239. #ifdef SH_DEBUG
  1240. dbgln("... = {} - {}", child_pid, wstatus);
  1241. #endif
  1242. if (child_pid < 0) {
  1243. if (errno == ECHILD) {
  1244. // The child process went away before we could process its death, just assume it exited all ok.
  1245. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1246. dbgln("Child process gone, cannot get exit code for {}", job_id);
  1247. child_pid = job.pid();
  1248. } else {
  1249. ASSERT_NOT_REACHED();
  1250. }
  1251. }
  1252. if (child_pid == 0) {
  1253. // If the child existed, but wasn't dead.
  1254. continue;
  1255. }
  1256. if (child_pid == job.pid()) {
  1257. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1258. job.set_signalled(WTERMSIG(wstatus));
  1259. } else if (WIFEXITED(wstatus)) {
  1260. job.set_has_exit(WEXITSTATUS(wstatus));
  1261. } else if (WIFSTOPPED(wstatus)) {
  1262. job.unblock();
  1263. job.set_is_suspended(true);
  1264. }
  1265. found_child = true;
  1266. #ifdef ENSURE_WAITID_ONCE
  1267. // NOTE: This check is here to find bugs about our assumptions about waitpid(),
  1268. // it does not hold in general, and it definitely does not hold in the long run.
  1269. // Reasons that we would call waitpid() more than once:
  1270. // - PID reuse/wraparound: This will simply fail the assertion, ignored here.
  1271. // - Non-terminating unblocks:
  1272. // - Suspension: (e.g. via ^Z)
  1273. // - ?
  1274. // - ?
  1275. if (job.exited())
  1276. s_waited_for_pids.set(child_pid);
  1277. #endif
  1278. }
  1279. if (job.should_be_disowned())
  1280. disowned_jobs.append(job_id);
  1281. }
  1282. for (auto job_id : disowned_jobs) {
  1283. jobs.remove(job_id);
  1284. }
  1285. } while (!found_child);
  1286. }
  1287. Shell::Shell()
  1288. : m_default_constructed(true)
  1289. {
  1290. push_frame("main").leak_frame();
  1291. int rc = gethostname(hostname, Shell::HostNameSize);
  1292. if (rc < 0)
  1293. perror("gethostname");
  1294. {
  1295. auto* pw = getpwuid(getuid());
  1296. if (pw) {
  1297. username = pw->pw_name;
  1298. home = pw->pw_dir;
  1299. setenv("HOME", pw->pw_dir, 1);
  1300. }
  1301. endpwent();
  1302. }
  1303. // For simplicity, start at the user's home directory.
  1304. this->cwd = home;
  1305. setenv("PWD", home.characters(), 1);
  1306. // Add the default PATH vars.
  1307. {
  1308. StringBuilder path;
  1309. path.append(getenv("PATH"));
  1310. if (path.length())
  1311. path.append(":");
  1312. path.append("/bin:/usr/bin:/usr/local/bin");
  1313. setenv("PATH", path.to_string().characters(), true);
  1314. }
  1315. cache_path();
  1316. }
  1317. Shell::Shell(Line::Editor& editor)
  1318. : m_editor(editor)
  1319. {
  1320. uid = getuid();
  1321. tcsetpgrp(0, getpgrp());
  1322. m_pid = getpid();
  1323. push_frame("main").leak_frame();
  1324. int rc = gethostname(hostname, Shell::HostNameSize);
  1325. if (rc < 0)
  1326. perror("gethostname");
  1327. auto istty = isatty(STDIN_FILENO);
  1328. m_is_interactive = istty;
  1329. if (istty) {
  1330. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1331. if (rc < 0)
  1332. perror("ttyname_r");
  1333. } else {
  1334. ttyname[0] = 0;
  1335. }
  1336. {
  1337. auto* cwd = getcwd(nullptr, 0);
  1338. this->cwd = cwd;
  1339. setenv("PWD", cwd, 1);
  1340. free(cwd);
  1341. }
  1342. {
  1343. auto* pw = getpwuid(getuid());
  1344. if (pw) {
  1345. username = pw->pw_name;
  1346. home = pw->pw_dir;
  1347. setenv("HOME", pw->pw_dir, 1);
  1348. }
  1349. endpwent();
  1350. }
  1351. directory_stack.append(cwd);
  1352. m_editor->load_history(get_history_path());
  1353. cache_path();
  1354. m_editor->register_key_input_callback('\n', [](Line::Editor& editor) {
  1355. auto ast = Parser(editor.line()).parse();
  1356. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1357. return true;
  1358. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1359. });
  1360. }
  1361. Shell::~Shell()
  1362. {
  1363. if (m_default_constructed)
  1364. return;
  1365. stop_all_jobs();
  1366. m_editor->save_history(get_history_path());
  1367. }
  1368. void Shell::stop_all_jobs()
  1369. {
  1370. if (!jobs.is_empty()) {
  1371. if (m_is_interactive && !m_is_subshell)
  1372. printf("Killing active jobs\n");
  1373. for (auto& entry : jobs) {
  1374. if (entry.value->is_suspended()) {
  1375. #ifdef SH_DEBUG
  1376. dbgln("Job {} is suspended", entry.value->pid());
  1377. #endif
  1378. kill_job(entry.value, SIGCONT);
  1379. }
  1380. kill_job(entry.value, SIGHUP);
  1381. }
  1382. usleep(10000); // Wait for a bit before killing the job
  1383. for (auto& entry : jobs) {
  1384. #ifdef SH_DEBUG
  1385. dbgln("Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1386. #endif
  1387. kill_job(entry.value, SIGKILL);
  1388. }
  1389. jobs.clear();
  1390. }
  1391. }
  1392. u64 Shell::find_last_job_id() const
  1393. {
  1394. u64 job_id = 0;
  1395. for (auto& entry : jobs) {
  1396. if (entry.value->job_id() > job_id)
  1397. job_id = entry.value->job_id();
  1398. }
  1399. return job_id;
  1400. }
  1401. const Job* Shell::find_job(u64 id)
  1402. {
  1403. for (auto& entry : jobs) {
  1404. if (entry.value->job_id() == id)
  1405. return entry.value;
  1406. }
  1407. return nullptr;
  1408. }
  1409. void Shell::kill_job(const Job* job, int sig)
  1410. {
  1411. if (!job)
  1412. return;
  1413. if (killpg(job->pgid(), sig) < 0) {
  1414. if (kill(job->pid(), sig) < 0) {
  1415. perror("kill");
  1416. }
  1417. }
  1418. }
  1419. void Shell::save_to(JsonObject& object)
  1420. {
  1421. Core::Object::save_to(object);
  1422. object.set("working_directory", cwd);
  1423. object.set("username", username);
  1424. object.set("user_home_path", home);
  1425. object.set("user_id", uid);
  1426. object.set("directory_stack_size", directory_stack.size());
  1427. object.set("cd_history_size", cd_history.size());
  1428. // Jobs.
  1429. JsonArray job_objects;
  1430. for (auto& job_entry : jobs) {
  1431. JsonObject job_object;
  1432. job_object.set("pid", job_entry.value->pid());
  1433. job_object.set("pgid", job_entry.value->pgid());
  1434. job_object.set("running_time", job_entry.value->timer().elapsed());
  1435. job_object.set("command", job_entry.value->cmd());
  1436. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1437. job_objects.append(move(job_object));
  1438. }
  1439. object.set("jobs", move(job_objects));
  1440. }
  1441. void FileDescriptionCollector::collect()
  1442. {
  1443. for (auto fd : m_fds)
  1444. close(fd);
  1445. m_fds.clear();
  1446. }
  1447. FileDescriptionCollector::~FileDescriptionCollector()
  1448. {
  1449. collect();
  1450. }
  1451. void FileDescriptionCollector::add(int fd)
  1452. {
  1453. m_fds.append(fd);
  1454. }
  1455. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  1456. {
  1457. for (auto& rewiring : intended_rewirings) {
  1458. int new_fd = dup(rewiring.new_fd);
  1459. if (new_fd < 0) {
  1460. if (errno != EBADF)
  1461. perror("dup");
  1462. // The fd that will be overwritten isn't open right now,
  1463. // it will be cleaned up by the exec()-side collector
  1464. // and we have nothing to do here, so just ignore this error.
  1465. continue;
  1466. }
  1467. auto flags = fcntl(new_fd, F_GETFL);
  1468. auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC);
  1469. ASSERT(rc == 0);
  1470. m_saves.append({ rewiring.new_fd, new_fd });
  1471. m_collector.add(new_fd);
  1472. }
  1473. }
  1474. SavedFileDescriptors::~SavedFileDescriptors()
  1475. {
  1476. for (auto& save : m_saves) {
  1477. if (dup2(save.saved, save.original) < 0) {
  1478. perror("dup2(~SavedFileDescriptors)");
  1479. continue;
  1480. }
  1481. }
  1482. }
  1483. }