Shell.cpp 62 KB

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