Shell.cpp 68 KB

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