Shell.cpp 66 KB

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