Shell.cpp 65 KB

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