Shell.cpp 49 KB

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