Shell.cpp 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560
  1. /*
  2. * Copyright (c) 2020-2022, 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/CharacterTypes.h>
  10. #include <AK/Debug.h>
  11. #include <AK/Function.h>
  12. #include <AK/GenericLexer.h>
  13. #include <AK/JsonParser.h>
  14. #include <AK/LexicalPath.h>
  15. #include <AK/QuickSort.h>
  16. #include <AK/ScopeGuard.h>
  17. #include <AK/ScopedValueRollback.h>
  18. #include <AK/StringBuilder.h>
  19. #include <AK/TemporaryChange.h>
  20. #include <AK/URL.h>
  21. #include <LibCore/DeprecatedFile.h>
  22. #include <LibCore/DirIterator.h>
  23. #include <LibCore/Event.h>
  24. #include <LibCore/EventLoop.h>
  25. #include <LibCore/System.h>
  26. #include <LibCore/Timer.h>
  27. #include <LibLine/Editor.h>
  28. #include <Shell/PosixParser.h>
  29. #include <errno.h>
  30. #include <fcntl.h>
  31. #include <inttypes.h>
  32. #include <pwd.h>
  33. #include <signal.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <sys/mman.h>
  38. #include <sys/stat.h>
  39. #include <sys/utsname.h>
  40. #include <sys/wait.h>
  41. #include <termios.h>
  42. #include <unistd.h>
  43. static bool s_disable_hyperlinks = false;
  44. extern char** environ;
  45. namespace Shell {
  46. void Shell::setup_signals()
  47. {
  48. if (m_should_reinstall_signal_handlers) {
  49. Core::EventLoop::register_signal(SIGCHLD, [this](int) {
  50. dbgln_if(SH_DEBUG, "SIGCHLD!");
  51. notify_child_event();
  52. });
  53. Core::EventLoop::register_signal(SIGTSTP, [this](auto) {
  54. auto job = current_job();
  55. kill_job(job, SIGTSTP);
  56. if (job) {
  57. job->set_is_suspended(true);
  58. job->unblock();
  59. }
  60. });
  61. }
  62. }
  63. void Shell::print_path(StringView path)
  64. {
  65. if (s_disable_hyperlinks || !m_is_interactive) {
  66. out("{}", path);
  67. return;
  68. }
  69. auto url = URL::create_with_file_scheme(path, {}, hostname);
  70. out("\033]8;;{}\033\\{}\033]8;;\033\\", url.serialize(), path);
  71. }
  72. DeprecatedString Shell::prompt() const
  73. {
  74. auto build_prompt = [&]() -> DeprecatedString {
  75. auto* ps1 = getenv("PROMPT");
  76. if (!ps1) {
  77. if (uid == 0)
  78. return "# ";
  79. StringBuilder builder;
  80. builder.appendff("\033]0;{}@{}:{}\007", username, hostname, cwd);
  81. builder.appendff("\033[31;1m{}\033[0m@\033[37;1m{}\033[0m:\033[32;1m{}\033[0m$> ", username, hostname, cwd);
  82. return builder.to_deprecated_string();
  83. }
  84. StringBuilder builder;
  85. for (char* ptr = ps1; *ptr; ++ptr) {
  86. if (*ptr == '\\') {
  87. ++ptr;
  88. if (!*ptr)
  89. break;
  90. switch (*ptr) {
  91. case 'X':
  92. builder.append("\033]0;"sv);
  93. break;
  94. case 'a':
  95. builder.append(0x07);
  96. break;
  97. case 'e':
  98. builder.append(0x1b);
  99. break;
  100. case 'u':
  101. builder.append(username);
  102. break;
  103. case 'h':
  104. builder.append({ hostname, strlen(hostname) });
  105. break;
  106. case 'w': {
  107. DeprecatedString home_path = getenv("HOME");
  108. if (cwd.starts_with(home_path)) {
  109. builder.append('~');
  110. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  111. } else {
  112. builder.append(cwd);
  113. }
  114. break;
  115. }
  116. case 'p':
  117. builder.append(uid == 0 ? '#' : '$');
  118. break;
  119. }
  120. continue;
  121. }
  122. builder.append(*ptr);
  123. }
  124. return builder.to_deprecated_string();
  125. };
  126. return build_prompt();
  127. }
  128. DeprecatedString Shell::expand_tilde(StringView expression)
  129. {
  130. VERIFY(expression.starts_with('~'));
  131. StringBuilder login_name;
  132. size_t first_slash_index = expression.length();
  133. for (size_t i = 1; i < expression.length(); ++i) {
  134. if (expression[i] == '/') {
  135. first_slash_index = i;
  136. break;
  137. }
  138. login_name.append(expression[i]);
  139. }
  140. StringBuilder path;
  141. for (size_t i = first_slash_index; i < expression.length(); ++i)
  142. path.append(expression[i]);
  143. if (login_name.is_empty()) {
  144. char const* home = getenv("HOME");
  145. if (!home) {
  146. auto passwd = getpwuid(getuid());
  147. VERIFY(passwd && passwd->pw_dir);
  148. return DeprecatedString::formatted("{}/{}", passwd->pw_dir, path.to_deprecated_string());
  149. }
  150. return DeprecatedString::formatted("{}/{}", home, path.to_deprecated_string());
  151. }
  152. auto passwd = getpwnam(login_name.to_deprecated_string().characters());
  153. if (!passwd)
  154. return expression;
  155. VERIFY(passwd->pw_dir);
  156. return DeprecatedString::formatted("{}/{}", passwd->pw_dir, path.to_deprecated_string());
  157. }
  158. bool Shell::is_glob(StringView s)
  159. {
  160. for (size_t i = 0; i < s.length(); i++) {
  161. char c = s.characters_without_null_termination()[i];
  162. if (c == '*' || c == '?')
  163. return true;
  164. }
  165. return false;
  166. }
  167. Vector<StringView> Shell::split_path(StringView path)
  168. {
  169. Vector<StringView> parts;
  170. size_t substart = 0;
  171. for (size_t i = 0; i < path.length(); i++) {
  172. char ch = path[i];
  173. if (ch != '/')
  174. continue;
  175. size_t sublen = i - substart;
  176. if (sublen != 0)
  177. parts.append(path.substring_view(substart, sublen));
  178. substart = i + 1;
  179. }
  180. size_t taillen = path.length() - substart;
  181. if (taillen != 0)
  182. parts.append(path.substring_view(substart, taillen));
  183. return parts;
  184. }
  185. Vector<DeprecatedString> Shell::expand_globs(StringView path, StringView base)
  186. {
  187. auto explicitly_set_base = false;
  188. if (path.starts_with('/')) {
  189. base = "/"sv;
  190. explicitly_set_base = true;
  191. }
  192. auto parts = split_path(path);
  193. DeprecatedString base_string = base;
  194. struct stat statbuf;
  195. if (lstat(base_string.characters(), &statbuf) < 0) {
  196. perror("lstat");
  197. return {};
  198. }
  199. StringBuilder resolved_base_path_builder;
  200. resolved_base_path_builder.append(Core::DeprecatedFile::real_path_for(base));
  201. if (S_ISDIR(statbuf.st_mode))
  202. resolved_base_path_builder.append('/');
  203. auto resolved_base = resolved_base_path_builder.string_view();
  204. auto results = expand_globs(move(parts), resolved_base);
  205. if (explicitly_set_base && base == "/")
  206. resolved_base = resolved_base.substring_view(1, resolved_base.length() - 1);
  207. for (auto& entry : results) {
  208. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  209. if (entry.is_empty())
  210. entry = ".";
  211. }
  212. // Make the output predictable and nice.
  213. quick_sort(results);
  214. return results;
  215. }
  216. Vector<DeprecatedString> Shell::expand_globs(Vector<StringView> path_segments, StringView base)
  217. {
  218. if (path_segments.is_empty()) {
  219. DeprecatedString base_str = base;
  220. struct stat statbuf;
  221. if (lstat(base_str.characters(), &statbuf) < 0)
  222. return {};
  223. return { move(base_str) };
  224. }
  225. auto first_segment = path_segments.take_first();
  226. if (is_glob(first_segment)) {
  227. Vector<DeprecatedString> result;
  228. Core::DirIterator di(base, Core::DirIterator::SkipParentAndBaseDir);
  229. if (di.has_error())
  230. return {};
  231. while (di.has_next()) {
  232. DeprecatedString path = di.next_path();
  233. // Dotfiles have to be explicitly requested
  234. if (path[0] == '.' && first_segment[0] != '.')
  235. continue;
  236. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  237. StringBuilder builder;
  238. builder.append(base);
  239. if (!base.ends_with('/'))
  240. builder.append('/');
  241. builder.append(path);
  242. result.extend(expand_globs(path_segments, builder.string_view()));
  243. }
  244. }
  245. return result;
  246. } else {
  247. StringBuilder builder;
  248. builder.append(base);
  249. if (!base.ends_with('/'))
  250. builder.append('/');
  251. builder.append(first_segment);
  252. return expand_globs(move(path_segments), builder.string_view());
  253. }
  254. }
  255. Vector<AST::Command> Shell::expand_aliases(Vector<AST::Command> initial_commands)
  256. {
  257. Vector<AST::Command> commands;
  258. Function<void(AST::Command&)> resolve_aliases_and_append = [&](auto& command) {
  259. if (!command.argv.is_empty()) {
  260. auto alias = resolve_alias(command.argv[0]);
  261. if (!alias.is_null()) {
  262. auto argv0 = command.argv.take_first();
  263. auto subcommand_ast = parse(alias, false);
  264. if (subcommand_ast) {
  265. while (subcommand_ast->is_execute()) {
  266. auto* ast = static_cast<AST::Execute*>(subcommand_ast.ptr());
  267. subcommand_ast = ast->command();
  268. }
  269. auto subcommand_nonnull = subcommand_ast.release_nonnull();
  270. NonnullRefPtr<AST::Node> substitute = adopt_ref(*new AST::Join(subcommand_nonnull->position(),
  271. subcommand_nonnull,
  272. adopt_ref(*new AST::CommandLiteral(subcommand_nonnull->position(), command))));
  273. auto res = substitute->run(*this);
  274. for (auto& subst_command : res->resolve_as_commands(*this)) {
  275. if (!subst_command.argv.is_empty() && subst_command.argv.first() == argv0) // Disallow an alias resolving to itself.
  276. commands.append(subst_command);
  277. else
  278. resolve_aliases_and_append(subst_command);
  279. }
  280. } else {
  281. commands.append(command);
  282. }
  283. } else {
  284. commands.append(command);
  285. }
  286. } else {
  287. commands.append(command);
  288. }
  289. };
  290. for (auto& command : initial_commands)
  291. resolve_aliases_and_append(command);
  292. return commands;
  293. }
  294. DeprecatedString Shell::resolve_path(DeprecatedString path) const
  295. {
  296. if (!path.starts_with('/'))
  297. path = DeprecatedString::formatted("{}/{}", cwd, path);
  298. return Core::DeprecatedFile::real_path_for(path);
  299. }
  300. Shell::LocalFrame* Shell::find_frame_containing_local_variable(StringView name)
  301. {
  302. for (size_t i = m_local_frames.size(); i > 0; --i) {
  303. auto& frame = m_local_frames[i - 1];
  304. if (frame.local_variables.contains(name))
  305. return &frame;
  306. }
  307. return nullptr;
  308. }
  309. RefPtr<AST::Value> Shell::lookup_local_variable(StringView name) const
  310. {
  311. if (auto* frame = find_frame_containing_local_variable(name))
  312. return frame->local_variables.get(name).value();
  313. if (auto index = name.to_uint(); index.has_value())
  314. return get_argument(index.value());
  315. return nullptr;
  316. }
  317. RefPtr<AST::Value> Shell::get_argument(size_t index) const
  318. {
  319. if (index == 0)
  320. return adopt_ref(*new AST::StringValue(current_script));
  321. --index;
  322. if (auto argv = lookup_local_variable("ARGV"sv)) {
  323. if (argv->is_list_without_resolution()) {
  324. AST::ListValue* list = static_cast<AST::ListValue*>(argv.ptr());
  325. if (list->values().size() <= index)
  326. return nullptr;
  327. return list->values().at(index);
  328. }
  329. if (index != 0)
  330. return nullptr;
  331. return argv;
  332. }
  333. return nullptr;
  334. }
  335. DeprecatedString Shell::local_variable_or(StringView name, DeprecatedString const& replacement) const
  336. {
  337. auto value = lookup_local_variable(name);
  338. if (value) {
  339. StringBuilder builder;
  340. builder.join(' ', value->resolve_as_list(*this));
  341. return builder.to_deprecated_string();
  342. }
  343. return replacement;
  344. }
  345. void Shell::set_local_variable(DeprecatedString const& name, RefPtr<AST::Value> value, bool only_in_current_frame)
  346. {
  347. if (!only_in_current_frame) {
  348. if (auto* frame = find_frame_containing_local_variable(name)) {
  349. frame->local_variables.set(name, move(value));
  350. return;
  351. }
  352. }
  353. m_local_frames.last().local_variables.set(name, move(value));
  354. }
  355. void Shell::unset_local_variable(StringView name, bool only_in_current_frame)
  356. {
  357. if (!only_in_current_frame) {
  358. if (auto* frame = find_frame_containing_local_variable(name))
  359. frame->local_variables.remove(name);
  360. return;
  361. }
  362. m_local_frames.last().local_variables.remove(name);
  363. }
  364. void Shell::define_function(DeprecatedString name, Vector<DeprecatedString> argnames, RefPtr<AST::Node> body)
  365. {
  366. add_entry_to_cache({ RunnablePath::Kind::Function, name });
  367. m_functions.set(name, { name, move(argnames), move(body) });
  368. }
  369. bool Shell::has_function(StringView name)
  370. {
  371. return m_functions.contains(name);
  372. }
  373. bool Shell::invoke_function(const AST::Command& command, int& retval)
  374. {
  375. if (command.argv.is_empty())
  376. return false;
  377. StringView name = command.argv.first();
  378. TemporaryChange<DeprecatedString> script_change { current_script, name };
  379. auto function_option = m_functions.get(name);
  380. if (!function_option.has_value())
  381. return false;
  382. auto& function = function_option.value();
  383. if (!function.body) {
  384. retval = 0;
  385. return true;
  386. }
  387. if (command.argv.size() - 1 < function.arguments.size()) {
  388. raise_error(ShellError::EvaluatedSyntaxError, DeprecatedString::formatted("Expected at least {} arguments to {}, but got {}", function.arguments.size(), function.name, command.argv.size() - 1), command.position);
  389. retval = 1;
  390. return true;
  391. }
  392. auto frame = push_frame(DeprecatedString::formatted("function {}", function.name));
  393. size_t index = 0;
  394. for (auto& arg : function.arguments) {
  395. ++index;
  396. set_local_variable(arg, adopt_ref(*new AST::StringValue(command.argv[index])), true);
  397. }
  398. auto argv = command.argv;
  399. argv.take_first();
  400. set_local_variable("ARGV", adopt_ref(*new AST::ListValue(move(argv))), true);
  401. Core::EventLoop loop;
  402. setup_signals();
  403. (void)function.body->run(*this);
  404. retval = last_return_code.value_or(0);
  405. return true;
  406. }
  407. DeprecatedString Shell::format(StringView source, ssize_t& cursor) const
  408. {
  409. Formatter formatter(source, cursor, m_in_posix_mode);
  410. auto result = formatter.format();
  411. cursor = formatter.cursor();
  412. return result;
  413. }
  414. Shell::Frame Shell::push_frame(DeprecatedString name)
  415. {
  416. m_local_frames.append(make<LocalFrame>(name, decltype(LocalFrame::local_variables) {}));
  417. dbgln_if(SH_DEBUG, "New frame '{}' at {:p}", name, &m_local_frames.last());
  418. return { m_local_frames, m_local_frames.last() };
  419. }
  420. void Shell::pop_frame()
  421. {
  422. VERIFY(m_local_frames.size() > 1);
  423. (void)m_local_frames.take_last();
  424. }
  425. Shell::Frame::~Frame()
  426. {
  427. if (!should_destroy_frame)
  428. return;
  429. if (&frames.last() != &frame) {
  430. dbgln("Frame destruction order violation near {:p} (container = {:p}) in '{}'", &frame, this, frame.name);
  431. dbgln("Current frames:");
  432. for (auto& frame : frames)
  433. dbgln("- {:p}: {}", &frame, frame.name);
  434. VERIFY_NOT_REACHED();
  435. }
  436. (void)frames.take_last();
  437. }
  438. DeprecatedString Shell::resolve_alias(StringView name) const
  439. {
  440. return m_aliases.get(name).value_or({});
  441. }
  442. Optional<Shell::RunnablePath> Shell::runnable_path_for(StringView name)
  443. {
  444. auto parts = name.split_view('/');
  445. auto path = name.to_deprecated_string();
  446. if (parts.size() > 1) {
  447. auto file = Core::DeprecatedFile::open(path.characters(), Core::OpenMode::ReadOnly);
  448. if (!file.is_error() && !file.value()->is_directory() && access(path.characters(), X_OK) == 0)
  449. return RunnablePath { RunnablePath::Kind::Executable, name };
  450. }
  451. auto* found = binary_search(cached_path.span(), path, nullptr, RunnablePathComparator {});
  452. if (!found)
  453. return {};
  454. return *found;
  455. }
  456. Optional<DeprecatedString> Shell::help_path_for(Vector<RunnablePath> visited, Shell::RunnablePath const& runnable_path)
  457. {
  458. switch (runnable_path.kind) {
  459. case RunnablePath::Kind::Executable: {
  460. LexicalPath lexical_path(runnable_path.path);
  461. return lexical_path.basename();
  462. }
  463. case RunnablePath::Kind::Alias: {
  464. if (visited.contains_slow(runnable_path))
  465. return {}; // Break out of an alias loop
  466. auto resolved = resolve_alias(runnable_path.path);
  467. auto* runnable = binary_search(cached_path.span(), resolved, nullptr, RunnablePathComparator {});
  468. if (!runnable)
  469. return {};
  470. visited.append(runnable_path);
  471. return help_path_for(visited, *runnable);
  472. }
  473. default:
  474. return {};
  475. }
  476. }
  477. int Shell::run_command(StringView cmd, Optional<SourcePosition> source_position_override)
  478. {
  479. // The default-constructed mode of the shell
  480. // should not be used for execution!
  481. VERIFY(!m_default_constructed);
  482. take_error();
  483. if (!last_return_code.has_value())
  484. last_return_code = 0;
  485. ScopedValueRollback source_position_rollback { m_source_position };
  486. if (source_position_override.has_value())
  487. m_source_position = move(source_position_override);
  488. if (!m_source_position.has_value())
  489. m_source_position = SourcePosition { .source_file = {}, .literal_source_text = cmd, .position = {} };
  490. if (cmd.is_empty())
  491. return 0;
  492. auto command = parse(cmd, m_is_interactive);
  493. if (!command)
  494. return 0;
  495. if constexpr (SH_DEBUG) {
  496. dbgln("Command follows");
  497. command->dump(0);
  498. }
  499. if (command->is_syntax_error()) {
  500. auto& error_node = command->syntax_error_node();
  501. auto& position = error_node.position();
  502. raise_error(ShellError::EvaluatedSyntaxError, error_node.error_text(), position);
  503. }
  504. if (!has_error(ShellError::None)) {
  505. possibly_print_error();
  506. take_error();
  507. return 1;
  508. }
  509. tcgetattr(0, &termios);
  510. (void)command->run(*this);
  511. if (!has_error(ShellError::None)) {
  512. possibly_print_error();
  513. take_error();
  514. return 1;
  515. }
  516. return last_return_code.value_or(0);
  517. }
  518. ErrorOr<RefPtr<Job>> Shell::run_command(const AST::Command& command)
  519. {
  520. FileDescriptionCollector fds;
  521. if (options.verbose)
  522. warnln("+ {}", command);
  523. // If the command is empty, store the redirections and apply them to all later commands.
  524. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  525. m_global_redirections.extend(command.redirections);
  526. for (auto& next_in_chain : command.next_chain)
  527. run_tail(command, next_in_chain, last_return_code.value_or(0));
  528. return nullptr;
  529. }
  530. // Resolve redirections.
  531. NonnullRefPtrVector<AST::Rewiring> rewirings;
  532. auto resolve_redirection = [&](auto& redirection) -> ErrorOr<void> {
  533. auto rewiring = TRY(redirection.apply());
  534. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseNew)
  535. rewirings.append(*rewiring);
  536. if (rewiring->fd_action == AST::Rewiring::Close::Old) {
  537. fds.add(rewiring->old_fd);
  538. } else if (rewiring->fd_action == AST::Rewiring::Close::New) {
  539. if (rewiring->new_fd != -1)
  540. fds.add(rewiring->new_fd);
  541. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseNew) {
  542. fds.add(rewiring->new_fd);
  543. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshNew) {
  544. VERIFY(rewiring->other_pipe_end);
  545. int pipe_fd[2];
  546. int rc = pipe(pipe_fd);
  547. if (rc < 0)
  548. return Error::from_syscall("pipe"sv, rc);
  549. rewiring->new_fd = pipe_fd[1];
  550. rewiring->other_pipe_end->new_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  551. fds.add(pipe_fd[1]);
  552. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshOld) {
  553. VERIFY(rewiring->other_pipe_end);
  554. int pipe_fd[2];
  555. int rc = pipe(pipe_fd);
  556. if (rc < 0)
  557. return Error::from_syscall("pipe"sv, rc);
  558. rewiring->old_fd = pipe_fd[1];
  559. rewiring->other_pipe_end->old_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  560. fds.add(pipe_fd[1]);
  561. }
  562. return {};
  563. };
  564. auto apply_rewirings = [&]() -> ErrorOr<void> {
  565. for (auto& rewiring : rewirings) {
  566. dbgln_if(SH_DEBUG, "in {}<{}>, dup2({}, {})", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.old_fd, rewiring.new_fd);
  567. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  568. if (rc < 0)
  569. return Error::from_syscall("dup2"sv, rc);
  570. // {new,old}_fd is closed via the `fds` collector, but rewiring.other_pipe_end->{new,old}_fd
  571. // isn't yet in that collector when the first child spawns.
  572. if (rewiring.other_pipe_end) {
  573. if (rewiring.fd_action == AST::Rewiring::Close::RefreshNew) {
  574. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->new_fd) < 0)
  575. perror("close other pipe end");
  576. } else if (rewiring.fd_action == AST::Rewiring::Close::RefreshOld) {
  577. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->old_fd) < 0)
  578. perror("close other pipe end");
  579. }
  580. }
  581. }
  582. return {};
  583. };
  584. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, false };
  585. for (auto& redirection : m_global_redirections)
  586. TRY(resolve_redirection(redirection));
  587. for (auto& redirection : command.redirections)
  588. TRY(resolve_redirection(redirection));
  589. if (int local_return_code = 0; command.should_wait && run_builtin(command, rewirings, local_return_code)) {
  590. last_return_code = local_return_code;
  591. for (auto& next_in_chain : command.next_chain)
  592. run_tail(command, next_in_chain, *last_return_code);
  593. return nullptr;
  594. }
  595. auto can_be_run_in_current_process = command.should_wait && !command.pipeline && !command.argv.is_empty();
  596. if (can_be_run_in_current_process && has_function(command.argv.first())) {
  597. SavedFileDescriptors fds { rewirings };
  598. for (auto& rewiring : rewirings)
  599. TRY(Core::System::dup2(rewiring.old_fd, rewiring.new_fd));
  600. if (int local_return_code = 0; invoke_function(command, local_return_code)) {
  601. last_return_code = local_return_code;
  602. for (auto& next_in_chain : command.next_chain)
  603. run_tail(command, next_in_chain, *last_return_code);
  604. return nullptr;
  605. }
  606. }
  607. if (command.argv.is_empty()
  608. && !command.next_chain.is_empty()
  609. && command.should_immediately_execute_next
  610. && command.redirections.is_empty()
  611. && command.next_chain.first().node->should_override_execution_in_current_process()) {
  612. for (auto& next_in_chain : command.next_chain)
  613. run_tail(command, next_in_chain, last_return_code.value_or(0));
  614. return nullptr;
  615. }
  616. Vector<char const*> argv;
  617. Vector<DeprecatedString> copy_argv = command.argv;
  618. argv.ensure_capacity(command.argv.size() + 1);
  619. for (auto& arg : copy_argv)
  620. argv.append(arg.characters());
  621. argv.append(nullptr);
  622. auto sync_pipe = TRY(Core::System::pipe2(0));
  623. auto child = TRY(Core::System::fork());
  624. if (child == 0) {
  625. close(sync_pipe[1]);
  626. m_pid = getpid();
  627. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  628. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, true };
  629. if (auto result = apply_rewirings(); result.is_error()) {
  630. warnln("Shell: Failed to apply rewirings in {}: {}", copy_argv[0], result.error());
  631. _exit(126);
  632. }
  633. fds.collect();
  634. u8 c;
  635. while (read(sync_pipe[0], &c, 1) < 0) {
  636. if (errno != EINTR) {
  637. warnln("Shell: Failed to sync in {}: {}", copy_argv[0], Error::from_syscall("read"sv, -errno));
  638. // There's nothing interesting we can do here.
  639. break;
  640. }
  641. }
  642. dbgln_if(SH_DEBUG, "Synced up with parent, we're good to exec()");
  643. close(sync_pipe[0]);
  644. if (!m_is_subshell && command.should_wait)
  645. tcsetattr(0, TCSANOW, &default_termios);
  646. m_is_subshell = true;
  647. if (command.should_immediately_execute_next) {
  648. VERIFY(command.argv.is_empty());
  649. Core::EventLoop mainloop;
  650. setup_signals();
  651. for (auto& next_in_chain : command.next_chain)
  652. run_tail(command, next_in_chain, 0);
  653. _exit(last_return_code.value_or(0));
  654. }
  655. if (int local_return_code = 0; run_builtin(command, {}, local_return_code))
  656. _exit(local_return_code);
  657. if (int local_return_code = 0; invoke_function(command, local_return_code))
  658. _exit(local_return_code);
  659. // We no longer need the jobs here.
  660. jobs.clear();
  661. execute_process(move(argv));
  662. VERIFY_NOT_REACHED();
  663. }
  664. close(sync_pipe[0]);
  665. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  666. if (command.pipeline) {
  667. if (is_first) {
  668. command.pipeline->pgid = child;
  669. }
  670. }
  671. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  672. if (!m_is_subshell || command.pipeline) {
  673. auto result = Core::System::setpgid(child, pgid);
  674. if (result.is_error() && m_is_interactive)
  675. warnln("Shell: {}", result.error());
  676. if (!m_is_subshell) {
  677. // There's no reason to care about the errors here
  678. // either we're in a tty, we're interactive, and this works
  679. // or we're not, and it fails - in which case, we don't need
  680. // stdin/stdout handoff to child processes anyway.
  681. tcsetpgrp(STDOUT_FILENO, pgid);
  682. tcsetpgrp(STDIN_FILENO, pgid);
  683. }
  684. }
  685. while (write(sync_pipe[1], "x", 1) < 0) {
  686. if (errno != EINTR) {
  687. warnln("Shell: Failed to sync with {}: {}", copy_argv[0], Error::from_syscall("write"sv, -errno));
  688. // There's nothing interesting we can do here.
  689. break;
  690. }
  691. }
  692. close(sync_pipe[1]);
  693. StringBuilder cmd;
  694. cmd.join(' ', command.argv);
  695. auto command_copy = AST::Command(command);
  696. // Clear the next chain if it's to be immediately executed
  697. // as the child will run this chain.
  698. if (command.should_immediately_execute_next)
  699. command_copy.next_chain.clear();
  700. auto job = Job::create(child, pgid, cmd.to_deprecated_string(), find_last_job_id() + 1, move(command_copy));
  701. jobs.set((u64)child, job);
  702. job->on_exit = [this](auto job) {
  703. if (!job->exited())
  704. return;
  705. if (job->is_running_in_background() && job->should_announce_exit())
  706. warnln("Shell: Job {} ({}) exited\n", job->job_id(), job->cmd());
  707. else if (job->signaled() && job->should_announce_signal())
  708. warnln("Shell: Job {} ({}) {}\n", job->job_id(), job->cmd(), strsignal(job->termination_signal()));
  709. last_return_code = job->exit_code();
  710. job->disown();
  711. if (m_editor && job->exit_code() == 0 && is_allowed_to_modify_termios(job->command())) {
  712. m_editor->refetch_default_termios();
  713. default_termios = m_editor->default_termios();
  714. termios = m_editor->termios();
  715. }
  716. run_tail(job);
  717. };
  718. fds.collect();
  719. return *job;
  720. }
  721. void Shell::execute_process(Vector<char const*>&& argv)
  722. {
  723. for (auto& promise : m_active_promises) {
  724. MUST(Core::System::pledge("stdio rpath exec"sv, promise.data.exec_promises));
  725. for (auto& item : promise.data.unveils)
  726. MUST(Core::System::unveil(item.path, item.access));
  727. }
  728. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  729. if (rc < 0) {
  730. auto parts = StringView { argv[0], strlen(argv[0]) }.split_view('/');
  731. if (parts.size() == 1) {
  732. // If this is a path in the current directory and it caused execvp() to fail,
  733. // simply don't attempt to execute it, see #6774.
  734. warnln("{}: Command not found.", argv[0]);
  735. _exit(127);
  736. }
  737. int saved_errno = errno;
  738. struct stat st;
  739. if (stat(argv[0], &st)) {
  740. warnln("stat({}): {}", argv[0], strerror(errno));
  741. // Return code 127 on command not found.
  742. _exit(127);
  743. }
  744. if (!(st.st_mode & S_IXUSR)) {
  745. warnln("{}: Not executable", argv[0]);
  746. // Return code 126 when file is not executable.
  747. _exit(126);
  748. }
  749. if (saved_errno == ENOENT) {
  750. do {
  751. auto file_result = Core::DeprecatedFile::open(argv[0], Core::OpenMode::ReadOnly);
  752. if (file_result.is_error())
  753. break;
  754. auto& file = file_result.value();
  755. auto line = file->read_line();
  756. if (!line.starts_with("#!"sv))
  757. break;
  758. GenericLexer shebang_lexer { line.substring_view(2) };
  759. auto shebang = shebang_lexer.consume_until(is_any_of("\n\r"sv)).to_deprecated_string();
  760. argv.prepend(shebang.characters());
  761. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  762. if (rc < 0) {
  763. warnln("{}: Invalid interpreter \"{}\": {}", argv[0], shebang.characters(), strerror(errno));
  764. _exit(126);
  765. }
  766. } while (false);
  767. warnln("{}: Command not found.", argv[0]);
  768. } else {
  769. if (S_ISDIR(st.st_mode)) {
  770. warnln("Shell: {}: Is a directory", argv[0]);
  771. _exit(126);
  772. }
  773. warnln("execvp({}): {}", argv[0], strerror(saved_errno));
  774. }
  775. _exit(126);
  776. }
  777. VERIFY_NOT_REACHED();
  778. }
  779. void Shell::run_tail(const AST::Command& invoking_command, const AST::NodeWithAction& next_in_chain, int head_exit_code)
  780. {
  781. if (m_error != ShellError::None) {
  782. possibly_print_error();
  783. if (!is_control_flow(m_error))
  784. take_error();
  785. return;
  786. }
  787. auto evaluate = [&] {
  788. if (next_in_chain.node->would_execute()) {
  789. (void)next_in_chain.node->run(*this);
  790. return;
  791. }
  792. auto node = next_in_chain.node;
  793. if (!invoking_command.should_wait)
  794. node = adopt_ref(static_cast<AST::Node&>(*new AST::Background(next_in_chain.node->position(), move(node))));
  795. (void)adopt_ref(static_cast<AST::Node&>(*new AST::Execute(next_in_chain.node->position(), move(node))))->run(*this);
  796. };
  797. switch (next_in_chain.action) {
  798. case AST::NodeWithAction::And:
  799. if (head_exit_code == 0)
  800. evaluate();
  801. break;
  802. case AST::NodeWithAction::Or:
  803. if (head_exit_code != 0)
  804. evaluate();
  805. break;
  806. case AST::NodeWithAction::Sequence:
  807. evaluate();
  808. break;
  809. }
  810. }
  811. void Shell::run_tail(RefPtr<Job> job)
  812. {
  813. if (auto cmd = job->command_ptr()) {
  814. deferred_invoke([=, this] {
  815. for (auto& next_in_chain : cmd->next_chain) {
  816. run_tail(*cmd, next_in_chain, job->exit_code());
  817. }
  818. });
  819. }
  820. }
  821. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  822. {
  823. if (m_error != ShellError::None) {
  824. possibly_print_error();
  825. if (!is_control_flow(m_error))
  826. take_error();
  827. return {};
  828. }
  829. NonnullRefPtrVector<Job> spawned_jobs;
  830. for (auto& command : commands) {
  831. if constexpr (SH_DEBUG) {
  832. dbgln("Command");
  833. for (auto& arg : command.argv)
  834. dbgln("argv: {}", arg);
  835. for (auto& redir : command.redirections) {
  836. if (redir.is_path_redirection()) {
  837. auto path_redir = (const AST::PathRedirection*)&redir;
  838. dbgln("redir path '{}' <-({})-> {}", path_redir->path, (int)path_redir->direction, path_redir->fd);
  839. } else if (redir.is_fd_redirection()) {
  840. auto* fdredir = (const AST::FdRedirection*)&redir;
  841. dbgln("redir fd {} -> {}", fdredir->old_fd, fdredir->new_fd);
  842. } else if (redir.is_close_redirection()) {
  843. auto close_redir = (const AST::CloseRedirection*)&redir;
  844. dbgln("close fd {}", close_redir->fd);
  845. } else {
  846. VERIFY_NOT_REACHED();
  847. }
  848. }
  849. }
  850. auto job_result = run_command(command);
  851. if (job_result.is_error()) {
  852. raise_error(ShellError::LaunchError, DeprecatedString::formatted("{} while running '{}'", job_result.error(), command.argv.first()), command.position);
  853. break;
  854. }
  855. auto job = job_result.release_value();
  856. if (!job)
  857. continue;
  858. spawned_jobs.append(*job);
  859. if (command.should_wait) {
  860. block_on_job(job);
  861. } else {
  862. job->set_running_in_background(true);
  863. if (!command.is_pipe_source && command.should_notify_if_in_background)
  864. job->set_should_announce_exit(true);
  865. }
  866. }
  867. if (m_error != ShellError::None) {
  868. possibly_print_error();
  869. if (!is_control_flow(m_error))
  870. take_error();
  871. }
  872. return spawned_jobs;
  873. }
  874. bool Shell::run_file(DeprecatedString const& filename, bool explicitly_invoked)
  875. {
  876. TemporaryChange script_change { current_script, filename };
  877. TemporaryChange interactive_change { m_is_interactive, false };
  878. TemporaryChange<Optional<SourcePosition>> source_change { m_source_position, SourcePosition { .source_file = filename, .literal_source_text = {}, .position = {} } };
  879. auto file_result = Core::DeprecatedFile::open(filename, Core::OpenMode::ReadOnly);
  880. if (file_result.is_error()) {
  881. auto error = DeprecatedString::formatted("'{}': {}", escape_token_for_single_quotes(filename), file_result.error());
  882. if (explicitly_invoked)
  883. raise_error(ShellError::OpenFailure, error);
  884. else
  885. dbgln("open() failed for {}", error);
  886. return false;
  887. }
  888. auto file = file_result.value();
  889. auto data = file->read_all();
  890. return run_command(data) == 0;
  891. }
  892. bool Shell::is_allowed_to_modify_termios(const AST::Command& command) const
  893. {
  894. if (command.argv.is_empty())
  895. return false;
  896. auto value = lookup_local_variable("PROGRAMS_ALLOWED_TO_MODIFY_DEFAULT_TERMIOS"sv);
  897. if (!value)
  898. return false;
  899. return value->resolve_as_list(*this).contains_slow(command.argv[0]);
  900. }
  901. void Shell::restore_ios()
  902. {
  903. if (m_is_subshell)
  904. return;
  905. tcsetattr(0, TCSANOW, &termios);
  906. tcsetpgrp(STDOUT_FILENO, m_pid);
  907. tcsetpgrp(STDIN_FILENO, m_pid);
  908. }
  909. void Shell::block_on_pipeline(RefPtr<AST::Pipeline> pipeline)
  910. {
  911. if (!pipeline)
  912. return;
  913. for (auto& it : jobs) {
  914. if (auto cmd = it.value->command_ptr(); cmd->pipeline == pipeline && cmd->is_pipe_source)
  915. block_on_job(it.value);
  916. }
  917. }
  918. void Shell::block_on_job(RefPtr<Job> job)
  919. {
  920. TemporaryChange<Job const*> current_job { m_current_job, job.ptr() };
  921. if (!job)
  922. return;
  923. if (job->is_suspended() && !job->shell_did_continue())
  924. return; // We cannot wait for a suspended job.
  925. ScopeGuard io_restorer { [&]() {
  926. if (job->exited() && !job->is_running_in_background()) {
  927. restore_ios();
  928. }
  929. } };
  930. bool job_exited { false };
  931. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  932. if (old_exit)
  933. old_exit(job);
  934. job_exited = true;
  935. };
  936. if (job->exited())
  937. return;
  938. while (!job_exited)
  939. Core::EventLoop::current().pump();
  940. // If the job is part of a pipeline, wait for the rest of the members too.
  941. if (auto command = job->command_ptr())
  942. block_on_pipeline(command->pipeline);
  943. }
  944. DeprecatedString Shell::get_history_path()
  945. {
  946. if (auto histfile = getenv("HISTFILE"))
  947. return { histfile };
  948. return DeprecatedString::formatted("{}/.history", home);
  949. }
  950. DeprecatedString Shell::escape_token_for_single_quotes(StringView token)
  951. {
  952. // `foo bar \n '` -> `'foo bar \n '"'"`
  953. StringBuilder builder;
  954. builder.append("'"sv);
  955. auto started_single_quote = true;
  956. for (auto c : token) {
  957. switch (c) {
  958. case '\'':
  959. builder.append("\"'\""sv);
  960. started_single_quote = false;
  961. continue;
  962. default:
  963. builder.append(c);
  964. if (!started_single_quote) {
  965. started_single_quote = true;
  966. builder.append("'"sv);
  967. }
  968. break;
  969. }
  970. }
  971. if (started_single_quote)
  972. builder.append("'"sv);
  973. return builder.to_deprecated_string();
  974. }
  975. DeprecatedString Shell::escape_token_for_double_quotes(StringView token)
  976. {
  977. // `foo bar \n $x 'blah "hello` -> `"foo bar \\n $x 'blah \"hello"`
  978. StringBuilder builder;
  979. builder.append('"');
  980. for (auto c : token) {
  981. switch (c) {
  982. case '\"':
  983. builder.append("\\\""sv);
  984. continue;
  985. case '\\':
  986. builder.append("\\\\"sv);
  987. continue;
  988. default:
  989. builder.append(c);
  990. break;
  991. }
  992. }
  993. builder.append('"');
  994. return builder.to_deprecated_string();
  995. }
  996. Shell::SpecialCharacterEscapeMode Shell::special_character_escape_mode(u32 code_point, EscapeMode mode)
  997. {
  998. switch (code_point) {
  999. case '\'':
  1000. if (mode == EscapeMode::DoubleQuotedString)
  1001. return SpecialCharacterEscapeMode::Untouched;
  1002. return SpecialCharacterEscapeMode::Escaped;
  1003. case '"':
  1004. case '$':
  1005. case '\\':
  1006. if (mode == EscapeMode::SingleQuotedString)
  1007. return SpecialCharacterEscapeMode::Untouched;
  1008. return SpecialCharacterEscapeMode::Escaped;
  1009. case '|':
  1010. case '>':
  1011. case '<':
  1012. case '(':
  1013. case ')':
  1014. case '{':
  1015. case '}':
  1016. case '&':
  1017. case ';':
  1018. case '?':
  1019. case '*':
  1020. case ' ':
  1021. if (mode == EscapeMode::SingleQuotedString || mode == EscapeMode::DoubleQuotedString)
  1022. return SpecialCharacterEscapeMode::Untouched;
  1023. return SpecialCharacterEscapeMode::Escaped;
  1024. case '\n':
  1025. case '\t':
  1026. case '\r':
  1027. return SpecialCharacterEscapeMode::QuotedAsEscape;
  1028. default:
  1029. // FIXME: Should instead use unicode's "graphic" property (categories L, M, N, P, S, Zs)
  1030. if (is_ascii(code_point))
  1031. return is_ascii_printable(code_point) ? SpecialCharacterEscapeMode::Untouched : SpecialCharacterEscapeMode::QuotedAsHex;
  1032. return SpecialCharacterEscapeMode::Untouched;
  1033. }
  1034. }
  1035. static DeprecatedString do_escape(Shell::EscapeMode escape_mode, auto& token)
  1036. {
  1037. StringBuilder builder;
  1038. for (auto c : token) {
  1039. static_assert(sizeof(c) == sizeof(u32) || sizeof(c) == sizeof(u8));
  1040. switch (Shell::special_character_escape_mode(c, escape_mode)) {
  1041. case Shell::SpecialCharacterEscapeMode::Untouched:
  1042. if constexpr (sizeof(c) == sizeof(u8))
  1043. builder.append(c);
  1044. else
  1045. builder.append(Utf32View { &c, 1 });
  1046. break;
  1047. case Shell::SpecialCharacterEscapeMode::Escaped:
  1048. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1049. builder.append("'"sv);
  1050. builder.append('\\');
  1051. builder.append(c);
  1052. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1053. builder.append("'"sv);
  1054. break;
  1055. case Shell::SpecialCharacterEscapeMode::QuotedAsEscape:
  1056. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1057. builder.append("'"sv);
  1058. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1059. builder.append("\""sv);
  1060. switch (c) {
  1061. case '\n':
  1062. builder.append(R"(\n)"sv);
  1063. break;
  1064. case '\t':
  1065. builder.append(R"(\t)"sv);
  1066. break;
  1067. case '\r':
  1068. builder.append(R"(\r)"sv);
  1069. break;
  1070. default:
  1071. VERIFY_NOT_REACHED();
  1072. }
  1073. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1074. builder.append("\""sv);
  1075. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1076. builder.append("'"sv);
  1077. break;
  1078. case Shell::SpecialCharacterEscapeMode::QuotedAsHex:
  1079. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1080. builder.append("'"sv);
  1081. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1082. builder.append("\""sv);
  1083. if (c <= NumericLimits<u8>::max())
  1084. builder.appendff(R"(\x{:0>2x})", static_cast<u8>(c));
  1085. else
  1086. builder.appendff(R"(\u{:0>8x})", static_cast<u32>(c));
  1087. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1088. builder.append("\""sv);
  1089. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1090. builder.append("'"sv);
  1091. break;
  1092. }
  1093. }
  1094. return builder.to_deprecated_string();
  1095. }
  1096. DeprecatedString Shell::escape_token(Utf32View token, EscapeMode escape_mode)
  1097. {
  1098. return do_escape(escape_mode, token);
  1099. }
  1100. DeprecatedString Shell::escape_token(StringView token, EscapeMode escape_mode)
  1101. {
  1102. Utf8View view { token };
  1103. if (view.validate())
  1104. return do_escape(escape_mode, view);
  1105. return do_escape(escape_mode, token);
  1106. }
  1107. DeprecatedString Shell::unescape_token(StringView token)
  1108. {
  1109. StringBuilder builder;
  1110. enum {
  1111. Free,
  1112. Escaped
  1113. } state { Free };
  1114. for (auto c : token) {
  1115. switch (state) {
  1116. case Escaped:
  1117. builder.append(c);
  1118. state = Free;
  1119. break;
  1120. case Free:
  1121. if (c == '\\')
  1122. state = Escaped;
  1123. else
  1124. builder.append(c);
  1125. break;
  1126. }
  1127. }
  1128. if (state == Escaped)
  1129. builder.append('\\');
  1130. return builder.to_deprecated_string();
  1131. }
  1132. void Shell::cache_path()
  1133. {
  1134. if (!m_is_interactive)
  1135. return;
  1136. if (!cached_path.is_empty())
  1137. cached_path.clear_with_capacity();
  1138. // Add shell builtins to the cache.
  1139. for (auto const& builtin_name : builtin_names)
  1140. cached_path.append({ RunnablePath::Kind::Builtin, escape_token(builtin_name) });
  1141. // Add functions to the cache.
  1142. for (auto& function : m_functions) {
  1143. auto name = escape_token(function.key);
  1144. if (cached_path.contains_slow(name))
  1145. continue;
  1146. cached_path.append({ RunnablePath::Kind::Function, name });
  1147. }
  1148. // Add aliases to the cache.
  1149. for (auto const& alias : m_aliases) {
  1150. auto name = escape_token(alias.key);
  1151. if (cached_path.contains_slow(name))
  1152. continue;
  1153. cached_path.append({ RunnablePath::Kind::Alias, name });
  1154. }
  1155. // TODO: Can we make this rely on Core::DeprecatedFile::resolve_executable_from_environment()?
  1156. DeprecatedString path = getenv("PATH");
  1157. if (!path.is_empty()) {
  1158. auto directories = path.split(':');
  1159. for (auto const& directory : directories) {
  1160. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1161. while (programs.has_next()) {
  1162. auto program = programs.next_path();
  1163. auto program_path = DeprecatedString::formatted("{}/{}", directory, program);
  1164. auto escaped_name = escape_token(program);
  1165. if (cached_path.contains_slow(escaped_name))
  1166. continue;
  1167. if (access(program_path.characters(), X_OK) == 0)
  1168. cached_path.append({ RunnablePath::Kind::Executable, escaped_name });
  1169. }
  1170. }
  1171. }
  1172. quick_sort(cached_path);
  1173. }
  1174. void Shell::add_entry_to_cache(RunnablePath const& entry)
  1175. {
  1176. size_t index = 0;
  1177. auto match = binary_search(cached_path.span(), entry, &index, RunnablePathComparator {});
  1178. if (match)
  1179. return;
  1180. while (index < cached_path.size() && strcmp(cached_path[index].path.characters(), entry.path.characters()) < 0) {
  1181. index++;
  1182. }
  1183. cached_path.insert(index, entry);
  1184. }
  1185. void Shell::remove_entry_from_cache(StringView entry)
  1186. {
  1187. size_t index { 0 };
  1188. auto match = binary_search(cached_path.span(), entry, &index, RunnablePathComparator {});
  1189. if (match)
  1190. cached_path.remove(index);
  1191. }
  1192. void Shell::highlight(Line::Editor& editor) const
  1193. {
  1194. auto line = editor.line();
  1195. auto ast = parse(line, m_is_interactive);
  1196. if (!ast)
  1197. return;
  1198. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  1199. }
  1200. Vector<Line::CompletionSuggestion> Shell::complete()
  1201. {
  1202. m_completion_stack_info = {};
  1203. return complete(m_editor->line(m_editor->cursor()));
  1204. }
  1205. Vector<Line::CompletionSuggestion> Shell::complete(StringView line)
  1206. {
  1207. auto ast = parse(line, m_is_interactive);
  1208. if (!ast)
  1209. return {};
  1210. return ast->complete_for_editor(*this, line.length());
  1211. }
  1212. Vector<Line::CompletionSuggestion> Shell::complete_path(StringView base, StringView part, size_t offset, ExecutableOnly executable_only, AST::Node const* command_node, AST::Node const* node, EscapeMode escape_mode)
  1213. {
  1214. auto token = offset ? part.substring_view(0, offset) : ""sv;
  1215. DeprecatedString path;
  1216. ssize_t last_slash = token.length() - 1;
  1217. while (last_slash >= 0 && token[last_slash] != '/')
  1218. --last_slash;
  1219. if (command_node) {
  1220. auto program_results = complete_via_program_itself(offset, command_node, node, escape_mode, {});
  1221. if (!program_results.is_error())
  1222. return program_results.release_value();
  1223. }
  1224. StringBuilder path_builder;
  1225. auto init_slash_part = token.substring_view(0, last_slash + 1);
  1226. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  1227. bool allow_direct_children = true;
  1228. // Depending on the base, we will have to prepend cwd.
  1229. if (base.is_empty()) {
  1230. // '' /foo -> absolute
  1231. // '' foo -> relative
  1232. if (!token.starts_with('/'))
  1233. path_builder.append(cwd);
  1234. path_builder.append('/');
  1235. path_builder.append(init_slash_part);
  1236. if (executable_only == ExecutableOnly::Yes && init_slash_part.is_empty())
  1237. allow_direct_children = false;
  1238. } else {
  1239. // /foo * -> absolute
  1240. // foo * -> relative
  1241. if (!base.starts_with('/'))
  1242. path_builder.append(cwd);
  1243. path_builder.append('/');
  1244. path_builder.append(base);
  1245. path_builder.append('/');
  1246. path_builder.append(init_slash_part);
  1247. }
  1248. path = path_builder.to_deprecated_string();
  1249. token = last_slash_part;
  1250. // the invariant part of the token is actually just the last segment
  1251. // e. in `cd /foo/bar', 'bar' is the invariant
  1252. // since we are not suggesting anything starting with
  1253. // `/foo/', but rather just `bar...'
  1254. auto token_length = escape_token(token, escape_mode).length();
  1255. size_t static_offset = 0;
  1256. auto invariant_offset = token_length;
  1257. if (m_editor)
  1258. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1259. // only suggest dot-files if path starts with a dot
  1260. Core::DirIterator files(path,
  1261. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1262. Vector<Line::CompletionSuggestion> suggestions;
  1263. while (files.has_next()) {
  1264. auto file = files.next_path();
  1265. if (file.starts_with(token)) {
  1266. struct stat program_status;
  1267. auto file_path = DeprecatedString::formatted("{}/{}", path, file);
  1268. int stat_error = stat(file_path.characters(), &program_status);
  1269. if (!stat_error && (executable_only == ExecutableOnly::No || access(file_path.characters(), X_OK) == 0)) {
  1270. if (S_ISDIR(program_status.st_mode)) {
  1271. suggestions.append({ escape_token(file, escape_mode), "/"sv });
  1272. } else {
  1273. if (!allow_direct_children && !file.contains('/'))
  1274. continue;
  1275. suggestions.append({ escape_token(file, escape_mode), " "sv });
  1276. }
  1277. suggestions.last().input_offset = token_length;
  1278. suggestions.last().invariant_offset = invariant_offset;
  1279. suggestions.last().static_offset = static_offset;
  1280. }
  1281. }
  1282. }
  1283. // The results of DirIterator are in the order they appear on-disk.
  1284. // Instead, return suggestions in lexicographical order.
  1285. quick_sort(suggestions, [](auto& a, auto& b) { return a.text_string < b.text_string; });
  1286. return suggestions;
  1287. }
  1288. Vector<Line::CompletionSuggestion> Shell::complete_program_name(StringView name, size_t offset, EscapeMode escape_mode)
  1289. {
  1290. auto match = binary_search(
  1291. cached_path.span(),
  1292. name,
  1293. nullptr,
  1294. [](auto& name, auto& program) {
  1295. return strncmp(
  1296. name.characters_without_null_termination(),
  1297. program.path.characters(),
  1298. name.length());
  1299. });
  1300. if (!match)
  1301. return complete_path(""sv, name, offset, ExecutableOnly::Yes, nullptr, nullptr, escape_mode);
  1302. DeprecatedString completion = match->path;
  1303. auto token_length = escape_token(name, escape_mode).length();
  1304. auto invariant_offset = token_length;
  1305. size_t static_offset = 0;
  1306. if (m_editor)
  1307. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1308. // Now that we have a program name starting with our token, we look at
  1309. // other program names starting with our token and cut off any mismatching
  1310. // characters.
  1311. Vector<Line::CompletionSuggestion> suggestions;
  1312. int index = match - cached_path.data();
  1313. for (int i = index - 1; i >= 0 && cached_path[i].path.starts_with(name); --i)
  1314. suggestions.append({ cached_path[i].path, " "sv });
  1315. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].path.starts_with(name); ++i)
  1316. suggestions.append({ cached_path[i].path, " "sv });
  1317. suggestions.append({ cached_path[index].path, " "sv });
  1318. for (auto& entry : suggestions) {
  1319. entry.input_offset = token_length;
  1320. entry.invariant_offset = invariant_offset;
  1321. entry.static_offset = static_offset;
  1322. }
  1323. return suggestions;
  1324. }
  1325. Vector<Line::CompletionSuggestion> Shell::complete_variable(StringView name, size_t offset)
  1326. {
  1327. Vector<Line::CompletionSuggestion> suggestions;
  1328. auto pattern = offset ? name.substring_view(0, offset) : ""sv;
  1329. auto invariant_offset = offset;
  1330. size_t static_offset = 0;
  1331. if (m_editor)
  1332. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1333. // Look at local variables.
  1334. for (auto& frame : m_local_frames) {
  1335. for (auto& variable : frame.local_variables) {
  1336. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1337. suggestions.append(variable.key);
  1338. }
  1339. }
  1340. // Look at the environment.
  1341. for (auto i = 0; environ[i]; ++i) {
  1342. StringView entry { environ[i], strlen(environ[i]) };
  1343. if (entry.starts_with(pattern)) {
  1344. auto parts = entry.split_view('=');
  1345. if (parts.is_empty() || parts.first().is_empty())
  1346. continue;
  1347. DeprecatedString name = parts.first();
  1348. if (suggestions.contains_slow(name))
  1349. continue;
  1350. suggestions.append(move(name));
  1351. }
  1352. }
  1353. for (auto& entry : suggestions) {
  1354. entry.input_offset = offset;
  1355. entry.invariant_offset = invariant_offset;
  1356. entry.static_offset = static_offset;
  1357. }
  1358. return suggestions;
  1359. }
  1360. Vector<Line::CompletionSuggestion> Shell::complete_user(StringView name, size_t offset)
  1361. {
  1362. Vector<Line::CompletionSuggestion> suggestions;
  1363. auto pattern = offset ? name.substring_view(0, offset) : ""sv;
  1364. auto invariant_offset = offset;
  1365. size_t static_offset = 0;
  1366. if (m_editor)
  1367. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1368. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1369. if (di.has_error())
  1370. return suggestions;
  1371. while (di.has_next()) {
  1372. DeprecatedString name = di.next_path();
  1373. if (name.starts_with(pattern)) {
  1374. suggestions.append(name);
  1375. auto& suggestion = suggestions.last();
  1376. suggestion.input_offset = offset;
  1377. suggestion.invariant_offset = invariant_offset;
  1378. suggestion.static_offset = static_offset;
  1379. }
  1380. }
  1381. return suggestions;
  1382. }
  1383. Vector<Line::CompletionSuggestion> Shell::complete_option(StringView program_name, StringView option, size_t offset, AST::Node const* command_node, AST::Node const* node)
  1384. {
  1385. if (command_node) {
  1386. auto program_results = complete_via_program_itself(offset, command_node, node, EscapeMode::Bareword, program_name);
  1387. if (!program_results.is_error())
  1388. return program_results.release_value();
  1389. }
  1390. size_t start = 0;
  1391. while (start < option.length() && option[start] == '-' && start < 2)
  1392. ++start;
  1393. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : ""sv;
  1394. auto invariant_offset = offset;
  1395. size_t static_offset = 0;
  1396. if (m_editor)
  1397. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1398. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1399. return {};
  1400. }
  1401. ErrorOr<Vector<Line::CompletionSuggestion>> Shell::complete_via_program_itself(size_t, AST::Node const* command_node, AST::Node const* node, EscapeMode, StringView known_program_name)
  1402. {
  1403. if (!command_node)
  1404. return Error::from_string_literal("Cannot complete null command");
  1405. if (command_node->would_execute())
  1406. return Error::from_string_literal("Refusing to complete nodes that would execute");
  1407. DeprecatedString program_name_storage;
  1408. if (known_program_name.is_null()) {
  1409. auto node = command_node->leftmost_trivial_literal();
  1410. if (!node)
  1411. return Error::from_string_literal("Cannot complete");
  1412. program_name_storage = node->run(*this)->resolve_as_string(*this);
  1413. known_program_name = program_name_storage;
  1414. }
  1415. auto program_name = known_program_name;
  1416. AST::Command completion_command;
  1417. completion_command.argv.append(program_name);
  1418. completion_command = expand_aliases({ completion_command }).last();
  1419. auto completion_utility_name = DeprecatedString::formatted("_complete_{}", completion_command.argv[0]);
  1420. if (binary_search(cached_path.span(), completion_utility_name, nullptr, RunnablePathComparator {}) != nullptr)
  1421. completion_command.argv[0] = completion_utility_name;
  1422. else if (!options.invoke_program_for_autocomplete)
  1423. return Error::from_string_literal("Refusing to use the program itself as completion source");
  1424. completion_command.argv.extend({ "--complete", "--" });
  1425. struct Visitor : public AST::NodeVisitor {
  1426. Visitor(Shell& shell, AST::Position position)
  1427. : shell(shell)
  1428. , completion_position(position)
  1429. {
  1430. lists.empend();
  1431. }
  1432. Shell& shell;
  1433. AST::Position completion_position;
  1434. Vector<Vector<DeprecatedString>> lists;
  1435. bool fail { false };
  1436. void push_list() { lists.empend(); }
  1437. Vector<DeprecatedString> pop_list() { return lists.take_last(); }
  1438. Vector<DeprecatedString>& list() { return lists.last(); }
  1439. bool should_include(AST::Node const* node) const { return node->position().end_offset <= completion_position.end_offset; }
  1440. virtual void visit(AST::BarewordLiteral const* node) override
  1441. {
  1442. if (should_include(node))
  1443. list().append(node->text());
  1444. }
  1445. virtual void visit(AST::BraceExpansion const* node) override
  1446. {
  1447. if (should_include(node))
  1448. list().extend(static_cast<AST::Node*>(const_cast<AST::BraceExpansion*>(node))->run(shell)->resolve_as_list(shell));
  1449. }
  1450. virtual void visit(AST::CommandLiteral const* node) override
  1451. {
  1452. if (should_include(node))
  1453. list().extend(node->command().argv);
  1454. }
  1455. virtual void visit(AST::DynamicEvaluate const* node) override
  1456. {
  1457. if (should_include(node))
  1458. fail = true;
  1459. }
  1460. virtual void visit(AST::DoubleQuotedString const* node) override
  1461. {
  1462. if (!should_include(node))
  1463. return;
  1464. push_list();
  1465. AST::NodeVisitor::visit(node);
  1466. auto list = pop_list();
  1467. StringBuilder builder;
  1468. builder.join(""sv, list);
  1469. this->list().append(builder.to_deprecated_string());
  1470. }
  1471. virtual void visit(AST::Glob const* node) override
  1472. {
  1473. if (should_include(node))
  1474. list().append(node->text());
  1475. }
  1476. virtual void visit(AST::Heredoc const* node) override
  1477. {
  1478. if (!should_include(node))
  1479. return;
  1480. push_list();
  1481. AST::NodeVisitor::visit(node);
  1482. auto list = pop_list();
  1483. StringBuilder builder;
  1484. builder.join(""sv, list);
  1485. this->list().append(builder.to_deprecated_string());
  1486. }
  1487. virtual void visit(AST::ImmediateExpression const* node) override
  1488. {
  1489. if (should_include(node))
  1490. fail = true;
  1491. }
  1492. virtual void visit(AST::Range const* node) override
  1493. {
  1494. if (!should_include(node))
  1495. return;
  1496. push_list();
  1497. node->start()->visit(*this);
  1498. list().append(pop_list().first());
  1499. }
  1500. virtual void visit(AST::SimpleVariable const* node) override
  1501. {
  1502. if (should_include(node))
  1503. list().extend(static_cast<AST::Node*>(const_cast<AST::SimpleVariable*>(node))->run(shell)->resolve_as_list(shell));
  1504. }
  1505. virtual void visit(AST::SpecialVariable const* node) override
  1506. {
  1507. if (should_include(node))
  1508. list().extend(static_cast<AST::Node*>(const_cast<AST::SpecialVariable*>(node))->run(shell)->resolve_as_list(shell));
  1509. }
  1510. virtual void visit(AST::Juxtaposition const* node) override
  1511. {
  1512. if (!should_include(node))
  1513. return;
  1514. push_list();
  1515. node->left()->visit(*this);
  1516. auto left = pop_list();
  1517. push_list();
  1518. node->right()->visit(*this);
  1519. auto right = pop_list();
  1520. StringBuilder builder;
  1521. for (auto& left_entry : left) {
  1522. for (auto& right_entry : right) {
  1523. builder.append(left_entry);
  1524. builder.append(right_entry);
  1525. list().append(builder.to_deprecated_string());
  1526. builder.clear();
  1527. }
  1528. }
  1529. }
  1530. virtual void visit(AST::StringLiteral const* node) override
  1531. {
  1532. if (should_include(node))
  1533. list().append(node->text());
  1534. }
  1535. virtual void visit(AST::Tilde const* node) override
  1536. {
  1537. if (should_include(node))
  1538. list().extend(static_cast<AST::Node*>(const_cast<AST::Tilde*>(node))->run(shell)->resolve_as_list(shell));
  1539. }
  1540. virtual void visit(AST::PathRedirectionNode const*) override { }
  1541. virtual void visit(AST::CloseFdRedirection const*) override { }
  1542. virtual void visit(AST::Fd2FdRedirection const*) override { }
  1543. virtual void visit(AST::Execute const*) override { }
  1544. virtual void visit(AST::ReadRedirection const*) override { }
  1545. virtual void visit(AST::ReadWriteRedirection const*) override { }
  1546. virtual void visit(AST::WriteAppendRedirection const*) override { }
  1547. virtual void visit(AST::WriteRedirection const*) override { }
  1548. } visitor { *this, node ? node->position() : AST::Position() };
  1549. command_node->visit(visitor);
  1550. if (visitor.fail)
  1551. return Error::from_string_literal("Cannot complete");
  1552. completion_command.argv.extend(visitor.list());
  1553. completion_command.should_wait = true;
  1554. completion_command.redirections.append(AST::PathRedirection::create("/dev/null", STDERR_FILENO, AST::PathRedirection::Write));
  1555. completion_command.redirections.append(AST::PathRedirection::create("/dev/null", STDIN_FILENO, AST::PathRedirection::Read));
  1556. auto execute_node = make_ref_counted<AST::Execute>(
  1557. AST::Position {},
  1558. make_ref_counted<AST::CommandLiteral>(AST::Position {}, move(completion_command)),
  1559. true);
  1560. Vector<Line::CompletionSuggestion> suggestions;
  1561. auto timer = TRY(Core::Timer::create_single_shot(300, [&] {
  1562. Core::EventLoop::current().quit(1);
  1563. }));
  1564. timer->start();
  1565. // Restrict the process to effectively readonly access to the FS.
  1566. auto scoped_promise = promise({
  1567. .exec_promises = "stdio rpath prot_exec no_error",
  1568. .unveils = {
  1569. { "/", "rx" },
  1570. },
  1571. });
  1572. {
  1573. TemporaryChange change(m_is_interactive, false);
  1574. execute_node->for_each_entry(*this, [&](NonnullRefPtr<AST::Value> entry) -> IterationDecision {
  1575. auto result = entry->resolve_as_string(*this);
  1576. JsonParser parser(result);
  1577. auto parsed_result = parser.parse();
  1578. if (parsed_result.is_error())
  1579. return IterationDecision::Continue;
  1580. auto parsed = parsed_result.release_value();
  1581. if (parsed.is_object()) {
  1582. auto& object = parsed.as_object();
  1583. auto kind = object.get_deprecated_string("kind"sv).value_or("plain");
  1584. if (kind == "path") {
  1585. auto base = object.get_deprecated_string("base"sv).value_or("");
  1586. auto part = object.get_deprecated_string("part"sv).value_or("");
  1587. auto executable_only = object.get_bool("executable_only"sv).value_or(false) ? ExecutableOnly::Yes : ExecutableOnly::No;
  1588. suggestions.extend(complete_path(base, part, part.length(), executable_only, nullptr, nullptr));
  1589. } else if (kind == "program") {
  1590. auto name = object.get_deprecated_string("name"sv).value_or("");
  1591. suggestions.extend(complete_program_name(name, name.length()));
  1592. } else if (kind == "proxy") {
  1593. if (m_completion_stack_info.size_free() < 4 * KiB) {
  1594. dbgln("Not enough stack space, recursion?");
  1595. return IterationDecision::Continue;
  1596. }
  1597. auto argv = object.get_deprecated_string("argv"sv).value_or("");
  1598. dbgln("Proxy completion for {}", argv);
  1599. suggestions.extend(complete(argv));
  1600. } else if (kind == "plain") {
  1601. Line::CompletionSuggestion suggestion {
  1602. object.get_deprecated_string("completion"sv).value_or(""),
  1603. object.get_deprecated_string("trailing_trivia"sv).value_or(""),
  1604. object.get_deprecated_string("display_trivia"sv).value_or(""),
  1605. };
  1606. suggestion.static_offset = object.get_u64("static_offset"sv).value_or(0);
  1607. suggestion.invariant_offset = object.get_u64("invariant_offset"sv).value_or(0);
  1608. suggestion.allow_commit_without_listing = object.get_bool("allow_commit_without_listing"sv).value_or(true);
  1609. suggestions.append(move(suggestion));
  1610. } else {
  1611. dbgln("LibLine: Unhandled completion kind: {}", kind);
  1612. }
  1613. } else {
  1614. suggestions.append(parsed.to_deprecated_string());
  1615. }
  1616. return IterationDecision::Continue;
  1617. });
  1618. }
  1619. auto pgid = getpgrp();
  1620. tcsetpgrp(STDOUT_FILENO, pgid);
  1621. tcsetpgrp(STDIN_FILENO, pgid);
  1622. if (suggestions.is_empty())
  1623. return Error::from_string_literal("No results");
  1624. return suggestions;
  1625. }
  1626. Vector<Line::CompletionSuggestion> Shell::complete_immediate_function_name(StringView name, size_t offset)
  1627. {
  1628. Vector<Line::CompletionSuggestion> suggestions;
  1629. auto invariant_offset = offset;
  1630. size_t static_offset = 0;
  1631. if (m_editor)
  1632. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1633. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(fn_name) \
  1634. if (auto name_view = #fn_name##sv; name_view.starts_with(name)) \
  1635. suggestions.append({ name_view, " "sv });
  1636. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  1637. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  1638. for (auto& entry : suggestions) {
  1639. entry.input_offset = offset;
  1640. entry.invariant_offset = invariant_offset;
  1641. entry.static_offset = static_offset;
  1642. }
  1643. return suggestions;
  1644. }
  1645. void Shell::bring_cursor_to_beginning_of_a_line() const
  1646. {
  1647. struct winsize ws;
  1648. if (m_editor) {
  1649. ws = m_editor->terminal_size();
  1650. } else {
  1651. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1652. // Very annoying assumptions.
  1653. ws.ws_col = 80;
  1654. ws.ws_row = 25;
  1655. }
  1656. }
  1657. // Black with Cyan background.
  1658. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1659. DeprecatedString eol_mark = getenv("PROMPT_EOL_MARK");
  1660. if (eol_mark.is_null())
  1661. eol_mark = default_mark;
  1662. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1663. if (eol_mark_length >= ws.ws_col) {
  1664. eol_mark = default_mark;
  1665. eol_mark_length = 1;
  1666. }
  1667. fputs(eol_mark.characters(), stderr);
  1668. // We write a line's worth of whitespace to the terminal. This way, we ensure that
  1669. // the prompt ends up on a new line even if there is dangling output on the current line.
  1670. size_t fill_count = ws.ws_col - eol_mark_length;
  1671. auto fill_buffer = DeprecatedString::repeated(' ', fill_count);
  1672. fwrite(fill_buffer.characters(), 1, fill_count, stderr);
  1673. putc('\r', stderr);
  1674. }
  1675. bool Shell::has_history_event(StringView source)
  1676. {
  1677. struct : public AST::NodeVisitor {
  1678. virtual void visit(const AST::HistoryEvent* node) override
  1679. {
  1680. has_history_event = true;
  1681. AST::NodeVisitor::visit(node);
  1682. }
  1683. bool has_history_event { false };
  1684. } visitor;
  1685. auto ast = Parser { source, true }.parse();
  1686. if (!ast)
  1687. return false;
  1688. ast->visit(visitor);
  1689. return visitor.has_history_event;
  1690. }
  1691. bool Shell::read_single_line()
  1692. {
  1693. while (true) {
  1694. restore_ios();
  1695. bring_cursor_to_beginning_of_a_line();
  1696. auto line_result = m_editor->get_line(prompt());
  1697. if (line_result.is_error()) {
  1698. auto is_eof = line_result.error() == Line::Editor::Error::Eof;
  1699. auto is_empty = line_result.error() == Line::Editor::Error::Empty;
  1700. if (is_eof || is_empty) {
  1701. // Pretend the user tried to execute builtin_exit()
  1702. auto exit_code = run_command("exit"sv);
  1703. if (exit_code != 0) {
  1704. // If we didn't end up actually calling exit(), and the command didn't succeed, just pretend it's all okay
  1705. // unless we can't, then just quit anyway.
  1706. if (!is_empty)
  1707. continue;
  1708. }
  1709. }
  1710. Core::EventLoop::current().quit(1);
  1711. return false;
  1712. }
  1713. auto& line = line_result.value();
  1714. if (line.is_empty())
  1715. return true;
  1716. run_command(line);
  1717. if (!has_history_event(line))
  1718. m_editor->add_to_history(line);
  1719. return true;
  1720. }
  1721. }
  1722. void Shell::custom_event(Core::CustomEvent& event)
  1723. {
  1724. if (event.custom_type() == ReadLine) {
  1725. if (read_single_line())
  1726. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1727. return;
  1728. }
  1729. }
  1730. void Shell::notify_child_event()
  1731. {
  1732. Vector<u64> disowned_jobs;
  1733. // Workaround the fact that we can't receive *who* exactly changed state.
  1734. // The child might still be alive (and even running) when this signal is dispatched to us
  1735. // so just...repeat until we find a suitable child.
  1736. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1737. // until the next child event we can actually handle, so stop after spending a total of 5110us (~5ms) on it.
  1738. bool found_child = false;
  1739. size_t const max_tries = 10;
  1740. size_t valid_attempts = max_tries;
  1741. useconds_t backoff_usec = 20;
  1742. int backoff_multiplier = 2;
  1743. for (;;) {
  1744. if (found_child || --valid_attempts == 0)
  1745. break;
  1746. // Ignore stray SIGCHLD when there are no jobs.
  1747. if (jobs.is_empty())
  1748. return;
  1749. if (valid_attempts < max_tries - 1) {
  1750. usleep(backoff_usec);
  1751. backoff_usec *= backoff_multiplier;
  1752. }
  1753. for (auto& it : jobs) {
  1754. auto job_id = it.key;
  1755. auto& job = *it.value;
  1756. int wstatus = 0;
  1757. dbgln_if(SH_DEBUG, "waitpid({} = {}) = ...", job.pid(), job.cmd());
  1758. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1759. dbgln_if(SH_DEBUG, "... = {} - exited: {}, suspended: {}", child_pid, WIFEXITED(wstatus), WIFSTOPPED(wstatus));
  1760. if (child_pid < 0) {
  1761. if (errno == ECHILD) {
  1762. // The child process went away before we could process its death, just assume it exited all ok.
  1763. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1764. child_pid = job.pid();
  1765. } else {
  1766. VERIFY_NOT_REACHED();
  1767. }
  1768. }
  1769. if (child_pid == 0) {
  1770. // If the child existed, but wasn't dead.
  1771. if (job.is_suspended() || job.shell_did_continue()) {
  1772. // The job was suspended, and someone sent it a SIGCONT.
  1773. job.set_is_suspended(false);
  1774. if (job.shell_did_continue())
  1775. job.set_shell_did_continue(false);
  1776. found_child = true;
  1777. }
  1778. continue;
  1779. }
  1780. if (child_pid == job.pid()) {
  1781. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1782. auto signal = WTERMSIG(wstatus);
  1783. job.set_signalled(signal);
  1784. if (signal == SIGINT)
  1785. raise_error(ShellError::InternalControlFlowInterrupted, "Interrupted"sv, job.command().position);
  1786. else if (signal == SIGKILL)
  1787. raise_error(ShellError::InternalControlFlowKilled, "Interrupted"sv, job.command().position);
  1788. } else if (WIFEXITED(wstatus)) {
  1789. job.set_has_exit(WEXITSTATUS(wstatus));
  1790. } else if (WIFSTOPPED(wstatus)) {
  1791. job.unblock();
  1792. job.set_is_suspended(true);
  1793. }
  1794. found_child = true;
  1795. }
  1796. if (job.should_be_disowned())
  1797. disowned_jobs.append(job_id);
  1798. }
  1799. for (auto job_id : disowned_jobs) {
  1800. jobs.remove(job_id);
  1801. }
  1802. }
  1803. }
  1804. Shell::Shell()
  1805. : m_default_constructed(true)
  1806. {
  1807. push_frame("main").leak_frame();
  1808. int rc = gethostname(hostname, Shell::HostNameSize);
  1809. if (rc < 0)
  1810. perror("gethostname");
  1811. {
  1812. auto* pw = getpwuid(getuid());
  1813. if (pw) {
  1814. username = pw->pw_name;
  1815. home = pw->pw_dir;
  1816. setenv("HOME", pw->pw_dir, 1);
  1817. }
  1818. endpwent();
  1819. }
  1820. // For simplicity, start at the user's home directory.
  1821. this->cwd = home;
  1822. setenv("PWD", home.characters(), 1);
  1823. // Add the default PATH vars.
  1824. {
  1825. StringBuilder path;
  1826. auto const* path_env_ptr = getenv("PATH");
  1827. if (path_env_ptr != NULL)
  1828. path.append({ path_env_ptr, strlen(path_env_ptr) });
  1829. if (path.length())
  1830. path.append(":"sv);
  1831. path.append(DEFAULT_PATH_SV);
  1832. setenv("PATH", path.to_deprecated_string().characters(), true);
  1833. }
  1834. cache_path();
  1835. }
  1836. Shell::Shell(Line::Editor& editor, bool attempt_interactive, bool posix_mode)
  1837. : m_in_posix_mode(posix_mode)
  1838. , m_editor(editor)
  1839. {
  1840. uid = getuid();
  1841. tcsetpgrp(0, getpgrp());
  1842. m_pid = getpid();
  1843. push_frame("main").leak_frame();
  1844. int rc = gethostname(hostname, Shell::HostNameSize);
  1845. if (rc < 0)
  1846. perror("gethostname");
  1847. auto istty = isatty(STDIN_FILENO);
  1848. m_is_interactive = attempt_interactive && istty;
  1849. if (istty) {
  1850. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1851. if (rc < 0)
  1852. perror("ttyname_r");
  1853. } else {
  1854. ttyname[0] = 0;
  1855. }
  1856. {
  1857. auto* cwd = getcwd(nullptr, 0);
  1858. this->cwd = cwd;
  1859. setenv("PWD", cwd, 1);
  1860. free(cwd);
  1861. }
  1862. {
  1863. auto* pw = getpwuid(getuid());
  1864. if (pw) {
  1865. username = pw->pw_name;
  1866. home = pw->pw_dir;
  1867. setenv("HOME", pw->pw_dir, 1);
  1868. }
  1869. endpwent();
  1870. }
  1871. directory_stack.append(cwd);
  1872. if (m_is_interactive) {
  1873. m_editor->load_history(get_history_path());
  1874. cache_path();
  1875. }
  1876. m_editor->register_key_input_callback('\n', [this](Line::Editor& editor) {
  1877. auto ast = parse(editor.line(), false);
  1878. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1879. return true;
  1880. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1881. });
  1882. start_timer(3000);
  1883. }
  1884. Shell::~Shell()
  1885. {
  1886. if (m_default_constructed)
  1887. return;
  1888. stop_all_jobs();
  1889. if (!m_is_interactive)
  1890. return;
  1891. m_editor->save_history(get_history_path());
  1892. }
  1893. void Shell::stop_all_jobs()
  1894. {
  1895. if (!jobs.is_empty()) {
  1896. if (m_is_interactive && !m_is_subshell)
  1897. printf("Killing active jobs\n");
  1898. for (auto& entry : jobs) {
  1899. if (entry.value->is_suspended()) {
  1900. dbgln_if(SH_DEBUG, "Job {} is suspended", entry.value->pid());
  1901. kill_job(entry.value, SIGCONT);
  1902. }
  1903. kill_job(entry.value, SIGHUP);
  1904. }
  1905. usleep(10000); // Wait for a bit before killing the job
  1906. for (auto& entry : jobs) {
  1907. dbgln_if(SH_DEBUG, "Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1908. kill_job(entry.value, SIGKILL);
  1909. }
  1910. jobs.clear();
  1911. }
  1912. }
  1913. u64 Shell::find_last_job_id() const
  1914. {
  1915. u64 job_id = 0;
  1916. for (auto& entry : jobs) {
  1917. if (entry.value->job_id() > job_id)
  1918. job_id = entry.value->job_id();
  1919. }
  1920. return job_id;
  1921. }
  1922. Job const* Shell::find_job(u64 id, bool is_pid)
  1923. {
  1924. for (auto& entry : jobs) {
  1925. if (is_pid) {
  1926. if (entry.value->pid() == static_cast<int>(id))
  1927. return entry.value;
  1928. } else {
  1929. if (entry.value->job_id() == id)
  1930. return entry.value;
  1931. }
  1932. }
  1933. return nullptr;
  1934. }
  1935. void Shell::kill_job(Job const* job, int sig)
  1936. {
  1937. if (!job)
  1938. return;
  1939. if (killpg(job->pgid(), sig) < 0) {
  1940. if (kill(job->pid(), sig) < 0) {
  1941. if (errno != ESRCH)
  1942. perror("kill");
  1943. }
  1944. }
  1945. }
  1946. void Shell::save_to(JsonObject& object)
  1947. {
  1948. Core::Object::save_to(object);
  1949. object.set("working_directory", cwd);
  1950. object.set("username", username);
  1951. object.set("user_home_path", home);
  1952. object.set("user_id", uid);
  1953. object.set("directory_stack_size", directory_stack.size());
  1954. object.set("cd_history_size", cd_history.size());
  1955. // Jobs.
  1956. JsonArray job_objects;
  1957. for (auto& job_entry : jobs) {
  1958. JsonObject job_object;
  1959. job_object.set("pid", job_entry.value->pid());
  1960. job_object.set("pgid", job_entry.value->pgid());
  1961. job_object.set("running_time", job_entry.value->timer().elapsed());
  1962. job_object.set("command", job_entry.value->cmd());
  1963. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1964. job_objects.append(move(job_object));
  1965. }
  1966. object.set("jobs", move(job_objects));
  1967. }
  1968. void Shell::possibly_print_error() const
  1969. {
  1970. switch (m_error) {
  1971. case ShellError::EvaluatedSyntaxError:
  1972. warnln("Shell Syntax Error: {}", m_error_description);
  1973. break;
  1974. case ShellError::InvalidSliceContentsError:
  1975. case ShellError::InvalidGlobError:
  1976. case ShellError::NonExhaustiveMatchRules:
  1977. warnln("Shell: {}", m_error_description);
  1978. break;
  1979. case ShellError::OpenFailure:
  1980. warnln("Shell: Open failed for {}", m_error_description);
  1981. break;
  1982. case ShellError::OutOfMemory:
  1983. warnln("Shell: Hit an OOM situation");
  1984. break;
  1985. case ShellError::LaunchError:
  1986. warnln("Shell: {}", m_error_description);
  1987. break;
  1988. case ShellError::InternalControlFlowBreak:
  1989. case ShellError::InternalControlFlowContinue:
  1990. case ShellError::InternalControlFlowInterrupted:
  1991. case ShellError::InternalControlFlowKilled:
  1992. return;
  1993. case ShellError::None:
  1994. return;
  1995. }
  1996. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  1997. auto& source_position = m_source_position.value();
  1998. auto do_line = [&](auto line, auto& current_line) {
  1999. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  2000. warnln("{:>3}| {}", line, current_line);
  2001. if (is_in_range) {
  2002. warn("\x1b[31m");
  2003. size_t length_written_so_far = 0;
  2004. if (line == (i64)source_position.position->start_line.line_number) {
  2005. warn("{:~>{}}", "", 5 + source_position.position->start_line.line_column);
  2006. length_written_so_far += source_position.position->start_line.line_column;
  2007. } else {
  2008. warn("{:~>{}}", "", 5);
  2009. }
  2010. if (line == (i64)source_position.position->end_line.line_number) {
  2011. warn("{:^>{}}", "", source_position.position->end_line.line_column - length_written_so_far);
  2012. length_written_so_far += source_position.position->start_line.line_column;
  2013. } else {
  2014. warn("{:^>{}}", "", current_line.length() - length_written_so_far);
  2015. }
  2016. warnln("\x1b[0m");
  2017. }
  2018. };
  2019. int line = -1;
  2020. DeprecatedString current_line;
  2021. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  2022. if (!source_position.source_file.is_null()) {
  2023. auto file = Core::DeprecatedFile::open(source_position.source_file, Core::OpenMode::ReadOnly);
  2024. if (file.is_error()) {
  2025. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file.error(), source_position.source_file);
  2026. return;
  2027. }
  2028. while (line < line_to_skip_to) {
  2029. if (file.value()->eof())
  2030. return;
  2031. current_line = file.value()->read_line();
  2032. ++line;
  2033. }
  2034. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  2035. do_line(line, current_line);
  2036. if (file.value()->eof())
  2037. current_line = "";
  2038. else
  2039. current_line = file.value()->read_line();
  2040. }
  2041. } else if (!source_position.literal_source_text.is_empty()) {
  2042. GenericLexer lexer { source_position.literal_source_text };
  2043. while (line < line_to_skip_to) {
  2044. if (lexer.is_eof())
  2045. return;
  2046. current_line = lexer.consume_line();
  2047. ++line;
  2048. }
  2049. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  2050. do_line(line, current_line);
  2051. if (lexer.is_eof())
  2052. current_line = "";
  2053. else
  2054. current_line = lexer.consume_line();
  2055. }
  2056. }
  2057. }
  2058. warnln();
  2059. }
  2060. Optional<int> Shell::resolve_job_spec(StringView str)
  2061. {
  2062. if (!str.starts_with('%'))
  2063. return {};
  2064. // %number -> job id <number>
  2065. if (auto number = str.substring_view(1).to_uint(); number.has_value())
  2066. return number.value();
  2067. // '%?str' -> iterate jobs and pick one with `str' in its command
  2068. // Note: must be quoted, since '?' will turn it into a glob - pretty ugly...
  2069. GenericLexer lexer { str.substring_view(1) };
  2070. if (!lexer.consume_specific('?'))
  2071. return {};
  2072. auto search_term = lexer.remaining();
  2073. for (auto& it : jobs) {
  2074. if (it.value->cmd().contains(search_term))
  2075. return it.key;
  2076. }
  2077. return {};
  2078. }
  2079. void Shell::timer_event(Core::TimerEvent& event)
  2080. {
  2081. event.accept();
  2082. if (m_is_subshell)
  2083. return;
  2084. auto const* autosave_env_ptr = getenv("HISTORY_AUTOSAVE_TIME_MS");
  2085. auto option = autosave_env_ptr != NULL ? StringView { autosave_env_ptr, strlen(autosave_env_ptr) } : StringView {};
  2086. auto time = option.to_uint();
  2087. if (!time.has_value() || time.value() == 0) {
  2088. m_history_autosave_time.clear();
  2089. stop_timer();
  2090. start_timer(3000);
  2091. return;
  2092. }
  2093. if (m_history_autosave_time != time) {
  2094. m_history_autosave_time = time.value();
  2095. stop_timer();
  2096. start_timer(m_history_autosave_time.value());
  2097. }
  2098. if (!m_history_autosave_time.has_value())
  2099. return;
  2100. if (m_editor && m_editor->is_history_dirty())
  2101. m_editor->save_history(get_history_path());
  2102. }
  2103. RefPtr<AST::Node> Shell::parse(StringView input, bool interactive, bool as_command) const
  2104. {
  2105. if (m_in_posix_mode) {
  2106. Posix::Parser parser(input);
  2107. if (as_command) {
  2108. auto node = parser.parse();
  2109. if constexpr (SHELL_POSIX_PARSER_DEBUG) {
  2110. dbgln("Parsed with the POSIX Parser:");
  2111. node->dump(0);
  2112. }
  2113. return node;
  2114. }
  2115. return parser.parse_word_list();
  2116. }
  2117. Parser parser { input, interactive };
  2118. if (as_command)
  2119. return parser.parse();
  2120. auto nodes = parser.parse_as_multiple_expressions();
  2121. return make_ref_counted<AST::ListConcatenate>(
  2122. nodes.is_empty() ? AST::Position { 0, 0, { 0, 0 }, { 0, 0 } } : nodes.first().position(),
  2123. move(nodes));
  2124. }
  2125. void FileDescriptionCollector::collect()
  2126. {
  2127. for (auto fd : m_fds)
  2128. close(fd);
  2129. m_fds.clear();
  2130. }
  2131. FileDescriptionCollector::~FileDescriptionCollector()
  2132. {
  2133. collect();
  2134. }
  2135. void FileDescriptionCollector::add(int fd)
  2136. {
  2137. m_fds.append(fd);
  2138. }
  2139. SavedFileDescriptors::SavedFileDescriptors(NonnullRefPtrVector<AST::Rewiring> const& intended_rewirings)
  2140. {
  2141. for (auto& rewiring : intended_rewirings) {
  2142. int new_fd = dup(rewiring.new_fd);
  2143. if (new_fd < 0) {
  2144. if (errno != EBADF)
  2145. perror("dup");
  2146. // The fd that will be overwritten isn't open right now,
  2147. // it will be cleaned up by the exec()-side collector
  2148. // and we have nothing to do here, so just ignore this error.
  2149. continue;
  2150. }
  2151. auto flags = fcntl(new_fd, F_GETFD);
  2152. auto rc = fcntl(new_fd, F_SETFD, flags | FD_CLOEXEC);
  2153. VERIFY(rc == 0);
  2154. m_saves.append({ rewiring.new_fd, new_fd });
  2155. m_collector.add(new_fd);
  2156. }
  2157. }
  2158. SavedFileDescriptors::~SavedFileDescriptors()
  2159. {
  2160. for (auto& save : m_saves) {
  2161. if (dup2(save.saved, save.original) < 0) {
  2162. perror("dup2(~SavedFileDescriptors)");
  2163. continue;
  2164. }
  2165. }
  2166. }
  2167. }