Shell.cpp 66 KB

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