Shell.cpp 65 KB

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