Shell.cpp 67 KB

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