Shell.cpp 66 KB

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