Shell.cpp 66 KB

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