Shell.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  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/LexicalPath.h>
  13. #include <AK/QuickSort.h>
  14. #include <AK/ScopeGuard.h>
  15. #include <AK/ScopedValueRollback.h>
  16. #include <AK/StringBuilder.h>
  17. #include <AK/TemporaryChange.h>
  18. #include <AK/URL.h>
  19. #include <LibCore/ArgsParser.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(const 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(const 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(const 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, const 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. function.body->run(*this);
  400. retval = last_return_code;
  401. return true;
  402. }
  403. String Shell::format(const 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. 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. 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(const 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(const 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. command->run(*this);
  482. if (!has_error(ShellError::None)) {
  483. possibly_print_error();
  484. take_error();
  485. return 1;
  486. }
  487. return last_return_code;
  488. }
  489. RefPtr<Job> Shell::run_command(const AST::Command& command)
  490. {
  491. FileDescriptionCollector fds;
  492. if (options.verbose)
  493. warnln("+ {}", command);
  494. // If the command is empty, store the redirections and apply them to all later commands.
  495. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  496. m_global_redirections.extend(command.redirections);
  497. for (auto& next_in_chain : command.next_chain)
  498. run_tail(command, next_in_chain, last_return_code);
  499. return nullptr;
  500. }
  501. // Resolve redirections.
  502. NonnullRefPtrVector<AST::Rewiring> rewirings;
  503. auto resolve_redirection = [&](auto& redirection) -> IterationDecision {
  504. auto rewiring_result = redirection.apply();
  505. if (rewiring_result.is_error()) {
  506. if (!rewiring_result.error().is_empty())
  507. warnln("error: {}", rewiring_result.error());
  508. return IterationDecision::Break;
  509. }
  510. auto& rewiring = rewiring_result.value();
  511. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseNew)
  512. rewirings.append(*rewiring);
  513. if (rewiring->fd_action == AST::Rewiring::Close::Old) {
  514. fds.add(rewiring->old_fd);
  515. } else if (rewiring->fd_action == AST::Rewiring::Close::New) {
  516. if (rewiring->new_fd != -1)
  517. fds.add(rewiring->new_fd);
  518. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseNew) {
  519. fds.add(rewiring->new_fd);
  520. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshNew) {
  521. VERIFY(rewiring->other_pipe_end);
  522. int pipe_fd[2];
  523. int rc = pipe(pipe_fd);
  524. if (rc < 0) {
  525. perror("pipe(RedirRefresh)");
  526. return IterationDecision::Break;
  527. }
  528. rewiring->new_fd = pipe_fd[1];
  529. rewiring->other_pipe_end->new_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. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshOld) {
  532. VERIFY(rewiring->other_pipe_end);
  533. int pipe_fd[2];
  534. int rc = pipe(pipe_fd);
  535. if (rc < 0) {
  536. perror("pipe(RedirRefresh)");
  537. return IterationDecision::Break;
  538. }
  539. rewiring->old_fd = pipe_fd[1];
  540. rewiring->other_pipe_end->old_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  541. fds.add(pipe_fd[1]);
  542. }
  543. return IterationDecision::Continue;
  544. };
  545. auto apply_rewirings = [&] {
  546. for (auto& rewiring : rewirings) {
  547. dbgln_if(SH_DEBUG, "in {}<{}>, dup2({}, {})", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.old_fd, rewiring.new_fd);
  548. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  549. if (rc < 0) {
  550. perror("dup2(run)");
  551. return IterationDecision::Break;
  552. }
  553. // {new,old}_fd is closed via the `fds` collector, but rewiring.other_pipe_end->{new,old}_fd
  554. // isn't yet in that collector when the first child spawns.
  555. if (rewiring.other_pipe_end) {
  556. if (rewiring.fd_action == AST::Rewiring::Close::RefreshNew) {
  557. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->new_fd) < 0)
  558. perror("close other pipe end");
  559. } else if (rewiring.fd_action == AST::Rewiring::Close::RefreshOld) {
  560. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->old_fd) < 0)
  561. perror("close other pipe end");
  562. }
  563. }
  564. }
  565. return IterationDecision::Continue;
  566. };
  567. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, false };
  568. for (auto& redirection : m_global_redirections) {
  569. if (resolve_redirection(redirection) == IterationDecision::Break)
  570. return nullptr;
  571. }
  572. for (auto& redirection : command.redirections) {
  573. if (resolve_redirection(redirection) == IterationDecision::Break)
  574. return nullptr;
  575. }
  576. if (command.should_wait && run_builtin(command, rewirings, last_return_code)) {
  577. for (auto& next_in_chain : command.next_chain)
  578. run_tail(command, next_in_chain, last_return_code);
  579. return nullptr;
  580. }
  581. auto can_be_run_in_current_process = command.should_wait && !command.pipeline && !command.argv.is_empty();
  582. if (can_be_run_in_current_process && has_function(command.argv.first())) {
  583. SavedFileDescriptors fds { rewirings };
  584. for (auto& rewiring : rewirings) {
  585. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  586. if (rc < 0) {
  587. perror("dup2(run)");
  588. return nullptr;
  589. }
  590. }
  591. if (invoke_function(command, last_return_code)) {
  592. for (auto& next_in_chain : command.next_chain)
  593. run_tail(command, next_in_chain, last_return_code);
  594. return nullptr;
  595. }
  596. }
  597. if (command.argv.is_empty()
  598. && !command.next_chain.is_empty()
  599. && command.should_immediately_execute_next
  600. && command.redirections.is_empty()
  601. && command.next_chain.first().node->should_override_execution_in_current_process()) {
  602. for (auto& next_in_chain : command.next_chain)
  603. run_tail(command, next_in_chain, last_return_code);
  604. return nullptr;
  605. }
  606. Vector<const char*> argv;
  607. Vector<String> copy_argv = command.argv;
  608. argv.ensure_capacity(command.argv.size() + 1);
  609. for (auto& arg : copy_argv)
  610. argv.append(arg.characters());
  611. argv.append(nullptr);
  612. int sync_pipe[2];
  613. if (pipe(sync_pipe) < 0) {
  614. perror("pipe");
  615. return nullptr;
  616. }
  617. pid_t child = fork();
  618. if (child < 0) {
  619. perror("fork");
  620. return nullptr;
  621. }
  622. if (child == 0) {
  623. close(sync_pipe[1]);
  624. m_is_subshell = true;
  625. m_pid = getpid();
  626. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  627. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, true };
  628. if (apply_rewirings() == IterationDecision::Break)
  629. _exit(126);
  630. fds.collect();
  631. u8 c;
  632. while (read(sync_pipe[0], &c, 1) < 0) {
  633. if (errno != EINTR) {
  634. perror("read");
  635. // There's nothing interesting we can do here.
  636. break;
  637. }
  638. }
  639. dbgln_if(SH_DEBUG, "Synced up with parent, we're good to exec()");
  640. close(sync_pipe[0]);
  641. if (!m_is_subshell && command.should_wait)
  642. tcsetattr(0, TCSANOW, &default_termios);
  643. if (command.should_immediately_execute_next) {
  644. VERIFY(command.argv.is_empty());
  645. Core::EventLoop mainloop;
  646. setup_signals();
  647. for (auto& next_in_chain : command.next_chain)
  648. run_tail(command, next_in_chain, 0);
  649. _exit(last_return_code);
  650. }
  651. if (run_builtin(command, {}, last_return_code))
  652. _exit(last_return_code);
  653. if (invoke_function(command, last_return_code))
  654. _exit(last_return_code);
  655. // We no longer need the jobs here.
  656. jobs.clear();
  657. execute_process(move(argv));
  658. VERIFY_NOT_REACHED();
  659. }
  660. close(sync_pipe[0]);
  661. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  662. if (command.pipeline) {
  663. if (is_first) {
  664. command.pipeline->pgid = child;
  665. }
  666. }
  667. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  668. if (!m_is_subshell || command.pipeline) {
  669. if (setpgid(child, pgid) < 0 && m_is_interactive)
  670. perror("setpgid");
  671. if (!m_is_subshell) {
  672. // There's no reason to care about the errors here
  673. // either we're in a tty, we're interactive, and this works
  674. // or we're not, and it fails - in which case, we don't need
  675. // stdin/stdout handoff to child processes anyway.
  676. tcsetpgrp(STDOUT_FILENO, pgid);
  677. tcsetpgrp(STDIN_FILENO, pgid);
  678. }
  679. }
  680. while (write(sync_pipe[1], "x", 1) < 0) {
  681. if (errno != EINTR) {
  682. perror("write");
  683. // There's nothing interesting we can do here.
  684. break;
  685. }
  686. }
  687. close(sync_pipe[1]);
  688. StringBuilder cmd;
  689. cmd.join(" ", command.argv);
  690. auto command_copy = AST::Command(command);
  691. // Clear the next chain if it's to be immediately executed
  692. // as the child will run this chain.
  693. if (command.should_immediately_execute_next)
  694. command_copy.next_chain.clear();
  695. auto job = Job::create(child, pgid, cmd.build(), find_last_job_id() + 1, move(command_copy));
  696. jobs.set((u64)child, job);
  697. job->on_exit = [this](auto job) {
  698. if (!job->exited())
  699. return;
  700. if (job->is_running_in_background() && job->should_announce_exit())
  701. warnln("Shell: Job {} ({}) exited\n", job->job_id(), job->cmd());
  702. else if (job->signaled() && job->should_announce_signal())
  703. warnln("Shell: Job {} ({}) {}\n", job->job_id(), job->cmd(), strsignal(job->termination_signal()));
  704. last_return_code = job->exit_code();
  705. job->disown();
  706. if (m_editor && job->exit_code() == 0 && is_allowed_to_modify_termios(job->command())) {
  707. m_editor->refetch_default_termios();
  708. default_termios = m_editor->default_termios();
  709. termios = m_editor->termios();
  710. }
  711. run_tail(job);
  712. };
  713. fds.collect();
  714. return *job;
  715. }
  716. void Shell::execute_process(Vector<const char*>&& argv)
  717. {
  718. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  719. if (rc < 0) {
  720. auto parts = StringView { argv[0] }.split_view('/');
  721. if (parts.size() == 1) {
  722. // If this is a path in the current directory and it caused execvp() to fail,
  723. // simply don't attempt to execute it, see #6774.
  724. warnln("{}: Command not found.", argv[0]);
  725. _exit(127);
  726. }
  727. int saved_errno = errno;
  728. struct stat st;
  729. if (stat(argv[0], &st)) {
  730. warnln("stat({}): {}", argv[0], strerror(errno));
  731. // Return code 127 on command not found.
  732. _exit(127);
  733. }
  734. if (!(st.st_mode & S_IXUSR)) {
  735. warnln("{}: Not executable", argv[0]);
  736. // Return code 126 when file is not executable.
  737. _exit(126);
  738. }
  739. if (saved_errno == ENOENT) {
  740. do {
  741. auto file_result = Core::File::open(argv[0], Core::OpenMode::ReadOnly);
  742. if (file_result.is_error())
  743. break;
  744. auto& file = file_result.value();
  745. auto line = file->read_line();
  746. if (!line.starts_with("#!"))
  747. break;
  748. GenericLexer shebang_lexer { line.substring_view(2) };
  749. auto shebang = shebang_lexer.consume_until(is_any_of("\n\r")).to_string();
  750. argv.prepend(shebang.characters());
  751. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  752. if (rc < 0) {
  753. warnln("{}: Invalid interpreter \"{}\": {}", argv[0], shebang.characters(), strerror(errno));
  754. _exit(126);
  755. }
  756. } while (false);
  757. warnln("{}: Command not found.", argv[0]);
  758. } else {
  759. if (S_ISDIR(st.st_mode)) {
  760. warnln("Shell: {}: Is a directory", argv[0]);
  761. _exit(126);
  762. }
  763. warnln("execvp({}): {}", argv[0], strerror(saved_errno));
  764. }
  765. _exit(126);
  766. }
  767. VERIFY_NOT_REACHED();
  768. }
  769. void Shell::run_tail(const AST::Command& invoking_command, const AST::NodeWithAction& next_in_chain, int head_exit_code)
  770. {
  771. if (m_error != ShellError::None) {
  772. possibly_print_error();
  773. if (!is_control_flow(m_error))
  774. take_error();
  775. return;
  776. }
  777. auto evaluate = [&] {
  778. if (next_in_chain.node->would_execute()) {
  779. next_in_chain.node->run(*this);
  780. return;
  781. }
  782. auto node = next_in_chain.node;
  783. if (!invoking_command.should_wait)
  784. node = adopt_ref(static_cast<AST::Node&>(*new AST::Background(next_in_chain.node->position(), move(node))));
  785. adopt_ref(static_cast<AST::Node&>(*new AST::Execute(next_in_chain.node->position(), move(node))))->run(*this);
  786. };
  787. switch (next_in_chain.action) {
  788. case AST::NodeWithAction::And:
  789. if (head_exit_code == 0)
  790. evaluate();
  791. break;
  792. case AST::NodeWithAction::Or:
  793. if (head_exit_code != 0)
  794. evaluate();
  795. break;
  796. case AST::NodeWithAction::Sequence:
  797. evaluate();
  798. break;
  799. }
  800. }
  801. void Shell::run_tail(RefPtr<Job> job)
  802. {
  803. if (auto cmd = job->command_ptr()) {
  804. deferred_invoke([=, this](auto&) {
  805. for (auto& next_in_chain : cmd->next_chain) {
  806. run_tail(*cmd, next_in_chain, job->exit_code());
  807. }
  808. });
  809. }
  810. }
  811. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  812. {
  813. if (m_error != ShellError::None) {
  814. possibly_print_error();
  815. if (!is_control_flow(m_error))
  816. take_error();
  817. return {};
  818. }
  819. NonnullRefPtrVector<Job> spawned_jobs;
  820. for (auto& command : commands) {
  821. if constexpr (SH_DEBUG) {
  822. dbgln("Command");
  823. for (auto& arg : command.argv)
  824. dbgln("argv: {}", arg);
  825. for (auto& redir : command.redirections) {
  826. if (redir.is_path_redirection()) {
  827. auto path_redir = (const AST::PathRedirection*)&redir;
  828. dbgln("redir path '{}' <-({})-> {}", path_redir->path, (int)path_redir->direction, path_redir->fd);
  829. } else if (redir.is_fd_redirection()) {
  830. auto* fdredir = (const AST::FdRedirection*)&redir;
  831. dbgln("redir fd {} -> {}", fdredir->old_fd, fdredir->new_fd);
  832. } else if (redir.is_close_redirection()) {
  833. auto close_redir = (const AST::CloseRedirection*)&redir;
  834. dbgln("close fd {}", close_redir->fd);
  835. } else {
  836. VERIFY_NOT_REACHED();
  837. }
  838. }
  839. }
  840. auto job = run_command(command);
  841. if (!job)
  842. continue;
  843. spawned_jobs.append(*job);
  844. if (command.should_wait) {
  845. block_on_job(job);
  846. } else {
  847. job->set_running_in_background(true);
  848. if (!command.is_pipe_source && command.should_notify_if_in_background)
  849. job->set_should_announce_exit(true);
  850. }
  851. }
  852. if (m_error != ShellError::None) {
  853. possibly_print_error();
  854. if (!is_control_flow(m_error))
  855. take_error();
  856. }
  857. return spawned_jobs;
  858. }
  859. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  860. {
  861. TemporaryChange script_change { current_script, filename };
  862. TemporaryChange interactive_change { m_is_interactive, false };
  863. TemporaryChange<Optional<SourcePosition>> source_change { m_source_position, SourcePosition { .source_file = filename, .literal_source_text = {}, .position = {} } };
  864. auto file_result = Core::File::open(filename, Core::OpenMode::ReadOnly);
  865. if (file_result.is_error()) {
  866. auto error = String::formatted("'{}': {}", escape_token_for_single_quotes(filename), file_result.error());
  867. if (explicitly_invoked)
  868. raise_error(ShellError::OpenFailure, error);
  869. else
  870. dbgln("open() failed for {}", error);
  871. return false;
  872. }
  873. auto file = file_result.value();
  874. auto data = file->read_all();
  875. return run_command(data) == 0;
  876. }
  877. bool Shell::is_allowed_to_modify_termios(const AST::Command& command) const
  878. {
  879. if (command.argv.is_empty())
  880. return false;
  881. auto value = lookup_local_variable("PROGRAMS_ALLOWED_TO_MODIFY_DEFAULT_TERMIOS"sv);
  882. if (!value)
  883. return false;
  884. return value->resolve_as_list(*this).contains_slow(command.argv[0]);
  885. }
  886. void Shell::restore_ios()
  887. {
  888. if (m_is_subshell)
  889. return;
  890. tcsetattr(0, TCSANOW, &termios);
  891. tcsetpgrp(STDOUT_FILENO, m_pid);
  892. tcsetpgrp(STDIN_FILENO, m_pid);
  893. }
  894. void Shell::block_on_pipeline(RefPtr<AST::Pipeline> pipeline)
  895. {
  896. if (!pipeline)
  897. return;
  898. for (auto& it : jobs) {
  899. if (auto cmd = it.value->command_ptr(); cmd->pipeline == pipeline && cmd->is_pipe_source)
  900. block_on_job(it.value);
  901. }
  902. }
  903. void Shell::block_on_job(RefPtr<Job> job)
  904. {
  905. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  906. if (!job)
  907. return;
  908. if (job->is_suspended() && !job->shell_did_continue())
  909. return; // We cannot wait for a suspended job.
  910. ScopeGuard io_restorer { [&]() {
  911. if (job->exited() && !job->is_running_in_background()) {
  912. restore_ios();
  913. }
  914. } };
  915. bool job_exited { false };
  916. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  917. if (old_exit)
  918. old_exit(job);
  919. job_exited = true;
  920. };
  921. if (job->exited())
  922. return;
  923. while (!job_exited)
  924. Core::EventLoop::current().pump();
  925. // If the job is part of a pipeline, wait for the rest of the members too.
  926. if (auto command = job->command_ptr())
  927. block_on_pipeline(command->pipeline);
  928. }
  929. String Shell::get_history_path()
  930. {
  931. if (auto histfile = getenv("HISTFILE"))
  932. return { histfile };
  933. return String::formatted("{}/.history", home);
  934. }
  935. String Shell::escape_token_for_single_quotes(const String& token)
  936. {
  937. // `foo bar \n '` -> `'foo bar \n '"'"`
  938. StringBuilder builder;
  939. builder.append("'");
  940. auto started_single_quote = true;
  941. for (auto c : token) {
  942. switch (c) {
  943. case '\'':
  944. builder.append("\"'\"");
  945. started_single_quote = false;
  946. continue;
  947. default:
  948. builder.append(c);
  949. if (!started_single_quote) {
  950. started_single_quote = true;
  951. builder.append("'");
  952. }
  953. break;
  954. }
  955. }
  956. if (started_single_quote)
  957. builder.append("'");
  958. return builder.build();
  959. }
  960. String Shell::escape_token_for_double_quotes(const String& token)
  961. {
  962. // `foo bar \n $x 'blah "hello` -> `"foo bar \\n $x 'blah \"hello"`
  963. StringBuilder builder;
  964. builder.append('"');
  965. for (auto c : token) {
  966. switch (c) {
  967. case '\"':
  968. builder.append("\\\"");
  969. continue;
  970. case '\\':
  971. builder.append("\\\\");
  972. continue;
  973. default:
  974. builder.append(c);
  975. break;
  976. }
  977. }
  978. builder.append('"');
  979. return builder.build();
  980. }
  981. Shell::SpecialCharacterEscapeMode Shell::special_character_escape_mode(u32 code_point)
  982. {
  983. switch (code_point) {
  984. case '\'':
  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. return SpecialCharacterEscapeMode::Escaped;
  999. case '\n':
  1000. case '\t':
  1001. case '\r':
  1002. return SpecialCharacterEscapeMode::QuotedAsEscape;
  1003. default:
  1004. // FIXME: Should instead use unicode's "graphic" property (categories L, M, N, P, S, Zs)
  1005. if (is_ascii(code_point))
  1006. return is_ascii_printable(code_point) ? SpecialCharacterEscapeMode::Untouched : SpecialCharacterEscapeMode::QuotedAsHex;
  1007. return SpecialCharacterEscapeMode::Untouched;
  1008. }
  1009. }
  1010. String Shell::escape_token(const String& token)
  1011. {
  1012. auto do_escape = [](auto& token) {
  1013. StringBuilder builder;
  1014. for (auto c : token) {
  1015. static_assert(sizeof(c) == sizeof(u32) || sizeof(c) == sizeof(u8));
  1016. switch (special_character_escape_mode(c)) {
  1017. case SpecialCharacterEscapeMode::Untouched:
  1018. if constexpr (sizeof(c) == sizeof(u8))
  1019. builder.append(c);
  1020. else
  1021. builder.append(Utf32View { &c, 1 });
  1022. break;
  1023. case SpecialCharacterEscapeMode::Escaped:
  1024. builder.append('\\');
  1025. builder.append(c);
  1026. break;
  1027. case SpecialCharacterEscapeMode::QuotedAsEscape:
  1028. switch (c) {
  1029. case '\n':
  1030. builder.append(R"("\n")");
  1031. break;
  1032. case '\t':
  1033. builder.append(R"("\t")");
  1034. break;
  1035. case '\r':
  1036. builder.append(R"("\r")");
  1037. break;
  1038. default:
  1039. VERIFY_NOT_REACHED();
  1040. }
  1041. break;
  1042. case SpecialCharacterEscapeMode::QuotedAsHex:
  1043. if (c <= NumericLimits<u8>::max())
  1044. builder.appendff(R"("\x{:0>2x}")", static_cast<u8>(c));
  1045. else
  1046. builder.appendff(R"("\u{:0>8x}")", static_cast<u32>(c));
  1047. break;
  1048. }
  1049. }
  1050. return builder.build();
  1051. };
  1052. Utf8View view { token };
  1053. if (view.validate())
  1054. return do_escape(view);
  1055. return do_escape(token);
  1056. }
  1057. String Shell::unescape_token(const String& token)
  1058. {
  1059. StringBuilder builder;
  1060. enum {
  1061. Free,
  1062. Escaped
  1063. } state { Free };
  1064. for (auto c : token) {
  1065. switch (state) {
  1066. case Escaped:
  1067. builder.append(c);
  1068. state = Free;
  1069. break;
  1070. case Free:
  1071. if (c == '\\')
  1072. state = Escaped;
  1073. else
  1074. builder.append(c);
  1075. break;
  1076. }
  1077. }
  1078. if (state == Escaped)
  1079. builder.append('\\');
  1080. return builder.build();
  1081. }
  1082. String Shell::find_in_path(const StringView& program_name)
  1083. {
  1084. String path = getenv("PATH");
  1085. if (!path.is_empty()) {
  1086. auto directories = path.split(':');
  1087. for (const auto& directory : directories) {
  1088. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1089. while (programs.has_next()) {
  1090. auto program = programs.next_path();
  1091. auto program_path = String::formatted("{}/{}", directory, program);
  1092. if (access(program_path.characters(), X_OK) != 0)
  1093. continue;
  1094. if (program == program_name)
  1095. return program_path;
  1096. }
  1097. }
  1098. }
  1099. return {};
  1100. }
  1101. void Shell::cache_path()
  1102. {
  1103. if (!m_is_interactive)
  1104. return;
  1105. if (!cached_path.is_empty())
  1106. cached_path.clear_with_capacity();
  1107. // Add shell builtins to the cache.
  1108. for (const auto& builtin_name : builtin_names)
  1109. cached_path.append(escape_token(builtin_name));
  1110. // Add functions to the cache.
  1111. for (auto& function : m_functions) {
  1112. auto name = escape_token(function.key);
  1113. if (cached_path.contains_slow(name))
  1114. continue;
  1115. cached_path.append(name);
  1116. }
  1117. // Add aliases to the cache.
  1118. for (const auto& alias : m_aliases) {
  1119. auto name = escape_token(alias.key);
  1120. if (cached_path.contains_slow(name))
  1121. continue;
  1122. cached_path.append(name);
  1123. }
  1124. String path = getenv("PATH");
  1125. if (!path.is_empty()) {
  1126. auto directories = path.split(':');
  1127. for (const auto& directory : directories) {
  1128. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1129. while (programs.has_next()) {
  1130. auto program = programs.next_path();
  1131. auto program_path = String::formatted("{}/{}", directory, program);
  1132. auto escaped_name = escape_token(program);
  1133. if (cached_path.contains_slow(escaped_name))
  1134. continue;
  1135. if (access(program_path.characters(), X_OK) == 0)
  1136. cached_path.append(escaped_name);
  1137. }
  1138. }
  1139. }
  1140. quick_sort(cached_path);
  1141. }
  1142. void Shell::add_entry_to_cache(const String& entry)
  1143. {
  1144. size_t index = 0;
  1145. auto match = binary_search(
  1146. cached_path.span(),
  1147. entry,
  1148. &index,
  1149. [](auto& name, auto& program) { return strcmp(name.characters(), program.characters()); });
  1150. if (match)
  1151. return;
  1152. while (index < cached_path.size() && strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  1153. index++;
  1154. }
  1155. cached_path.insert(index, entry);
  1156. }
  1157. void Shell::remove_entry_from_cache(const String& entry)
  1158. {
  1159. size_t index { 0 };
  1160. auto match = binary_search(
  1161. cached_path.span(),
  1162. entry,
  1163. &index,
  1164. [](const auto& a, const auto& b) { return strcmp(a.characters(), b.characters()); });
  1165. if (match)
  1166. cached_path.remove(index);
  1167. }
  1168. void Shell::highlight(Line::Editor& editor) const
  1169. {
  1170. auto line = editor.line();
  1171. Parser parser(line, m_is_interactive);
  1172. auto ast = parser.parse();
  1173. if (!ast)
  1174. return;
  1175. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  1176. }
  1177. Vector<Line::CompletionSuggestion> Shell::complete()
  1178. {
  1179. auto line = m_editor->line(m_editor->cursor());
  1180. Parser parser(line, m_is_interactive);
  1181. auto ast = parser.parse();
  1182. if (!ast)
  1183. return {};
  1184. return ast->complete_for_editor(*this, line.length());
  1185. }
  1186. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base,
  1187. const String& part, size_t offset, ExecutableOnly executable_only)
  1188. {
  1189. auto token = offset ? part.substring_view(0, offset) : "";
  1190. String path;
  1191. ssize_t last_slash = token.length() - 1;
  1192. while (last_slash >= 0 && token[last_slash] != '/')
  1193. --last_slash;
  1194. StringBuilder path_builder;
  1195. auto init_slash_part = token.substring_view(0, last_slash + 1);
  1196. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  1197. bool allow_direct_children = true;
  1198. // Depending on the base, we will have to prepend cwd.
  1199. if (base.is_empty()) {
  1200. // '' /foo -> absolute
  1201. // '' foo -> relative
  1202. if (!token.starts_with('/'))
  1203. path_builder.append(cwd);
  1204. path_builder.append('/');
  1205. path_builder.append(init_slash_part);
  1206. if (executable_only == ExecutableOnly::Yes && init_slash_part.is_empty())
  1207. allow_direct_children = false;
  1208. } else {
  1209. // /foo * -> absolute
  1210. // foo * -> relative
  1211. if (!base.starts_with('/'))
  1212. path_builder.append(cwd);
  1213. path_builder.append('/');
  1214. path_builder.append(base);
  1215. path_builder.append('/');
  1216. path_builder.append(init_slash_part);
  1217. }
  1218. path = path_builder.build();
  1219. token = last_slash_part;
  1220. // the invariant part of the token is actually just the last segment
  1221. // e. in `cd /foo/bar', 'bar' is the invariant
  1222. // since we are not suggesting anything starting with
  1223. // `/foo/', but rather just `bar...'
  1224. auto token_length = escape_token(token).length();
  1225. if (m_editor)
  1226. m_editor->suggest(token_length, last_slash + 1);
  1227. // only suggest dot-files if path starts with a dot
  1228. Core::DirIterator files(path,
  1229. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1230. Vector<Line::CompletionSuggestion> suggestions;
  1231. while (files.has_next()) {
  1232. auto file = files.next_path();
  1233. if (file.starts_with(token)) {
  1234. struct stat program_status;
  1235. auto file_path = String::formatted("{}/{}", path, file);
  1236. int stat_error = stat(file_path.characters(), &program_status);
  1237. if (!stat_error && (executable_only == ExecutableOnly::No || access(file_path.characters(), X_OK) == 0)) {
  1238. if (S_ISDIR(program_status.st_mode)) {
  1239. suggestions.append({ escape_token(file), "/" });
  1240. } else {
  1241. if (!allow_direct_children && !file.contains("/"))
  1242. continue;
  1243. suggestions.append({ escape_token(file), " " });
  1244. }
  1245. suggestions.last().input_offset = token_length;
  1246. }
  1247. }
  1248. }
  1249. return suggestions;
  1250. }
  1251. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  1252. {
  1253. auto match = binary_search(
  1254. cached_path.span(),
  1255. name,
  1256. nullptr,
  1257. [](auto& name, auto& program) { return strncmp(name.characters(), program.characters(), name.length()); });
  1258. if (!match)
  1259. return complete_path("", name, offset, ExecutableOnly::Yes);
  1260. String completion = *match;
  1261. auto token_length = escape_token(name).length();
  1262. if (m_editor)
  1263. m_editor->suggest(token_length, 0);
  1264. // Now that we have a program name starting with our token, we look at
  1265. // other program names starting with our token and cut off any mismatching
  1266. // characters.
  1267. Vector<Line::CompletionSuggestion> suggestions;
  1268. int index = match - cached_path.data();
  1269. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  1270. suggestions.append({ cached_path[i], " " });
  1271. suggestions.last().input_offset = token_length;
  1272. }
  1273. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  1274. suggestions.append({ cached_path[i], " " });
  1275. suggestions.last().input_offset = token_length;
  1276. }
  1277. suggestions.append({ cached_path[index], " " });
  1278. suggestions.last().input_offset = token_length;
  1279. return suggestions;
  1280. }
  1281. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  1282. {
  1283. Vector<Line::CompletionSuggestion> suggestions;
  1284. auto pattern = offset ? name.substring_view(0, offset) : "";
  1285. if (m_editor)
  1286. m_editor->suggest(offset);
  1287. // Look at local variables.
  1288. for (auto& frame : m_local_frames) {
  1289. for (auto& variable : frame.local_variables) {
  1290. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1291. suggestions.append(variable.key);
  1292. }
  1293. }
  1294. // Look at the environment.
  1295. for (auto i = 0; environ[i]; ++i) {
  1296. auto entry = StringView { environ[i] };
  1297. if (entry.starts_with(pattern)) {
  1298. auto parts = entry.split_view('=');
  1299. if (parts.is_empty() || parts.first().is_empty())
  1300. continue;
  1301. String name = parts.first();
  1302. if (suggestions.contains_slow(name))
  1303. continue;
  1304. suggestions.append(move(name));
  1305. suggestions.last().input_offset = offset;
  1306. }
  1307. }
  1308. return suggestions;
  1309. }
  1310. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  1311. {
  1312. Vector<Line::CompletionSuggestion> suggestions;
  1313. auto pattern = offset ? name.substring_view(0, offset) : "";
  1314. if (m_editor)
  1315. m_editor->suggest(offset);
  1316. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1317. if (di.has_error())
  1318. return suggestions;
  1319. while (di.has_next()) {
  1320. String name = di.next_path();
  1321. if (name.starts_with(pattern)) {
  1322. suggestions.append(name);
  1323. suggestions.last().input_offset = offset;
  1324. }
  1325. }
  1326. return suggestions;
  1327. }
  1328. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  1329. {
  1330. size_t start = 0;
  1331. while (start < option.length() && option[start] == '-' && start < 2)
  1332. ++start;
  1333. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  1334. if (m_editor)
  1335. m_editor->suggest(offset);
  1336. Vector<Line::CompletionSuggestion> suggestions;
  1337. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1338. // FIXME: Figure out how to do this stuff.
  1339. if (has_builtin(program_name)) {
  1340. // Complete builtins.
  1341. if (program_name == "setopt") {
  1342. bool negate = false;
  1343. if (option_pattern.starts_with("no_")) {
  1344. negate = true;
  1345. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  1346. }
  1347. auto maybe_negate = [&](const StringView& view) {
  1348. static StringBuilder builder;
  1349. builder.clear();
  1350. builder.append("--");
  1351. if (negate)
  1352. builder.append("no_");
  1353. builder.append(view);
  1354. return builder.to_string();
  1355. };
  1356. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  1357. if (StringView { #name }.starts_with(option_pattern)) { \
  1358. suggestions.append(maybe_negate(#name)); \
  1359. suggestions.last().input_offset = offset; \
  1360. }
  1361. ENUMERATE_SHELL_OPTIONS();
  1362. #undef __ENUMERATE_SHELL_OPTION
  1363. return suggestions;
  1364. }
  1365. }
  1366. return suggestions;
  1367. }
  1368. Vector<Line::CompletionSuggestion> Shell::complete_immediate_function_name(const String& name, size_t offset)
  1369. {
  1370. Vector<Line::CompletionSuggestion> suggestions;
  1371. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(fn_name) \
  1372. if (auto name_view = StringView { #fn_name }; name_view.starts_with(name)) { \
  1373. suggestions.append({ name_view, " " }); \
  1374. suggestions.last().input_offset = offset; \
  1375. }
  1376. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  1377. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  1378. if (m_editor)
  1379. m_editor->suggest(offset);
  1380. return suggestions;
  1381. }
  1382. void Shell::bring_cursor_to_beginning_of_a_line() const
  1383. {
  1384. struct winsize ws;
  1385. if (m_editor) {
  1386. ws = m_editor->terminal_size();
  1387. } else {
  1388. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1389. // Very annoying assumptions.
  1390. ws.ws_col = 80;
  1391. ws.ws_row = 25;
  1392. }
  1393. }
  1394. // Black with Cyan background.
  1395. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1396. String eol_mark = getenv("PROMPT_EOL_MARK");
  1397. if (eol_mark.is_null())
  1398. eol_mark = default_mark;
  1399. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1400. if (eol_mark_length >= ws.ws_col) {
  1401. eol_mark = default_mark;
  1402. eol_mark_length = 1;
  1403. }
  1404. fputs(eol_mark.characters(), stderr);
  1405. for (auto i = eol_mark_length; i < ws.ws_col; ++i)
  1406. putc(' ', stderr);
  1407. putc('\r', stderr);
  1408. }
  1409. bool Shell::has_history_event(StringView source)
  1410. {
  1411. struct : public AST::NodeVisitor {
  1412. virtual void visit(const AST::HistoryEvent* node)
  1413. {
  1414. has_history_event = true;
  1415. AST::NodeVisitor::visit(node);
  1416. }
  1417. bool has_history_event { false };
  1418. } visitor;
  1419. auto ast = Parser { source, true }.parse();
  1420. if (!ast)
  1421. return false;
  1422. ast->visit(visitor);
  1423. return visitor.has_history_event;
  1424. }
  1425. bool Shell::read_single_line()
  1426. {
  1427. restore_ios();
  1428. bring_cursor_to_beginning_of_a_line();
  1429. auto line_result = m_editor->get_line(prompt());
  1430. if (line_result.is_error()) {
  1431. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1432. // Pretend the user tried to execute builtin_exit()
  1433. run_command("exit");
  1434. return read_single_line();
  1435. } else {
  1436. Core::EventLoop::current().quit(1);
  1437. return false;
  1438. }
  1439. }
  1440. auto& line = line_result.value();
  1441. if (line.is_empty())
  1442. return true;
  1443. run_command(line);
  1444. if (!has_history_event(line))
  1445. m_editor->add_to_history(line);
  1446. return true;
  1447. }
  1448. void Shell::custom_event(Core::CustomEvent& event)
  1449. {
  1450. if (event.custom_type() == ReadLine) {
  1451. if (read_single_line())
  1452. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1453. return;
  1454. }
  1455. }
  1456. void Shell::notify_child_event()
  1457. {
  1458. Vector<u64> disowned_jobs;
  1459. // Workaround the fact that we can't receive *who* exactly changed state.
  1460. // The child might still be alive (and even running) when this signal is dispatched to us
  1461. // so just...repeat until we find a suitable child.
  1462. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1463. // until the next child event we can actually handle.
  1464. bool found_child = false;
  1465. do {
  1466. // Ignore stray SIGCHLD when there are no jobs.
  1467. if (jobs.is_empty())
  1468. return;
  1469. for (auto& it : jobs) {
  1470. auto job_id = it.key;
  1471. auto& job = *it.value;
  1472. int wstatus = 0;
  1473. dbgln_if(SH_DEBUG, "waitpid({} = {}) = ...", job.pid(), job.cmd());
  1474. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1475. dbgln_if(SH_DEBUG, "... = {} - exited: {}, suspended: {}", child_pid, WIFEXITED(wstatus), WIFSTOPPED(wstatus));
  1476. if (child_pid < 0) {
  1477. if (errno == ECHILD) {
  1478. // The child process went away before we could process its death, just assume it exited all ok.
  1479. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1480. child_pid = job.pid();
  1481. } else {
  1482. VERIFY_NOT_REACHED();
  1483. }
  1484. }
  1485. if (child_pid == 0) {
  1486. // If the child existed, but wasn't dead.
  1487. if (job.is_suspended() || job.shell_did_continue()) {
  1488. // The job was suspended, and someone sent it a SIGCONT.
  1489. job.set_is_suspended(false);
  1490. if (job.shell_did_continue())
  1491. job.set_shell_did_continue(false);
  1492. found_child = true;
  1493. }
  1494. continue;
  1495. }
  1496. if (child_pid == job.pid()) {
  1497. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1498. job.set_signalled(WTERMSIG(wstatus));
  1499. } else if (WIFEXITED(wstatus)) {
  1500. job.set_has_exit(WEXITSTATUS(wstatus));
  1501. } else if (WIFSTOPPED(wstatus)) {
  1502. job.unblock();
  1503. job.set_is_suspended(true);
  1504. }
  1505. found_child = true;
  1506. }
  1507. if (job.should_be_disowned())
  1508. disowned_jobs.append(job_id);
  1509. }
  1510. for (auto job_id : disowned_jobs) {
  1511. jobs.remove(job_id);
  1512. }
  1513. } while (!found_child);
  1514. }
  1515. Shell::Shell()
  1516. : m_default_constructed(true)
  1517. {
  1518. push_frame("main").leak_frame();
  1519. int rc = gethostname(hostname, Shell::HostNameSize);
  1520. if (rc < 0)
  1521. perror("gethostname");
  1522. {
  1523. auto* pw = getpwuid(getuid());
  1524. if (pw) {
  1525. username = pw->pw_name;
  1526. home = pw->pw_dir;
  1527. setenv("HOME", pw->pw_dir, 1);
  1528. }
  1529. endpwent();
  1530. }
  1531. // For simplicity, start at the user's home directory.
  1532. this->cwd = home;
  1533. setenv("PWD", home.characters(), 1);
  1534. // Add the default PATH vars.
  1535. {
  1536. StringBuilder path;
  1537. path.append(getenv("PATH"));
  1538. if (path.length())
  1539. path.append(":");
  1540. path.append("/bin:/usr/bin:/usr/local/bin");
  1541. setenv("PATH", path.to_string().characters(), true);
  1542. }
  1543. cache_path();
  1544. }
  1545. Shell::Shell(Line::Editor& editor, bool attempt_interactive)
  1546. : m_editor(editor)
  1547. {
  1548. uid = getuid();
  1549. tcsetpgrp(0, getpgrp());
  1550. m_pid = getpid();
  1551. push_frame("main").leak_frame();
  1552. int rc = gethostname(hostname, Shell::HostNameSize);
  1553. if (rc < 0)
  1554. perror("gethostname");
  1555. auto istty = isatty(STDIN_FILENO);
  1556. m_is_interactive = attempt_interactive && istty;
  1557. if (istty) {
  1558. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1559. if (rc < 0)
  1560. perror("ttyname_r");
  1561. } else {
  1562. ttyname[0] = 0;
  1563. }
  1564. {
  1565. auto* cwd = getcwd(nullptr, 0);
  1566. this->cwd = cwd;
  1567. setenv("PWD", cwd, 1);
  1568. free(cwd);
  1569. }
  1570. {
  1571. auto* pw = getpwuid(getuid());
  1572. if (pw) {
  1573. username = pw->pw_name;
  1574. home = pw->pw_dir;
  1575. setenv("HOME", pw->pw_dir, 1);
  1576. }
  1577. endpwent();
  1578. }
  1579. directory_stack.append(cwd);
  1580. if (m_is_interactive) {
  1581. m_editor->load_history(get_history_path());
  1582. cache_path();
  1583. }
  1584. m_editor->register_key_input_callback('\n', [](Line::Editor& editor) {
  1585. auto ast = Parser(editor.line()).parse();
  1586. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1587. return true;
  1588. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1589. });
  1590. start_timer(3000);
  1591. }
  1592. Shell::~Shell()
  1593. {
  1594. if (m_default_constructed)
  1595. return;
  1596. stop_all_jobs();
  1597. if (!m_is_interactive)
  1598. return;
  1599. m_editor->save_history(get_history_path());
  1600. }
  1601. void Shell::stop_all_jobs()
  1602. {
  1603. if (!jobs.is_empty()) {
  1604. if (m_is_interactive && !m_is_subshell)
  1605. printf("Killing active jobs\n");
  1606. for (auto& entry : jobs) {
  1607. if (entry.value->is_suspended()) {
  1608. dbgln_if(SH_DEBUG, "Job {} is suspended", entry.value->pid());
  1609. kill_job(entry.value, SIGCONT);
  1610. }
  1611. kill_job(entry.value, SIGHUP);
  1612. }
  1613. usleep(10000); // Wait for a bit before killing the job
  1614. for (auto& entry : jobs) {
  1615. dbgln_if(SH_DEBUG, "Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1616. kill_job(entry.value, SIGKILL);
  1617. }
  1618. jobs.clear();
  1619. }
  1620. }
  1621. u64 Shell::find_last_job_id() const
  1622. {
  1623. u64 job_id = 0;
  1624. for (auto& entry : jobs) {
  1625. if (entry.value->job_id() > job_id)
  1626. job_id = entry.value->job_id();
  1627. }
  1628. return job_id;
  1629. }
  1630. const Job* Shell::find_job(u64 id, bool is_pid)
  1631. {
  1632. for (auto& entry : jobs) {
  1633. if (is_pid) {
  1634. if (entry.value->pid() == static_cast<int>(id))
  1635. return entry.value;
  1636. } else {
  1637. if (entry.value->job_id() == id)
  1638. return entry.value;
  1639. }
  1640. }
  1641. return nullptr;
  1642. }
  1643. void Shell::kill_job(const Job* job, int sig)
  1644. {
  1645. if (!job)
  1646. return;
  1647. if (killpg(job->pgid(), sig) < 0) {
  1648. if (kill(job->pid(), sig) < 0) {
  1649. if (errno != ESRCH)
  1650. perror("kill");
  1651. }
  1652. }
  1653. }
  1654. void Shell::save_to(JsonObject& object)
  1655. {
  1656. Core::Object::save_to(object);
  1657. object.set("working_directory", cwd);
  1658. object.set("username", username);
  1659. object.set("user_home_path", home);
  1660. object.set("user_id", uid);
  1661. object.set("directory_stack_size", directory_stack.size());
  1662. object.set("cd_history_size", cd_history.size());
  1663. // Jobs.
  1664. JsonArray job_objects;
  1665. for (auto& job_entry : jobs) {
  1666. JsonObject job_object;
  1667. job_object.set("pid", job_entry.value->pid());
  1668. job_object.set("pgid", job_entry.value->pgid());
  1669. job_object.set("running_time", job_entry.value->timer().elapsed());
  1670. job_object.set("command", job_entry.value->cmd());
  1671. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1672. job_objects.append(move(job_object));
  1673. }
  1674. object.set("jobs", move(job_objects));
  1675. }
  1676. void Shell::possibly_print_error() const
  1677. {
  1678. switch (m_error) {
  1679. case ShellError::EvaluatedSyntaxError:
  1680. warnln("Shell Syntax Error: {}", m_error_description);
  1681. break;
  1682. case ShellError::InvalidSliceContentsError:
  1683. case ShellError::InvalidGlobError:
  1684. case ShellError::NonExhaustiveMatchRules:
  1685. warnln("Shell: {}", m_error_description);
  1686. break;
  1687. case ShellError::OpenFailure:
  1688. warnln("Shell: Open failed for {}", m_error_description);
  1689. break;
  1690. case ShellError::InternalControlFlowBreak:
  1691. case ShellError::InternalControlFlowContinue:
  1692. return;
  1693. case ShellError::None:
  1694. return;
  1695. }
  1696. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  1697. auto& source_position = m_source_position.value();
  1698. auto do_line = [&](auto line, auto& current_line) {
  1699. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  1700. warnln("{:>3}| {}", line, current_line);
  1701. if (is_in_range) {
  1702. warn("\x1b[31m");
  1703. size_t length_written_so_far = 0;
  1704. if (line == (i64)source_position.position->start_line.line_number) {
  1705. warn("{:~>{}}", "", 5 + source_position.position->start_line.line_column);
  1706. length_written_so_far += source_position.position->start_line.line_column;
  1707. } else {
  1708. warn("{:~>{}}", "", 5);
  1709. }
  1710. if (line == (i64)source_position.position->end_line.line_number) {
  1711. warn("{:^>{}}", "", source_position.position->end_line.line_column - length_written_so_far);
  1712. length_written_so_far += source_position.position->start_line.line_column;
  1713. } else {
  1714. warn("{:^>{}}", "", current_line.length() - length_written_so_far);
  1715. }
  1716. warnln("\x1b[0m");
  1717. }
  1718. };
  1719. int line = -1;
  1720. String current_line;
  1721. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  1722. if (!source_position.source_file.is_null()) {
  1723. auto file = Core::File::open(source_position.source_file, Core::OpenMode::ReadOnly);
  1724. if (file.is_error()) {
  1725. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file.error(), source_position.source_file);
  1726. return;
  1727. }
  1728. while (line < line_to_skip_to) {
  1729. if (file.value()->eof())
  1730. return;
  1731. current_line = file.value()->read_line();
  1732. ++line;
  1733. }
  1734. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1735. do_line(line, current_line);
  1736. if (file.value()->eof())
  1737. current_line = "";
  1738. else
  1739. current_line = file.value()->read_line();
  1740. }
  1741. } else if (!source_position.literal_source_text.is_empty()) {
  1742. GenericLexer lexer { source_position.literal_source_text };
  1743. while (line < line_to_skip_to) {
  1744. if (lexer.is_eof())
  1745. return;
  1746. current_line = lexer.consume_line();
  1747. ++line;
  1748. }
  1749. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1750. do_line(line, current_line);
  1751. if (lexer.is_eof())
  1752. current_line = "";
  1753. else
  1754. current_line = lexer.consume_line();
  1755. }
  1756. }
  1757. }
  1758. warnln();
  1759. }
  1760. Optional<int> Shell::resolve_job_spec(const String& str)
  1761. {
  1762. if (!str.starts_with('%'))
  1763. return {};
  1764. // %number -> job id <number>
  1765. if (auto number = str.substring_view(1).to_uint(); number.has_value())
  1766. return number.value();
  1767. // '%?str' -> iterate jobs and pick one with `str' in its command
  1768. // Note: must be quoted, since '?' will turn it into a glob - pretty ugly...
  1769. GenericLexer lexer { str.substring_view(1) };
  1770. if (!lexer.consume_specific('?'))
  1771. return {};
  1772. auto search_term = lexer.remaining();
  1773. for (auto& it : jobs) {
  1774. if (it.value->cmd().contains(search_term))
  1775. return it.key;
  1776. }
  1777. return {};
  1778. }
  1779. void Shell::timer_event(Core::TimerEvent& event)
  1780. {
  1781. event.accept();
  1782. if (m_is_subshell)
  1783. return;
  1784. StringView option = getenv("HISTORY_AUTOSAVE_TIME_MS");
  1785. auto time = option.to_uint();
  1786. if (!time.has_value() || time.value() == 0) {
  1787. m_history_autosave_time.clear();
  1788. stop_timer();
  1789. start_timer(3000);
  1790. return;
  1791. }
  1792. if (m_history_autosave_time != time) {
  1793. m_history_autosave_time = time.value();
  1794. stop_timer();
  1795. start_timer(m_history_autosave_time.value());
  1796. }
  1797. if (!m_history_autosave_time.has_value())
  1798. return;
  1799. if (m_editor && m_editor->is_history_dirty())
  1800. m_editor->save_history(get_history_path());
  1801. }
  1802. void FileDescriptionCollector::collect()
  1803. {
  1804. for (auto fd : m_fds)
  1805. close(fd);
  1806. m_fds.clear();
  1807. }
  1808. FileDescriptionCollector::~FileDescriptionCollector()
  1809. {
  1810. collect();
  1811. }
  1812. void FileDescriptionCollector::add(int fd)
  1813. {
  1814. m_fds.append(fd);
  1815. }
  1816. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  1817. {
  1818. for (auto& rewiring : intended_rewirings) {
  1819. int new_fd = dup(rewiring.new_fd);
  1820. if (new_fd < 0) {
  1821. if (errno != EBADF)
  1822. perror("dup");
  1823. // The fd that will be overwritten isn't open right now,
  1824. // it will be cleaned up by the exec()-side collector
  1825. // and we have nothing to do here, so just ignore this error.
  1826. continue;
  1827. }
  1828. auto flags = fcntl(new_fd, F_GETFD);
  1829. auto rc = fcntl(new_fd, F_SETFD, flags | FD_CLOEXEC);
  1830. VERIFY(rc == 0);
  1831. m_saves.append({ rewiring.new_fd, new_fd });
  1832. m_collector.add(new_fd);
  1833. }
  1834. }
  1835. SavedFileDescriptors::~SavedFileDescriptors()
  1836. {
  1837. for (auto& save : m_saves) {
  1838. if (dup2(save.saved, save.original) < 0) {
  1839. perror("dup2(~SavedFileDescriptors)");
  1840. continue;
  1841. }
  1842. }
  1843. }
  1844. }