Shell.cpp 51 KB

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