Shell.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177
  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. if (m_editor)
  1198. m_editor->suggest(token_length, last_slash + 1);
  1199. // only suggest dot-files if path starts with a dot
  1200. Core::DirIterator files(path,
  1201. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1202. Vector<Line::CompletionSuggestion> suggestions;
  1203. while (files.has_next()) {
  1204. auto file = files.next_path();
  1205. if (file.starts_with(token)) {
  1206. struct stat program_status;
  1207. auto file_path = String::formatted("{}/{}", path, file);
  1208. int stat_error = stat(file_path.characters(), &program_status);
  1209. if (!stat_error && (executable_only == ExecutableOnly::No || access(file_path.characters(), X_OK) == 0)) {
  1210. if (S_ISDIR(program_status.st_mode)) {
  1211. suggestions.append({ escape_token(file), "/" });
  1212. } else {
  1213. if (!allow_direct_children && !file.contains("/"))
  1214. continue;
  1215. suggestions.append({ escape_token(file), " " });
  1216. }
  1217. suggestions.last().input_offset = token_length;
  1218. }
  1219. }
  1220. }
  1221. return suggestions;
  1222. }
  1223. Vector<Line::CompletionSuggestion> Shell::complete_program_name(StringView name, size_t offset)
  1224. {
  1225. auto match = binary_search(
  1226. cached_path.span(),
  1227. name,
  1228. nullptr,
  1229. [](auto& name, auto& program) {
  1230. return strncmp(
  1231. name.characters_without_null_termination(),
  1232. program.characters(),
  1233. name.length());
  1234. });
  1235. if (!match)
  1236. return complete_path("", name, offset, ExecutableOnly::Yes);
  1237. String completion = *match;
  1238. auto token_length = escape_token(name).length();
  1239. if (m_editor)
  1240. m_editor->suggest(token_length, 0);
  1241. // Now that we have a program name starting with our token, we look at
  1242. // other program names starting with our token and cut off any mismatching
  1243. // characters.
  1244. Vector<Line::CompletionSuggestion> suggestions;
  1245. int index = match - cached_path.data();
  1246. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  1247. suggestions.append({ cached_path[i], " " });
  1248. suggestions.last().input_offset = token_length;
  1249. }
  1250. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  1251. suggestions.append({ cached_path[i], " " });
  1252. suggestions.last().input_offset = token_length;
  1253. }
  1254. suggestions.append({ cached_path[index], " " });
  1255. suggestions.last().input_offset = token_length;
  1256. return suggestions;
  1257. }
  1258. Vector<Line::CompletionSuggestion> Shell::complete_variable(StringView name, size_t offset)
  1259. {
  1260. Vector<Line::CompletionSuggestion> suggestions;
  1261. auto pattern = offset ? name.substring_view(0, offset) : "";
  1262. if (m_editor)
  1263. m_editor->suggest(offset);
  1264. // Look at local variables.
  1265. for (auto& frame : m_local_frames) {
  1266. for (auto& variable : frame.local_variables) {
  1267. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1268. suggestions.append(variable.key);
  1269. }
  1270. }
  1271. // Look at the environment.
  1272. for (auto i = 0; environ[i]; ++i) {
  1273. auto entry = StringView { environ[i] };
  1274. if (entry.starts_with(pattern)) {
  1275. auto parts = entry.split_view('=');
  1276. if (parts.is_empty() || parts.first().is_empty())
  1277. continue;
  1278. String name = parts.first();
  1279. if (suggestions.contains_slow(name))
  1280. continue;
  1281. suggestions.append(move(name));
  1282. suggestions.last().input_offset = offset;
  1283. }
  1284. }
  1285. return suggestions;
  1286. }
  1287. Vector<Line::CompletionSuggestion> Shell::complete_user(StringView name, size_t offset)
  1288. {
  1289. Vector<Line::CompletionSuggestion> suggestions;
  1290. auto pattern = offset ? name.substring_view(0, offset) : "";
  1291. if (m_editor)
  1292. m_editor->suggest(offset);
  1293. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1294. if (di.has_error())
  1295. return suggestions;
  1296. while (di.has_next()) {
  1297. String name = di.next_path();
  1298. if (name.starts_with(pattern)) {
  1299. suggestions.append(name);
  1300. suggestions.last().input_offset = offset;
  1301. }
  1302. }
  1303. return suggestions;
  1304. }
  1305. Vector<Line::CompletionSuggestion> Shell::complete_option(StringView program_name, StringView option, size_t offset)
  1306. {
  1307. size_t start = 0;
  1308. while (start < option.length() && option[start] == '-' && start < 2)
  1309. ++start;
  1310. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  1311. if (m_editor)
  1312. m_editor->suggest(offset);
  1313. Vector<Line::CompletionSuggestion> suggestions;
  1314. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1315. // FIXME: Figure out how to do this stuff.
  1316. if (has_builtin(program_name)) {
  1317. // Complete builtins.
  1318. if (program_name == "setopt") {
  1319. bool negate = false;
  1320. if (option_pattern.starts_with("no_")) {
  1321. negate = true;
  1322. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  1323. }
  1324. auto maybe_negate = [&](StringView view) {
  1325. static StringBuilder builder;
  1326. builder.clear();
  1327. builder.append("--");
  1328. if (negate)
  1329. builder.append("no_");
  1330. builder.append(view);
  1331. return builder.to_string();
  1332. };
  1333. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  1334. if (#name##sv.starts_with(option_pattern)) { \
  1335. suggestions.append(maybe_negate(#name)); \
  1336. suggestions.last().input_offset = offset; \
  1337. }
  1338. ENUMERATE_SHELL_OPTIONS();
  1339. #undef __ENUMERATE_SHELL_OPTION
  1340. return suggestions;
  1341. }
  1342. }
  1343. return suggestions;
  1344. }
  1345. Vector<Line::CompletionSuggestion> Shell::complete_immediate_function_name(StringView name, size_t offset)
  1346. {
  1347. Vector<Line::CompletionSuggestion> suggestions;
  1348. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(fn_name) \
  1349. if (auto name_view = #fn_name##sv; name_view.starts_with(name)) { \
  1350. suggestions.append({ name_view, " " }); \
  1351. suggestions.last().input_offset = offset; \
  1352. }
  1353. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  1354. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  1355. if (m_editor)
  1356. m_editor->suggest(offset);
  1357. return suggestions;
  1358. }
  1359. void Shell::bring_cursor_to_beginning_of_a_line() const
  1360. {
  1361. struct winsize ws;
  1362. if (m_editor) {
  1363. ws = m_editor->terminal_size();
  1364. } else {
  1365. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1366. // Very annoying assumptions.
  1367. ws.ws_col = 80;
  1368. ws.ws_row = 25;
  1369. }
  1370. }
  1371. // Black with Cyan background.
  1372. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1373. String eol_mark = getenv("PROMPT_EOL_MARK");
  1374. if (eol_mark.is_null())
  1375. eol_mark = default_mark;
  1376. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1377. if (eol_mark_length >= ws.ws_col) {
  1378. eol_mark = default_mark;
  1379. eol_mark_length = 1;
  1380. }
  1381. fputs(eol_mark.characters(), stderr);
  1382. // We write a line's worth of whitespace to the terminal. This way, we ensure that
  1383. // the prompt ends up on a new line even if there is dangling output on the current line.
  1384. size_t fill_count = ws.ws_col - eol_mark_length;
  1385. auto fill_buffer = String::repeated(' ', fill_count);
  1386. fwrite(fill_buffer.characters(), 1, fill_count, stderr);
  1387. putc('\r', stderr);
  1388. }
  1389. bool Shell::has_history_event(StringView source)
  1390. {
  1391. struct : public AST::NodeVisitor {
  1392. virtual void visit(const AST::HistoryEvent* node) override
  1393. {
  1394. has_history_event = true;
  1395. AST::NodeVisitor::visit(node);
  1396. }
  1397. bool has_history_event { false };
  1398. } visitor;
  1399. auto ast = Parser { source, true }.parse();
  1400. if (!ast)
  1401. return false;
  1402. ast->visit(visitor);
  1403. return visitor.has_history_event;
  1404. }
  1405. bool Shell::read_single_line()
  1406. {
  1407. while (true) {
  1408. restore_ios();
  1409. bring_cursor_to_beginning_of_a_line();
  1410. auto line_result = m_editor->get_line(prompt());
  1411. if (line_result.is_error()) {
  1412. auto is_eof = line_result.error() == Line::Editor::Error::Eof;
  1413. auto is_empty = line_result.error() == Line::Editor::Error::Empty;
  1414. if (is_eof || is_empty) {
  1415. // Pretend the user tried to execute builtin_exit()
  1416. auto exit_code = run_command("exit");
  1417. if (exit_code != 0) {
  1418. // If we didn't end up actually calling exit(), and the command didn't succeed, just pretend it's all okay
  1419. // unless we can't, then just quit anyway.
  1420. if (!is_empty)
  1421. continue;
  1422. }
  1423. }
  1424. Core::EventLoop::current().quit(1);
  1425. return false;
  1426. }
  1427. auto& line = line_result.value();
  1428. if (line.is_empty())
  1429. return true;
  1430. run_command(line);
  1431. if (!has_history_event(line))
  1432. m_editor->add_to_history(line);
  1433. return true;
  1434. }
  1435. }
  1436. void Shell::custom_event(Core::CustomEvent& event)
  1437. {
  1438. if (event.custom_type() == ReadLine) {
  1439. if (read_single_line())
  1440. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1441. return;
  1442. }
  1443. }
  1444. void Shell::notify_child_event()
  1445. {
  1446. Vector<u64> disowned_jobs;
  1447. // Workaround the fact that we can't receive *who* exactly changed state.
  1448. // The child might still be alive (and even running) when this signal is dispatched to us
  1449. // so just...repeat until we find a suitable child.
  1450. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1451. // until the next child event we can actually handle.
  1452. bool found_child = false;
  1453. do {
  1454. // Ignore stray SIGCHLD when there are no jobs.
  1455. if (jobs.is_empty())
  1456. return;
  1457. for (auto& it : jobs) {
  1458. auto job_id = it.key;
  1459. auto& job = *it.value;
  1460. int wstatus = 0;
  1461. dbgln_if(SH_DEBUG, "waitpid({} = {}) = ...", job.pid(), job.cmd());
  1462. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1463. dbgln_if(SH_DEBUG, "... = {} - exited: {}, suspended: {}", child_pid, WIFEXITED(wstatus), WIFSTOPPED(wstatus));
  1464. if (child_pid < 0) {
  1465. if (errno == ECHILD) {
  1466. // The child process went away before we could process its death, just assume it exited all ok.
  1467. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1468. child_pid = job.pid();
  1469. } else {
  1470. VERIFY_NOT_REACHED();
  1471. }
  1472. }
  1473. if (child_pid == 0) {
  1474. // If the child existed, but wasn't dead.
  1475. if (job.is_suspended() || job.shell_did_continue()) {
  1476. // The job was suspended, and someone sent it a SIGCONT.
  1477. job.set_is_suspended(false);
  1478. if (job.shell_did_continue())
  1479. job.set_shell_did_continue(false);
  1480. found_child = true;
  1481. }
  1482. continue;
  1483. }
  1484. if (child_pid == job.pid()) {
  1485. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1486. auto signal = WTERMSIG(wstatus);
  1487. job.set_signalled(signal);
  1488. if (signal == SIGINT)
  1489. raise_error(ShellError::InternalControlFlowInterrupted, "Interrupted"sv, job.command().position);
  1490. else if (signal == SIGKILL)
  1491. raise_error(ShellError::InternalControlFlowKilled, "Interrupted"sv, job.command().position);
  1492. } else if (WIFEXITED(wstatus)) {
  1493. job.set_has_exit(WEXITSTATUS(wstatus));
  1494. } else if (WIFSTOPPED(wstatus)) {
  1495. job.unblock();
  1496. job.set_is_suspended(true);
  1497. }
  1498. found_child = true;
  1499. }
  1500. if (job.should_be_disowned())
  1501. disowned_jobs.append(job_id);
  1502. }
  1503. for (auto job_id : disowned_jobs) {
  1504. jobs.remove(job_id);
  1505. }
  1506. } while (!found_child);
  1507. }
  1508. Shell::Shell()
  1509. : m_default_constructed(true)
  1510. {
  1511. push_frame("main").leak_frame();
  1512. int rc = gethostname(hostname, Shell::HostNameSize);
  1513. if (rc < 0)
  1514. perror("gethostname");
  1515. {
  1516. auto* pw = getpwuid(getuid());
  1517. if (pw) {
  1518. username = pw->pw_name;
  1519. home = pw->pw_dir;
  1520. setenv("HOME", pw->pw_dir, 1);
  1521. }
  1522. endpwent();
  1523. }
  1524. // For simplicity, start at the user's home directory.
  1525. this->cwd = home;
  1526. setenv("PWD", home.characters(), 1);
  1527. // Add the default PATH vars.
  1528. {
  1529. StringBuilder path;
  1530. path.append(getenv("PATH"));
  1531. if (path.length())
  1532. path.append(":");
  1533. path.append("/usr/local/bin:/usr/bin:/bin");
  1534. setenv("PATH", path.to_string().characters(), true);
  1535. }
  1536. cache_path();
  1537. }
  1538. Shell::Shell(Line::Editor& editor, bool attempt_interactive)
  1539. : m_editor(editor)
  1540. {
  1541. uid = getuid();
  1542. tcsetpgrp(0, getpgrp());
  1543. m_pid = getpid();
  1544. push_frame("main").leak_frame();
  1545. int rc = gethostname(hostname, Shell::HostNameSize);
  1546. if (rc < 0)
  1547. perror("gethostname");
  1548. auto istty = isatty(STDIN_FILENO);
  1549. m_is_interactive = attempt_interactive && istty;
  1550. if (istty) {
  1551. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1552. if (rc < 0)
  1553. perror("ttyname_r");
  1554. } else {
  1555. ttyname[0] = 0;
  1556. }
  1557. {
  1558. auto* cwd = getcwd(nullptr, 0);
  1559. this->cwd = cwd;
  1560. setenv("PWD", cwd, 1);
  1561. free(cwd);
  1562. }
  1563. {
  1564. auto* pw = getpwuid(getuid());
  1565. if (pw) {
  1566. username = pw->pw_name;
  1567. home = pw->pw_dir;
  1568. setenv("HOME", pw->pw_dir, 1);
  1569. }
  1570. endpwent();
  1571. }
  1572. directory_stack.append(cwd);
  1573. if (m_is_interactive) {
  1574. m_editor->load_history(get_history_path());
  1575. cache_path();
  1576. }
  1577. m_editor->register_key_input_callback('\n', [](Line::Editor& editor) {
  1578. auto ast = Parser(editor.line()).parse();
  1579. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1580. return true;
  1581. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1582. });
  1583. start_timer(3000);
  1584. }
  1585. Shell::~Shell()
  1586. {
  1587. if (m_default_constructed)
  1588. return;
  1589. stop_all_jobs();
  1590. if (!m_is_interactive)
  1591. return;
  1592. m_editor->save_history(get_history_path());
  1593. }
  1594. void Shell::stop_all_jobs()
  1595. {
  1596. if (!jobs.is_empty()) {
  1597. if (m_is_interactive && !m_is_subshell)
  1598. printf("Killing active jobs\n");
  1599. for (auto& entry : jobs) {
  1600. if (entry.value->is_suspended()) {
  1601. dbgln_if(SH_DEBUG, "Job {} is suspended", entry.value->pid());
  1602. kill_job(entry.value, SIGCONT);
  1603. }
  1604. kill_job(entry.value, SIGHUP);
  1605. }
  1606. usleep(10000); // Wait for a bit before killing the job
  1607. for (auto& entry : jobs) {
  1608. dbgln_if(SH_DEBUG, "Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1609. kill_job(entry.value, SIGKILL);
  1610. }
  1611. jobs.clear();
  1612. }
  1613. }
  1614. u64 Shell::find_last_job_id() const
  1615. {
  1616. u64 job_id = 0;
  1617. for (auto& entry : jobs) {
  1618. if (entry.value->job_id() > job_id)
  1619. job_id = entry.value->job_id();
  1620. }
  1621. return job_id;
  1622. }
  1623. const Job* Shell::find_job(u64 id, bool is_pid)
  1624. {
  1625. for (auto& entry : jobs) {
  1626. if (is_pid) {
  1627. if (entry.value->pid() == static_cast<int>(id))
  1628. return entry.value;
  1629. } else {
  1630. if (entry.value->job_id() == id)
  1631. return entry.value;
  1632. }
  1633. }
  1634. return nullptr;
  1635. }
  1636. void Shell::kill_job(const Job* job, int sig)
  1637. {
  1638. if (!job)
  1639. return;
  1640. if (killpg(job->pgid(), sig) < 0) {
  1641. if (kill(job->pid(), sig) < 0) {
  1642. if (errno != ESRCH)
  1643. perror("kill");
  1644. }
  1645. }
  1646. }
  1647. void Shell::save_to(JsonObject& object)
  1648. {
  1649. Core::Object::save_to(object);
  1650. object.set("working_directory", cwd);
  1651. object.set("username", username);
  1652. object.set("user_home_path", home);
  1653. object.set("user_id", uid);
  1654. object.set("directory_stack_size", directory_stack.size());
  1655. object.set("cd_history_size", cd_history.size());
  1656. // Jobs.
  1657. JsonArray job_objects;
  1658. for (auto& job_entry : jobs) {
  1659. JsonObject job_object;
  1660. job_object.set("pid", job_entry.value->pid());
  1661. job_object.set("pgid", job_entry.value->pgid());
  1662. job_object.set("running_time", job_entry.value->timer().elapsed());
  1663. job_object.set("command", job_entry.value->cmd());
  1664. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1665. job_objects.append(move(job_object));
  1666. }
  1667. object.set("jobs", move(job_objects));
  1668. }
  1669. void Shell::possibly_print_error() const
  1670. {
  1671. switch (m_error) {
  1672. case ShellError::EvaluatedSyntaxError:
  1673. warnln("Shell Syntax Error: {}", m_error_description);
  1674. break;
  1675. case ShellError::InvalidSliceContentsError:
  1676. case ShellError::InvalidGlobError:
  1677. case ShellError::NonExhaustiveMatchRules:
  1678. warnln("Shell: {}", m_error_description);
  1679. break;
  1680. case ShellError::OpenFailure:
  1681. warnln("Shell: Open failed for {}", m_error_description);
  1682. break;
  1683. case ShellError::OutOfMemory:
  1684. warnln("Shell: Hit an OOM situation");
  1685. break;
  1686. case ShellError::LaunchError:
  1687. warnln("Shell: {}", m_error_description);
  1688. break;
  1689. case ShellError::InternalControlFlowBreak:
  1690. case ShellError::InternalControlFlowContinue:
  1691. case ShellError::InternalControlFlowInterrupted:
  1692. case ShellError::InternalControlFlowKilled:
  1693. return;
  1694. case ShellError::None:
  1695. return;
  1696. }
  1697. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  1698. auto& source_position = m_source_position.value();
  1699. auto do_line = [&](auto line, auto& current_line) {
  1700. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  1701. warnln("{:>3}| {}", line, current_line);
  1702. if (is_in_range) {
  1703. warn("\x1b[31m");
  1704. size_t length_written_so_far = 0;
  1705. if (line == (i64)source_position.position->start_line.line_number) {
  1706. warn("{:~>{}}", "", 5 + source_position.position->start_line.line_column);
  1707. length_written_so_far += source_position.position->start_line.line_column;
  1708. } else {
  1709. warn("{:~>{}}", "", 5);
  1710. }
  1711. if (line == (i64)source_position.position->end_line.line_number) {
  1712. warn("{:^>{}}", "", source_position.position->end_line.line_column - length_written_so_far);
  1713. length_written_so_far += source_position.position->start_line.line_column;
  1714. } else {
  1715. warn("{:^>{}}", "", current_line.length() - length_written_so_far);
  1716. }
  1717. warnln("\x1b[0m");
  1718. }
  1719. };
  1720. int line = -1;
  1721. String current_line;
  1722. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  1723. if (!source_position.source_file.is_null()) {
  1724. auto file = Core::File::open(source_position.source_file, Core::OpenMode::ReadOnly);
  1725. if (file.is_error()) {
  1726. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file.error(), source_position.source_file);
  1727. return;
  1728. }
  1729. while (line < line_to_skip_to) {
  1730. if (file.value()->eof())
  1731. return;
  1732. current_line = file.value()->read_line();
  1733. ++line;
  1734. }
  1735. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1736. do_line(line, current_line);
  1737. if (file.value()->eof())
  1738. current_line = "";
  1739. else
  1740. current_line = file.value()->read_line();
  1741. }
  1742. } else if (!source_position.literal_source_text.is_empty()) {
  1743. GenericLexer lexer { source_position.literal_source_text };
  1744. while (line < line_to_skip_to) {
  1745. if (lexer.is_eof())
  1746. return;
  1747. current_line = lexer.consume_line();
  1748. ++line;
  1749. }
  1750. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1751. do_line(line, current_line);
  1752. if (lexer.is_eof())
  1753. current_line = "";
  1754. else
  1755. current_line = lexer.consume_line();
  1756. }
  1757. }
  1758. }
  1759. warnln();
  1760. }
  1761. Optional<int> Shell::resolve_job_spec(StringView str)
  1762. {
  1763. if (!str.starts_with('%'))
  1764. return {};
  1765. // %number -> job id <number>
  1766. if (auto number = str.substring_view(1).to_uint(); number.has_value())
  1767. return number.value();
  1768. // '%?str' -> iterate jobs and pick one with `str' in its command
  1769. // Note: must be quoted, since '?' will turn it into a glob - pretty ugly...
  1770. GenericLexer lexer { str.substring_view(1) };
  1771. if (!lexer.consume_specific('?'))
  1772. return {};
  1773. auto search_term = lexer.remaining();
  1774. for (auto& it : jobs) {
  1775. if (it.value->cmd().contains(search_term))
  1776. return it.key;
  1777. }
  1778. return {};
  1779. }
  1780. void Shell::timer_event(Core::TimerEvent& event)
  1781. {
  1782. event.accept();
  1783. if (m_is_subshell)
  1784. return;
  1785. StringView option = getenv("HISTORY_AUTOSAVE_TIME_MS");
  1786. auto time = option.to_uint();
  1787. if (!time.has_value() || time.value() == 0) {
  1788. m_history_autosave_time.clear();
  1789. stop_timer();
  1790. start_timer(3000);
  1791. return;
  1792. }
  1793. if (m_history_autosave_time != time) {
  1794. m_history_autosave_time = time.value();
  1795. stop_timer();
  1796. start_timer(m_history_autosave_time.value());
  1797. }
  1798. if (!m_history_autosave_time.has_value())
  1799. return;
  1800. if (m_editor && m_editor->is_history_dirty())
  1801. m_editor->save_history(get_history_path());
  1802. }
  1803. void FileDescriptionCollector::collect()
  1804. {
  1805. for (auto fd : m_fds)
  1806. close(fd);
  1807. m_fds.clear();
  1808. }
  1809. FileDescriptionCollector::~FileDescriptionCollector()
  1810. {
  1811. collect();
  1812. }
  1813. void FileDescriptionCollector::add(int fd)
  1814. {
  1815. m_fds.append(fd);
  1816. }
  1817. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  1818. {
  1819. for (auto& rewiring : intended_rewirings) {
  1820. int new_fd = dup(rewiring.new_fd);
  1821. if (new_fd < 0) {
  1822. if (errno != EBADF)
  1823. perror("dup");
  1824. // The fd that will be overwritten isn't open right now,
  1825. // it will be cleaned up by the exec()-side collector
  1826. // and we have nothing to do here, so just ignore this error.
  1827. continue;
  1828. }
  1829. auto flags = fcntl(new_fd, F_GETFD);
  1830. auto rc = fcntl(new_fd, F_SETFD, flags | FD_CLOEXEC);
  1831. VERIFY(rc == 0);
  1832. m_saves.append({ rewiring.new_fd, new_fd });
  1833. m_collector.add(new_fd);
  1834. }
  1835. }
  1836. SavedFileDescriptors::~SavedFileDescriptors()
  1837. {
  1838. for (auto& save : m_saves) {
  1839. if (dup2(save.saved, save.original) < 0) {
  1840. perror("dup2(~SavedFileDescriptors)");
  1841. continue;
  1842. }
  1843. }
  1844. }
  1845. }