Shell.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664
  1. /*
  2. * Copyright (c) 2020-2022, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Shell.h"
  7. #include "Execution.h"
  8. #include "Formatter.h"
  9. #include <AK/CharacterTypes.h>
  10. #include <AK/Debug.h>
  11. #include <AK/Function.h>
  12. #include <AK/GenericLexer.h>
  13. #include <AK/JsonParser.h>
  14. #include <AK/LexicalPath.h>
  15. #include <AK/QuickSort.h>
  16. #include <AK/ScopeGuard.h>
  17. #include <AK/ScopedValueRollback.h>
  18. #include <AK/StringBuilder.h>
  19. #include <AK/TemporaryChange.h>
  20. #include <AK/URL.h>
  21. #include <LibCore/DirIterator.h>
  22. #include <LibCore/Event.h>
  23. #include <LibCore/EventLoop.h>
  24. #include <LibCore/File.h>
  25. #include <LibCore/System.h>
  26. #include <LibCore/Timer.h>
  27. #include <LibFileSystem/FileSystem.h>
  28. #include <LibLine/Editor.h>
  29. #include <Shell/PosixParser.h>
  30. #include <errno.h>
  31. #include <fcntl.h>
  32. #include <inttypes.h>
  33. #include <pwd.h>
  34. #include <signal.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <sys/mman.h>
  39. #include <sys/stat.h>
  40. #include <sys/utsname.h>
  41. #include <sys/wait.h>
  42. #include <termios.h>
  43. #include <unistd.h>
  44. static bool s_disable_hyperlinks = false;
  45. extern char** environ;
  46. namespace Shell {
  47. void Shell::setup_signals()
  48. {
  49. if (m_should_reinstall_signal_handlers) {
  50. Core::EventLoop::register_signal(SIGCHLD, [this](int) {
  51. dbgln_if(SH_DEBUG, "SIGCHLD!");
  52. notify_child_event();
  53. });
  54. Core::EventLoop::register_signal(SIGTSTP, [this](auto) {
  55. auto job = current_job();
  56. kill_job(job, SIGTSTP);
  57. if (job) {
  58. job->set_is_suspended(true);
  59. job->unblock();
  60. }
  61. });
  62. }
  63. }
  64. void Shell::print_path(StringView path)
  65. {
  66. if (s_disable_hyperlinks || !m_is_interactive) {
  67. out("{}", path);
  68. return;
  69. }
  70. auto url = URL::create_with_file_scheme(path, {}, hostname);
  71. out("\033]8;;{}\033\\{}\033]8;;\033\\", url.serialize(), path);
  72. }
  73. DeprecatedString Shell::prompt() const
  74. {
  75. if (m_next_scheduled_prompt_text.has_value())
  76. return m_next_scheduled_prompt_text.release_value();
  77. auto build_prompt = [&]() -> DeprecatedString {
  78. auto* ps1 = getenv("PROMPT");
  79. if (!ps1) {
  80. if (uid == 0)
  81. return "# ";
  82. StringBuilder builder;
  83. builder.appendff("\033]0;{}@{}:{}\007", username, hostname, cwd);
  84. builder.appendff("\033[31;1m{}\033[0m@\033[37;1m{}\033[0m:\033[32;1m{}\033[0m$> ", username, hostname, cwd);
  85. return builder.to_deprecated_string();
  86. }
  87. StringBuilder builder;
  88. for (char* ptr = ps1; *ptr; ++ptr) {
  89. if (*ptr == '\\') {
  90. ++ptr;
  91. if (!*ptr)
  92. break;
  93. switch (*ptr) {
  94. case 'X':
  95. builder.append("\033]0;"sv);
  96. break;
  97. case 'a':
  98. builder.append(0x07);
  99. break;
  100. case 'e':
  101. builder.append(0x1b);
  102. break;
  103. case 'u':
  104. builder.append(username);
  105. break;
  106. case 'h':
  107. builder.append({ hostname, strlen(hostname) });
  108. break;
  109. case 'w': {
  110. DeprecatedString home_path = getenv("HOME");
  111. if (cwd.starts_with(home_path)) {
  112. builder.append('~');
  113. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  114. } else {
  115. builder.append(cwd);
  116. }
  117. break;
  118. }
  119. case 'p':
  120. builder.append(uid == 0 ? '#' : '$');
  121. break;
  122. }
  123. continue;
  124. }
  125. builder.append(*ptr);
  126. }
  127. return builder.to_deprecated_string();
  128. };
  129. return build_prompt();
  130. }
  131. DeprecatedString Shell::expand_tilde(StringView expression)
  132. {
  133. VERIFY(expression.starts_with('~'));
  134. StringBuilder login_name;
  135. size_t first_slash_index = expression.length();
  136. for (size_t i = 1; i < expression.length(); ++i) {
  137. if (expression[i] == '/') {
  138. first_slash_index = i;
  139. break;
  140. }
  141. login_name.append(expression[i]);
  142. }
  143. StringBuilder path;
  144. for (size_t i = first_slash_index; i < expression.length(); ++i)
  145. path.append(expression[i]);
  146. if (login_name.is_empty()) {
  147. char const* home = getenv("HOME");
  148. if (!home) {
  149. auto passwd = getpwuid(getuid());
  150. VERIFY(passwd && passwd->pw_dir);
  151. return DeprecatedString::formatted("{}/{}", passwd->pw_dir, path.to_deprecated_string());
  152. }
  153. return DeprecatedString::formatted("{}/{}", home, path.to_deprecated_string());
  154. }
  155. auto passwd = getpwnam(login_name.to_deprecated_string().characters());
  156. if (!passwd)
  157. return expression;
  158. VERIFY(passwd->pw_dir);
  159. return DeprecatedString::formatted("{}/{}", passwd->pw_dir, path.to_deprecated_string());
  160. }
  161. bool Shell::is_glob(StringView s)
  162. {
  163. for (size_t i = 0; i < s.length(); i++) {
  164. char c = s.characters_without_null_termination()[i];
  165. if (c == '*' || c == '?')
  166. return true;
  167. }
  168. return false;
  169. }
  170. Vector<StringView> Shell::split_path(StringView path)
  171. {
  172. Vector<StringView> parts;
  173. size_t substart = 0;
  174. for (size_t i = 0; i < path.length(); i++) {
  175. char ch = path[i];
  176. if (ch != '/')
  177. continue;
  178. size_t sublen = i - substart;
  179. if (sublen != 0)
  180. parts.append(path.substring_view(substart, sublen));
  181. substart = i + 1;
  182. }
  183. size_t taillen = path.length() - substart;
  184. if (taillen != 0)
  185. parts.append(path.substring_view(substart, taillen));
  186. return parts;
  187. }
  188. Vector<DeprecatedString> Shell::expand_globs(StringView path, StringView base)
  189. {
  190. auto explicitly_set_base = false;
  191. if (path.starts_with('/')) {
  192. base = "/"sv;
  193. explicitly_set_base = true;
  194. }
  195. auto parts = split_path(path);
  196. DeprecatedString base_string = base;
  197. struct stat statbuf;
  198. if (lstat(base_string.characters(), &statbuf) < 0) {
  199. perror("lstat");
  200. return {};
  201. }
  202. StringBuilder resolved_base_path_builder;
  203. resolved_base_path_builder.append(FileSystem::real_path(base).release_value_but_fixme_should_propagate_errors());
  204. if (S_ISDIR(statbuf.st_mode))
  205. resolved_base_path_builder.append('/');
  206. auto resolved_base = resolved_base_path_builder.string_view();
  207. auto results = expand_globs(move(parts), resolved_base);
  208. if (explicitly_set_base && base == "/")
  209. resolved_base = resolved_base.substring_view(1, resolved_base.length() - 1);
  210. for (auto& entry : results) {
  211. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  212. if (entry.is_empty())
  213. entry = ".";
  214. }
  215. // Make the output predictable and nice.
  216. quick_sort(results);
  217. return results;
  218. }
  219. Vector<DeprecatedString> Shell::expand_globs(Vector<StringView> path_segments, StringView base)
  220. {
  221. if (path_segments.is_empty()) {
  222. DeprecatedString base_str = base;
  223. struct stat statbuf;
  224. if (lstat(base_str.characters(), &statbuf) < 0)
  225. return {};
  226. return { move(base_str) };
  227. }
  228. auto first_segment = path_segments.take_first();
  229. if (is_glob(first_segment)) {
  230. Vector<DeprecatedString> result;
  231. Core::DirIterator di(base, Core::DirIterator::SkipParentAndBaseDir);
  232. if (di.has_error())
  233. return {};
  234. while (di.has_next()) {
  235. DeprecatedString path = di.next_path();
  236. // Dotfiles have to be explicitly requested
  237. if (path[0] == '.' && first_segment[0] != '.')
  238. continue;
  239. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  240. StringBuilder builder;
  241. builder.append(base);
  242. if (!base.ends_with('/'))
  243. builder.append('/');
  244. builder.append(path);
  245. result.extend(expand_globs(path_segments, builder.string_view()));
  246. }
  247. }
  248. return result;
  249. } else {
  250. StringBuilder builder;
  251. builder.append(base);
  252. if (!base.ends_with('/'))
  253. builder.append('/');
  254. builder.append(first_segment);
  255. return expand_globs(move(path_segments), builder.string_view());
  256. }
  257. }
  258. ErrorOr<Vector<AST::Command>> Shell::expand_aliases(Vector<AST::Command> initial_commands)
  259. {
  260. Vector<AST::Command> commands;
  261. Function<ErrorOr<void>(AST::Command&)> resolve_aliases_and_append = [&](auto& command) -> ErrorOr<void> {
  262. if (!command.argv.is_empty()) {
  263. auto alias = resolve_alias(command.argv[0]);
  264. if (alias.has_value()) {
  265. auto argv0 = command.argv.take_first();
  266. auto subcommand_ast = parse(*alias, false);
  267. if (subcommand_ast) {
  268. while (subcommand_ast->is_execute()) {
  269. auto* ast = static_cast<AST::Execute*>(subcommand_ast.ptr());
  270. subcommand_ast = ast->command();
  271. }
  272. auto subcommand_nonnull = subcommand_ast.release_nonnull();
  273. NonnullRefPtr<AST::Node> substitute = adopt_ref(*new AST::Join(subcommand_nonnull->position(),
  274. subcommand_nonnull,
  275. adopt_ref(*new AST::CommandLiteral(subcommand_nonnull->position(), command))));
  276. auto res = TRY(substitute->run(*this));
  277. for (auto& subst_command : TRY(res->resolve_as_commands(*this))) {
  278. if (!subst_command.argv.is_empty() && subst_command.argv.first() == argv0) // Disallow an alias resolving to itself.
  279. commands.append(subst_command);
  280. else
  281. TRY(resolve_aliases_and_append(subst_command));
  282. }
  283. } else {
  284. commands.append(command);
  285. }
  286. } else {
  287. commands.append(command);
  288. }
  289. } else {
  290. commands.append(command);
  291. }
  292. return {};
  293. };
  294. for (auto& command : initial_commands)
  295. TRY(resolve_aliases_and_append(command));
  296. return commands;
  297. }
  298. DeprecatedString Shell::resolve_path(DeprecatedString path) const
  299. {
  300. if (!path.starts_with('/'))
  301. path = DeprecatedString::formatted("{}/{}", cwd, path);
  302. return FileSystem::real_path(path).release_value_but_fixme_should_propagate_errors().to_deprecated_string();
  303. }
  304. Shell::LocalFrame* Shell::find_frame_containing_local_variable(StringView name)
  305. {
  306. for (size_t i = m_local_frames.size(); i > 0; --i) {
  307. auto& frame = m_local_frames[i - 1];
  308. if (frame->local_variables.contains(name))
  309. return frame;
  310. }
  311. return nullptr;
  312. }
  313. ErrorOr<RefPtr<AST::Value const>> Shell::look_up_local_variable(StringView name) const
  314. {
  315. if (auto* frame = find_frame_containing_local_variable(name))
  316. return frame->local_variables.get(name).value();
  317. if (auto index = name.to_uint(); index.has_value())
  318. return get_argument(index.value());
  319. return nullptr;
  320. }
  321. ErrorOr<RefPtr<AST::Value const>> Shell::get_argument(size_t index) const
  322. {
  323. if (index == 0)
  324. return adopt_ref(*new AST::StringValue(TRY(String::from_deprecated_string(current_script))));
  325. --index;
  326. if (auto argv = TRY(look_up_local_variable("ARGV"sv))) {
  327. if (argv->is_list_without_resolution()) {
  328. AST::ListValue const* list = static_cast<AST::ListValue const*>(argv.ptr());
  329. if (list->values().size() <= index)
  330. return nullptr;
  331. return list->values().at(index);
  332. }
  333. if (index != 0)
  334. return nullptr;
  335. return argv;
  336. }
  337. return nullptr;
  338. }
  339. ErrorOr<DeprecatedString> Shell::local_variable_or(StringView name, DeprecatedString const& replacement) const
  340. {
  341. auto value = TRY(look_up_local_variable(name));
  342. if (value) {
  343. StringBuilder builder;
  344. builder.join(' ', TRY(const_cast<AST::Value&>(*value).resolve_as_list(const_cast<Shell&>(*this))));
  345. return builder.to_deprecated_string();
  346. }
  347. return replacement;
  348. }
  349. void Shell::set_local_variable(DeprecatedString const& name, RefPtr<AST::Value> value, bool only_in_current_frame)
  350. {
  351. if (!only_in_current_frame) {
  352. if (auto* frame = find_frame_containing_local_variable(name)) {
  353. frame->local_variables.set(name, move(value));
  354. return;
  355. }
  356. }
  357. LocalFrame* selected_frame = nullptr;
  358. if (m_in_posix_mode) {
  359. // POSIX mode: Drop everything in the closest function frame (or the global frame if there is no function frame).
  360. auto& closest_function_frame = m_local_frames.last_matching([](auto& frame) { return frame->is_function_frame; }).value();
  361. selected_frame = closest_function_frame.ptr();
  362. } else {
  363. selected_frame = m_local_frames.last().ptr();
  364. }
  365. selected_frame->local_variables.set(name, move(value));
  366. }
  367. void Shell::unset_local_variable(StringView name, bool only_in_current_frame)
  368. {
  369. if (!only_in_current_frame) {
  370. if (auto* frame = find_frame_containing_local_variable(name))
  371. frame->local_variables.remove(name);
  372. return;
  373. }
  374. m_local_frames.last()->local_variables.remove(name);
  375. }
  376. void Shell::define_function(DeprecatedString name, Vector<DeprecatedString> argnames, RefPtr<AST::Node> body)
  377. {
  378. add_entry_to_cache({ RunnablePath::Kind::Function, name });
  379. m_functions.set(name, { name, move(argnames), move(body) });
  380. }
  381. bool Shell::has_function(StringView name)
  382. {
  383. return m_functions.contains(name);
  384. }
  385. bool Shell::invoke_function(const AST::Command& command, int& retval)
  386. {
  387. if (command.argv.is_empty())
  388. return false;
  389. StringView name = command.argv.first();
  390. TemporaryChange<DeprecatedString> script_change { current_script, name };
  391. auto function_option = m_functions.get(name);
  392. if (!function_option.has_value())
  393. return false;
  394. auto& function = function_option.value();
  395. if (!function.body) {
  396. retval = 0;
  397. return true;
  398. }
  399. if (command.argv.size() - 1 < function.arguments.size()) {
  400. raise_error(ShellError::EvaluatedSyntaxError, DeprecatedString::formatted("Expected at least {} arguments to {}, but got {}", function.arguments.size(), function.name, command.argv.size() - 1), command.position);
  401. retval = 1;
  402. return true;
  403. }
  404. auto frame = push_frame(DeprecatedString::formatted("function {}", function.name), LocalFrameKind::FunctionOrGlobal);
  405. size_t index = 0;
  406. for (auto& arg : function.arguments) {
  407. ++index;
  408. set_local_variable(arg, adopt_ref(*new AST::StringValue(command.argv[index])), true);
  409. }
  410. auto argv = command.argv;
  411. argv.take_first();
  412. set_local_variable("ARGV", adopt_ref(*new AST::ListValue(move(argv))), true);
  413. Core::EventLoop loop;
  414. setup_signals();
  415. (void)function.body->run(*this);
  416. if (has_error(ShellError::InternalControlFlowReturn))
  417. take_error();
  418. retval = last_return_code.value_or(0);
  419. return true;
  420. }
  421. DeprecatedString Shell::format(StringView source, ssize_t& cursor) const
  422. {
  423. Formatter formatter(source, cursor, m_in_posix_mode);
  424. auto result = formatter.format();
  425. cursor = formatter.cursor();
  426. return result;
  427. }
  428. Shell::Frame Shell::push_frame(DeprecatedString name, Shell::LocalFrameKind kind)
  429. {
  430. m_local_frames.append(make<LocalFrame>(name, decltype(LocalFrame::local_variables) {}, kind));
  431. dbgln_if(SH_DEBUG, "New frame '{}' at {:p}", name, &m_local_frames.last());
  432. return { m_local_frames, *m_local_frames.last() };
  433. }
  434. void Shell::pop_frame()
  435. {
  436. VERIFY(m_local_frames.size() > 1);
  437. (void)m_local_frames.take_last();
  438. }
  439. Shell::Frame::~Frame()
  440. {
  441. if (!should_destroy_frame)
  442. return;
  443. if (frames.last() != &frame) {
  444. dbgln("Frame destruction order violation near {:p} (container = {:p}) in '{}'", &frame, this, frame.name);
  445. dbgln("Current frames:");
  446. for (auto& frame : frames)
  447. dbgln("- {:p}: {}", &frame, frame->name);
  448. VERIFY_NOT_REACHED();
  449. }
  450. (void)frames.take_last();
  451. }
  452. Optional<DeprecatedString> Shell::resolve_alias(StringView name) const
  453. {
  454. return m_aliases.get(name);
  455. }
  456. Optional<Shell::RunnablePath> Shell::runnable_path_for(StringView name)
  457. {
  458. auto parts = name.find('/');
  459. if (parts.has_value()) {
  460. auto file_or_error = Core::File::open(name, Core::File::OpenMode::Read);
  461. if (!file_or_error.is_error()
  462. && !FileSystem::is_directory(file_or_error.value()->fd())
  463. && !Core::System::access(name, X_OK).is_error())
  464. return RunnablePath { RunnablePath::Kind::Executable, name };
  465. }
  466. auto* found = binary_search(cached_path.span(), name, nullptr, RunnablePathComparator {});
  467. if (!found)
  468. return {};
  469. return *found;
  470. }
  471. Optional<DeprecatedString> Shell::help_path_for(Vector<RunnablePath> visited, Shell::RunnablePath const& runnable_path)
  472. {
  473. switch (runnable_path.kind) {
  474. case RunnablePath::Kind::Executable: {
  475. LexicalPath lexical_path(runnable_path.path);
  476. return lexical_path.basename();
  477. }
  478. case RunnablePath::Kind::Alias: {
  479. if (visited.contains_slow(runnable_path))
  480. return {}; // Break out of an alias loop
  481. auto resolved = resolve_alias(runnable_path.path).value_or("");
  482. auto* runnable = binary_search(cached_path.span(), resolved, nullptr, RunnablePathComparator {});
  483. if (!runnable)
  484. return {};
  485. visited.append(runnable_path);
  486. return help_path_for(visited, *runnable);
  487. }
  488. default:
  489. return {};
  490. }
  491. }
  492. int Shell::run_command(StringView cmd, Optional<SourcePosition> source_position_override)
  493. {
  494. // The default-constructed mode of the shell
  495. // should not be used for execution!
  496. VERIFY(!m_default_constructed);
  497. take_error();
  498. if (!last_return_code.has_value())
  499. last_return_code = 0;
  500. ScopedValueRollback source_position_rollback { m_source_position };
  501. if (source_position_override.has_value())
  502. m_source_position = move(source_position_override);
  503. if (!m_source_position.has_value())
  504. m_source_position = SourcePosition { .source_file = {}, .literal_source_text = cmd, .position = {} };
  505. if (cmd.is_empty())
  506. return 0;
  507. auto command = parse(cmd, m_is_interactive);
  508. if (!command)
  509. return 0;
  510. if constexpr (SH_DEBUG) {
  511. dbgln("Command follows");
  512. (void)command->dump(0);
  513. }
  514. if (command->is_syntax_error()) {
  515. auto& error_node = command->syntax_error_node();
  516. auto& position = error_node.position();
  517. raise_error(ShellError::EvaluatedSyntaxError, error_node.error_text().bytes_as_string_view(), position);
  518. }
  519. if (!has_error(ShellError::None)) {
  520. possibly_print_error();
  521. take_error();
  522. return 1;
  523. }
  524. tcgetattr(0, &termios);
  525. (void)command->run(*this);
  526. if (!has_error(ShellError::None)) {
  527. possibly_print_error();
  528. take_error();
  529. return 1;
  530. }
  531. return last_return_code.value_or(0);
  532. }
  533. ErrorOr<RefPtr<Job>> Shell::run_command(const AST::Command& command)
  534. {
  535. FileDescriptionCollector fds;
  536. if (options.verbose)
  537. warnln("+ {}", command);
  538. // If the command is empty, store the redirections and apply them to all later commands.
  539. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  540. m_global_redirections.extend(command.redirections);
  541. for (auto& next_in_chain : command.next_chain)
  542. run_tail(command, next_in_chain, last_return_code.value_or(0));
  543. return nullptr;
  544. }
  545. // Resolve redirections.
  546. Vector<NonnullRefPtr<AST::Rewiring>> rewirings;
  547. auto resolve_redirection = [&](auto& redirection) -> ErrorOr<void> {
  548. auto rewiring = TRY(redirection->apply());
  549. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseNew)
  550. rewirings.append(*rewiring);
  551. if (rewiring->fd_action == AST::Rewiring::Close::Old) {
  552. fds.add(rewiring->old_fd);
  553. } else if (rewiring->fd_action == AST::Rewiring::Close::New) {
  554. if (rewiring->new_fd != -1)
  555. fds.add(rewiring->new_fd);
  556. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseNew) {
  557. fds.add(rewiring->new_fd);
  558. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshNew) {
  559. VERIFY(rewiring->other_pipe_end);
  560. int pipe_fd[2];
  561. int rc = pipe(pipe_fd);
  562. if (rc < 0)
  563. return Error::from_syscall("pipe"sv, rc);
  564. rewiring->new_fd = pipe_fd[1];
  565. rewiring->other_pipe_end->new_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  566. fds.add(pipe_fd[1]);
  567. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshOld) {
  568. VERIFY(rewiring->other_pipe_end);
  569. int pipe_fd[2];
  570. int rc = pipe(pipe_fd);
  571. if (rc < 0)
  572. return Error::from_syscall("pipe"sv, rc);
  573. rewiring->old_fd = pipe_fd[1];
  574. rewiring->other_pipe_end->old_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  575. fds.add(pipe_fd[1]);
  576. }
  577. return {};
  578. };
  579. auto apply_rewirings = [&]() -> ErrorOr<void> {
  580. for (auto& rewiring : rewirings) {
  581. dbgln_if(SH_DEBUG, "in {}<{}>, dup2({}, {})", command.argv.is_empty() ? "(<Empty>)"sv : command.argv[0], getpid(), rewiring->old_fd, rewiring->new_fd);
  582. int rc = dup2(rewiring->old_fd, rewiring->new_fd);
  583. if (rc < 0)
  584. return Error::from_syscall("dup2"sv, rc);
  585. // {new,old}_fd is closed via the `fds` collector, but rewiring->other_pipe_end->{new,old}_fd
  586. // isn't yet in that collector when the first child spawns.
  587. if (rewiring->other_pipe_end) {
  588. if (rewiring->fd_action == AST::Rewiring::Close::RefreshNew) {
  589. if (rewiring->other_pipe_end && close(rewiring->other_pipe_end->new_fd) < 0)
  590. perror("close other pipe end");
  591. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshOld) {
  592. if (rewiring->other_pipe_end && close(rewiring->other_pipe_end->old_fd) < 0)
  593. perror("close other pipe end");
  594. }
  595. }
  596. }
  597. return {};
  598. };
  599. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, false };
  600. for (auto& redirection : m_global_redirections)
  601. TRY(resolve_redirection(redirection));
  602. for (auto& redirection : command.redirections)
  603. TRY(resolve_redirection(redirection));
  604. if (int local_return_code = 0; command.should_wait && TRY(run_builtin(command, rewirings, local_return_code))) {
  605. last_return_code = local_return_code;
  606. for (auto& next_in_chain : command.next_chain)
  607. run_tail(command, next_in_chain, *last_return_code);
  608. return nullptr;
  609. }
  610. auto can_be_run_in_current_process = command.should_wait && !command.pipeline && !command.argv.is_empty();
  611. if (can_be_run_in_current_process && has_function(command.argv.first())) {
  612. SavedFileDescriptors fds { rewirings };
  613. for (auto& rewiring : rewirings)
  614. TRY(Core::System::dup2(rewiring->old_fd, rewiring->new_fd));
  615. if (int local_return_code = 0; invoke_function(command, local_return_code)) {
  616. last_return_code = local_return_code;
  617. for (auto& next_in_chain : command.next_chain)
  618. run_tail(command, next_in_chain, *last_return_code);
  619. return nullptr;
  620. }
  621. }
  622. if (command.argv.is_empty()
  623. && !command.next_chain.is_empty()
  624. && command.should_immediately_execute_next
  625. && command.redirections.is_empty()
  626. && command.next_chain.first().node->should_override_execution_in_current_process()) {
  627. for (auto& next_in_chain : command.next_chain)
  628. run_tail(command, next_in_chain, last_return_code.value_or(0));
  629. return nullptr;
  630. }
  631. Vector<char const*> argv;
  632. Vector<DeprecatedString> copy_argv;
  633. argv.ensure_capacity(command.argv.size() + 1);
  634. for (auto& arg : command.argv) {
  635. copy_argv.append(arg.to_deprecated_string());
  636. argv.append(copy_argv.last().characters());
  637. }
  638. argv.append(nullptr);
  639. auto sync_pipe = TRY(Core::System::pipe2(0));
  640. auto child = TRY(Core::System::fork());
  641. if (child == 0) {
  642. close(sync_pipe[1]);
  643. m_pid = getpid();
  644. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  645. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, true };
  646. if (auto result = apply_rewirings(); result.is_error()) {
  647. warnln("Shell: Failed to apply rewirings in {}: {}", copy_argv[0], result.error());
  648. _exit(126);
  649. }
  650. fds.collect();
  651. u8 c;
  652. while (read(sync_pipe[0], &c, 1) < 0) {
  653. if (errno != EINTR) {
  654. warnln("Shell: Failed to sync in {}: {}", copy_argv[0], Error::from_syscall("read"sv, -errno));
  655. // There's nothing interesting we can do here.
  656. break;
  657. }
  658. }
  659. dbgln_if(SH_DEBUG, "Synced up with parent, we're good to exec()");
  660. close(sync_pipe[0]);
  661. if (!m_is_subshell && command.should_wait)
  662. tcsetattr(0, TCSANOW, &default_termios);
  663. m_is_subshell = true;
  664. if (command.should_immediately_execute_next) {
  665. VERIFY(command.argv.is_empty());
  666. Core::EventLoop mainloop;
  667. setup_signals();
  668. for (auto& next_in_chain : command.next_chain)
  669. run_tail(command, next_in_chain, 0);
  670. _exit(last_return_code.value_or(0));
  671. }
  672. if (int local_return_code = 0; TRY(run_builtin(command, {}, local_return_code)))
  673. _exit(local_return_code);
  674. if (int local_return_code = 0; invoke_function(command, local_return_code))
  675. _exit(local_return_code);
  676. // We no longer need the jobs here.
  677. jobs.clear();
  678. execute_process(move(argv));
  679. VERIFY_NOT_REACHED();
  680. }
  681. close(sync_pipe[0]);
  682. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  683. if (command.pipeline) {
  684. if (is_first) {
  685. command.pipeline->pgid = child;
  686. }
  687. }
  688. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  689. if (!m_is_subshell || command.pipeline) {
  690. auto result = Core::System::setpgid(child, pgid);
  691. if (result.is_error() && m_is_interactive)
  692. warnln("Shell: {}", result.error());
  693. if (!m_is_subshell) {
  694. // There's no reason to care about the errors here
  695. // either we're in a tty, we're interactive, and this works
  696. // or we're not, and it fails - in which case, we don't need
  697. // stdin/stdout handoff to child processes anyway.
  698. tcsetpgrp(STDOUT_FILENO, pgid);
  699. tcsetpgrp(STDIN_FILENO, pgid);
  700. }
  701. }
  702. while (write(sync_pipe[1], "x", 1) < 0) {
  703. if (errno != EINTR) {
  704. warnln("Shell: Failed to sync with {}: {}", copy_argv[0], Error::from_syscall("write"sv, -errno));
  705. // There's nothing interesting we can do here.
  706. break;
  707. }
  708. }
  709. close(sync_pipe[1]);
  710. StringBuilder cmd;
  711. cmd.join(' ', command.argv);
  712. auto command_copy = AST::Command(command);
  713. // Clear the next chain if it's to be immediately executed
  714. // as the child will run this chain.
  715. if (command.should_immediately_execute_next)
  716. command_copy.next_chain.clear();
  717. auto job = Job::create(child, pgid, cmd.to_deprecated_string(), find_last_job_id() + 1, move(command_copy));
  718. jobs.set((u64)child, job);
  719. job->on_exit = [this](auto job) {
  720. if (!job->exited())
  721. return;
  722. if (job->is_running_in_background() && job->should_announce_exit())
  723. warnln("Shell: Job {} ({}) exited\n", job->job_id(), job->cmd());
  724. else if (job->signaled() && job->should_announce_signal())
  725. warnln("Shell: Job {} ({}) {}\n", job->job_id(), job->cmd(), strsignal(job->termination_signal()));
  726. last_return_code = job->exit_code();
  727. job->disown();
  728. if (m_editor && job->exit_code() == 0 && is_allowed_to_modify_termios(job->command())) {
  729. m_editor->refetch_default_termios();
  730. default_termios = m_editor->default_termios();
  731. termios = m_editor->termios();
  732. }
  733. run_tail(job);
  734. };
  735. fds.collect();
  736. return *job;
  737. }
  738. ErrorOr<void> Shell::execute_process(Span<StringView> argv)
  739. {
  740. Vector<DeprecatedString> strings;
  741. Vector<char const*> args;
  742. TRY(strings.try_ensure_capacity(argv.size()));
  743. TRY(args.try_ensure_capacity(argv.size() + 1));
  744. for (auto& entry : argv) {
  745. strings.unchecked_append(entry);
  746. args.unchecked_append(strings.last().characters());
  747. }
  748. args.append(nullptr);
  749. // NOTE: noreturn.
  750. execute_process(move(args));
  751. }
  752. void Shell::execute_process(Vector<char const*>&& argv)
  753. {
  754. for (auto& promise : m_active_promises) {
  755. MUST(Core::System::pledge("stdio rpath exec"sv, promise.data.exec_promises));
  756. for (auto& item : promise.data.unveils)
  757. MUST(Core::System::unveil(item.path, item.access));
  758. }
  759. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  760. if (rc < 0) {
  761. auto parts = StringView { argv[0], strlen(argv[0]) }.split_view('/');
  762. if (parts.size() == 1) {
  763. // If this is a path in the current directory and it caused execvp() to fail,
  764. // simply don't attempt to execute it, see #6774.
  765. warnln("{}: Command not found.", argv[0]);
  766. _exit(127);
  767. }
  768. int saved_errno = errno;
  769. struct stat st;
  770. if (stat(argv[0], &st)) {
  771. warnln("stat({}): {}", argv[0], strerror(errno));
  772. // Return code 127 on command not found.
  773. _exit(127);
  774. }
  775. if (!(st.st_mode & S_IXUSR)) {
  776. warnln("{}: Not executable", argv[0]);
  777. // Return code 126 when file is not executable.
  778. _exit(126);
  779. }
  780. if (saved_errno == ENOENT) {
  781. do {
  782. auto path_as_string_or_error = String::from_utf8({ argv[0], strlen(argv[0]) });
  783. if (path_as_string_or_error.is_error())
  784. break;
  785. auto file_result = Core::File::open(path_as_string_or_error.value(), Core::File::OpenMode::Read);
  786. if (file_result.is_error())
  787. break;
  788. auto buffered_file_result = Core::InputBufferedFile::create(file_result.release_value());
  789. if (buffered_file_result.is_error())
  790. break;
  791. auto file = buffered_file_result.release_value();
  792. Array<u8, 1 * KiB> line_buf;
  793. auto line_or_error = file->read_line(line_buf);
  794. if (line_or_error.is_error())
  795. break;
  796. auto line = line_or_error.release_value();
  797. if (!line.starts_with("#!"sv))
  798. break;
  799. GenericLexer shebang_lexer { line.substring_view(2) };
  800. auto shebang = shebang_lexer.consume_until(is_any_of("\n\r"sv)).to_deprecated_string();
  801. argv.prepend(shebang.characters());
  802. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  803. if (rc < 0) {
  804. warnln("{}: Invalid interpreter \"{}\": {}", argv[0], shebang.characters(), strerror(errno));
  805. _exit(126);
  806. }
  807. } while (false);
  808. warnln("{}: Command not found.", argv[0]);
  809. } else {
  810. if (S_ISDIR(st.st_mode)) {
  811. warnln("Shell: {}: Is a directory", argv[0]);
  812. _exit(126);
  813. }
  814. warnln("execvp({}): {}", argv[0], strerror(saved_errno));
  815. }
  816. _exit(126);
  817. }
  818. VERIFY_NOT_REACHED();
  819. }
  820. void Shell::run_tail(const AST::Command& invoking_command, const AST::NodeWithAction& next_in_chain, int head_exit_code)
  821. {
  822. if (m_error != ShellError::None) {
  823. possibly_print_error();
  824. if (!is_control_flow(m_error))
  825. take_error();
  826. return;
  827. }
  828. auto evaluate = [&] {
  829. if (next_in_chain.node->would_execute()) {
  830. (void)next_in_chain.node->run(*this);
  831. return;
  832. }
  833. auto node = next_in_chain.node;
  834. if (!invoking_command.should_wait)
  835. node = adopt_ref(static_cast<AST::Node&>(*new AST::Background(next_in_chain.node->position(), move(node))));
  836. (void)adopt_ref(static_cast<AST::Node&>(*new AST::Execute(next_in_chain.node->position(), move(node))))->run(*this);
  837. };
  838. switch (next_in_chain.action) {
  839. case AST::NodeWithAction::And:
  840. if (head_exit_code == 0)
  841. evaluate();
  842. break;
  843. case AST::NodeWithAction::Or:
  844. if (head_exit_code != 0)
  845. evaluate();
  846. break;
  847. case AST::NodeWithAction::Sequence:
  848. evaluate();
  849. break;
  850. }
  851. }
  852. void Shell::run_tail(RefPtr<Job> job)
  853. {
  854. if (auto cmd = job->command_ptr()) {
  855. deferred_invoke([=, this] {
  856. for (auto& next_in_chain : cmd->next_chain) {
  857. run_tail(*cmd, next_in_chain, job->exit_code());
  858. }
  859. });
  860. }
  861. }
  862. Vector<NonnullRefPtr<Job>> Shell::run_commands(Vector<AST::Command>& commands)
  863. {
  864. if (m_error != ShellError::None) {
  865. possibly_print_error();
  866. if (!is_control_flow(m_error))
  867. take_error();
  868. return {};
  869. }
  870. Vector<NonnullRefPtr<Job>> spawned_jobs;
  871. for (auto& command : commands) {
  872. if constexpr (SH_DEBUG) {
  873. dbgln("Command");
  874. for (auto& arg : command.argv)
  875. dbgln("argv: {}", arg);
  876. for (auto& redir : command.redirections) {
  877. if (redir->is_path_redirection()) {
  878. auto path_redir = (const AST::PathRedirection*)&redir;
  879. dbgln("redir path '{}' <-({})-> {}", path_redir->path, (int)path_redir->direction, path_redir->fd);
  880. } else if (redir->is_fd_redirection()) {
  881. auto* fdredir = (const AST::FdRedirection*)&redir;
  882. dbgln("redir fd {} -> {}", fdredir->old_fd, fdredir->new_fd);
  883. } else if (redir->is_close_redirection()) {
  884. auto close_redir = (const AST::CloseRedirection*)&redir;
  885. dbgln("close fd {}", close_redir->fd);
  886. } else {
  887. VERIFY_NOT_REACHED();
  888. }
  889. }
  890. }
  891. auto job_result = run_command(command);
  892. if (job_result.is_error()) {
  893. raise_error(ShellError::LaunchError, DeprecatedString::formatted("{} while running '{}'", job_result.error(), command.argv.first()), command.position);
  894. break;
  895. }
  896. auto job = job_result.release_value();
  897. if (!job)
  898. continue;
  899. spawned_jobs.append(*job);
  900. if (command.should_wait) {
  901. block_on_job(job);
  902. } else {
  903. job->set_running_in_background(true);
  904. if (!command.is_pipe_source && command.should_notify_if_in_background)
  905. job->set_should_announce_exit(true);
  906. }
  907. }
  908. if (m_error != ShellError::None) {
  909. possibly_print_error();
  910. if (!is_control_flow(m_error))
  911. take_error();
  912. }
  913. return spawned_jobs;
  914. }
  915. bool Shell::run_file(DeprecatedString const& filename, bool explicitly_invoked)
  916. {
  917. TemporaryChange script_change { current_script, filename };
  918. TemporaryChange interactive_change { m_is_interactive, false };
  919. TemporaryChange<Optional<SourcePosition>> source_change { m_source_position, SourcePosition { .source_file = filename, .literal_source_text = {}, .position = {} } };
  920. auto file_or_error = Core::File::open(filename, Core::File::OpenMode::Read);
  921. if (file_or_error.is_error()) {
  922. auto error = DeprecatedString::formatted("'{}': {}", escape_token_for_single_quotes(filename), file_or_error.error());
  923. if (explicitly_invoked)
  924. raise_error(ShellError::OpenFailure, error);
  925. else
  926. dbgln("open() failed for {}", error);
  927. return false;
  928. }
  929. auto file = file_or_error.release_value();
  930. auto data_or_error = file->read_until_eof();
  931. if (data_or_error.is_error()) {
  932. auto error = DeprecatedString::formatted("'{}': {}", escape_token_for_single_quotes(filename), data_or_error.error());
  933. if (explicitly_invoked)
  934. raise_error(ShellError::OpenFailure, error);
  935. else
  936. dbgln("reading after open() failed for {}", error);
  937. return false;
  938. }
  939. return run_command(data_or_error.value()) == 0;
  940. }
  941. bool Shell::is_allowed_to_modify_termios(const AST::Command& command) const
  942. {
  943. if (command.argv.is_empty())
  944. return false;
  945. auto value = look_up_local_variable("PROGRAMS_ALLOWED_TO_MODIFY_DEFAULT_TERMIOS"sv);
  946. if (value.is_error())
  947. return false;
  948. if (!value.value())
  949. return false;
  950. auto result = const_cast<AST::Value&>(*value.value()).resolve_as_list(const_cast<Shell&>(*this));
  951. if (result.is_error())
  952. return false;
  953. return result.value().contains_slow(command.argv[0]);
  954. }
  955. void Shell::restore_ios()
  956. {
  957. if (m_is_subshell)
  958. return;
  959. tcsetattr(0, TCSANOW, &termios);
  960. tcsetpgrp(STDOUT_FILENO, m_pid);
  961. tcsetpgrp(STDIN_FILENO, m_pid);
  962. }
  963. void Shell::block_on_pipeline(RefPtr<AST::Pipeline> pipeline)
  964. {
  965. if (!pipeline)
  966. return;
  967. for (auto& it : jobs) {
  968. if (auto cmd = it.value->command_ptr(); cmd->pipeline == pipeline && cmd->is_pipe_source)
  969. block_on_job(it.value);
  970. }
  971. }
  972. void Shell::block_on_job(RefPtr<Job> job)
  973. {
  974. TemporaryChange<Job*> current_job { m_current_job, job.ptr() };
  975. if (!job)
  976. return;
  977. if (job->is_suspended() && !job->shell_did_continue())
  978. return; // We cannot wait for a suspended job.
  979. ScopeGuard io_restorer { [&]() {
  980. if (job->exited() && !job->is_running_in_background()) {
  981. restore_ios();
  982. }
  983. } };
  984. bool job_exited { false };
  985. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  986. if (old_exit)
  987. old_exit(job);
  988. job_exited = true;
  989. };
  990. if (job->exited())
  991. return;
  992. while (!job_exited)
  993. Core::EventLoop::current().pump();
  994. // If the job is part of a pipeline, wait for the rest of the members too.
  995. if (auto command = job->command_ptr())
  996. block_on_pipeline(command->pipeline);
  997. }
  998. DeprecatedString Shell::get_history_path()
  999. {
  1000. if (auto histfile = getenv("HISTFILE"))
  1001. return { histfile };
  1002. return DeprecatedString::formatted("{}/.history", home);
  1003. }
  1004. DeprecatedString Shell::escape_token_for_single_quotes(StringView token)
  1005. {
  1006. // `foo bar \n '` -> `'foo bar \n '"'"`
  1007. StringBuilder builder;
  1008. builder.append("'"sv);
  1009. auto started_single_quote = true;
  1010. for (auto c : token) {
  1011. switch (c) {
  1012. case '\'':
  1013. builder.append("\"'\""sv);
  1014. started_single_quote = false;
  1015. continue;
  1016. default:
  1017. builder.append(c);
  1018. if (!started_single_quote) {
  1019. started_single_quote = true;
  1020. builder.append("'"sv);
  1021. }
  1022. break;
  1023. }
  1024. }
  1025. if (started_single_quote)
  1026. builder.append("'"sv);
  1027. return builder.to_deprecated_string();
  1028. }
  1029. DeprecatedString Shell::escape_token_for_double_quotes(StringView token)
  1030. {
  1031. // `foo bar \n $x 'blah "hello` -> `"foo bar \\n $x 'blah \"hello"`
  1032. StringBuilder builder;
  1033. builder.append('"');
  1034. for (auto c : token) {
  1035. switch (c) {
  1036. case '\"':
  1037. builder.append("\\\""sv);
  1038. continue;
  1039. case '\\':
  1040. builder.append("\\\\"sv);
  1041. continue;
  1042. default:
  1043. builder.append(c);
  1044. break;
  1045. }
  1046. }
  1047. builder.append('"');
  1048. return builder.to_deprecated_string();
  1049. }
  1050. Shell::SpecialCharacterEscapeMode Shell::special_character_escape_mode(u32 code_point, EscapeMode mode)
  1051. {
  1052. switch (code_point) {
  1053. case '\'':
  1054. if (mode == EscapeMode::DoubleQuotedString)
  1055. return SpecialCharacterEscapeMode::Untouched;
  1056. return SpecialCharacterEscapeMode::Escaped;
  1057. case '"':
  1058. case '$':
  1059. case '\\':
  1060. if (mode == EscapeMode::SingleQuotedString)
  1061. return SpecialCharacterEscapeMode::Untouched;
  1062. return SpecialCharacterEscapeMode::Escaped;
  1063. case '|':
  1064. case '>':
  1065. case '<':
  1066. case '(':
  1067. case ')':
  1068. case '{':
  1069. case '}':
  1070. case '&':
  1071. case ';':
  1072. case '?':
  1073. case '*':
  1074. case ' ':
  1075. if (mode == EscapeMode::SingleQuotedString || mode == EscapeMode::DoubleQuotedString)
  1076. return SpecialCharacterEscapeMode::Untouched;
  1077. return SpecialCharacterEscapeMode::Escaped;
  1078. case '\n':
  1079. case '\t':
  1080. case '\r':
  1081. return SpecialCharacterEscapeMode::QuotedAsEscape;
  1082. default:
  1083. // FIXME: Should instead use unicode's "graphic" property (categories L, M, N, P, S, Zs)
  1084. if (is_ascii(code_point))
  1085. return is_ascii_printable(code_point) ? SpecialCharacterEscapeMode::Untouched : SpecialCharacterEscapeMode::QuotedAsHex;
  1086. return SpecialCharacterEscapeMode::Untouched;
  1087. }
  1088. }
  1089. static DeprecatedString do_escape(Shell::EscapeMode escape_mode, auto& token)
  1090. {
  1091. StringBuilder builder;
  1092. for (auto c : token) {
  1093. static_assert(sizeof(c) == sizeof(u32) || sizeof(c) == sizeof(u8));
  1094. switch (Shell::special_character_escape_mode(c, escape_mode)) {
  1095. case Shell::SpecialCharacterEscapeMode::Untouched:
  1096. if constexpr (sizeof(c) == sizeof(u8))
  1097. builder.append(c);
  1098. else
  1099. builder.append(Utf32View { &c, 1 });
  1100. break;
  1101. case Shell::SpecialCharacterEscapeMode::Escaped:
  1102. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1103. builder.append("'"sv);
  1104. builder.append('\\');
  1105. builder.append(c);
  1106. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1107. builder.append("'"sv);
  1108. break;
  1109. case Shell::SpecialCharacterEscapeMode::QuotedAsEscape:
  1110. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1111. builder.append("'"sv);
  1112. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1113. builder.append("\""sv);
  1114. switch (c) {
  1115. case '\n':
  1116. builder.append(R"(\n)"sv);
  1117. break;
  1118. case '\t':
  1119. builder.append(R"(\t)"sv);
  1120. break;
  1121. case '\r':
  1122. builder.append(R"(\r)"sv);
  1123. break;
  1124. default:
  1125. VERIFY_NOT_REACHED();
  1126. }
  1127. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1128. builder.append("\""sv);
  1129. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1130. builder.append("'"sv);
  1131. break;
  1132. case Shell::SpecialCharacterEscapeMode::QuotedAsHex:
  1133. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1134. builder.append("'"sv);
  1135. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1136. builder.append("\""sv);
  1137. if (c <= NumericLimits<u8>::max())
  1138. builder.appendff(R"(\x{:0>2x})", static_cast<u8>(c));
  1139. else
  1140. builder.appendff(R"(\u{:0>8x})", static_cast<u32>(c));
  1141. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1142. builder.append("\""sv);
  1143. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1144. builder.append("'"sv);
  1145. break;
  1146. }
  1147. }
  1148. return builder.to_deprecated_string();
  1149. }
  1150. DeprecatedString Shell::escape_token(Utf32View token, EscapeMode escape_mode)
  1151. {
  1152. return do_escape(escape_mode, token);
  1153. }
  1154. DeprecatedString Shell::escape_token(StringView token, EscapeMode escape_mode)
  1155. {
  1156. Utf8View view { token };
  1157. if (view.validate())
  1158. return do_escape(escape_mode, view);
  1159. return do_escape(escape_mode, token);
  1160. }
  1161. DeprecatedString Shell::unescape_token(StringView token)
  1162. {
  1163. StringBuilder builder;
  1164. enum {
  1165. Free,
  1166. Escaped
  1167. } state { Free };
  1168. for (auto c : token) {
  1169. switch (state) {
  1170. case Escaped:
  1171. builder.append(c);
  1172. state = Free;
  1173. break;
  1174. case Free:
  1175. if (c == '\\')
  1176. state = Escaped;
  1177. else
  1178. builder.append(c);
  1179. break;
  1180. }
  1181. }
  1182. if (state == Escaped)
  1183. builder.append('\\');
  1184. return builder.to_deprecated_string();
  1185. }
  1186. void Shell::cache_path()
  1187. {
  1188. if (!m_is_interactive)
  1189. return;
  1190. if (!cached_path.is_empty())
  1191. cached_path.clear_with_capacity();
  1192. // Add shell builtins to the cache.
  1193. for (auto const& builtin_name : builtin_names)
  1194. cached_path.append({ RunnablePath::Kind::Builtin, escape_token(builtin_name) });
  1195. // Add functions to the cache.
  1196. for (auto& function : m_functions) {
  1197. auto name = escape_token(function.key);
  1198. if (cached_path.contains_slow(name))
  1199. continue;
  1200. cached_path.append({ RunnablePath::Kind::Function, name });
  1201. }
  1202. // Add aliases to the cache.
  1203. for (auto const& alias : m_aliases) {
  1204. auto name = escape_token(alias.key);
  1205. if (cached_path.contains_slow(name))
  1206. continue;
  1207. cached_path.append({ RunnablePath::Kind::Alias, name });
  1208. }
  1209. // TODO: Can we make this rely on Core::System::resolve_executable_from_environment()?
  1210. DeprecatedString path = getenv("PATH");
  1211. if (!path.is_empty()) {
  1212. auto directories = path.split(':');
  1213. for (auto const& directory : directories) {
  1214. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1215. while (programs.has_next()) {
  1216. auto program = programs.next_path();
  1217. auto program_path = DeprecatedString::formatted("{}/{}", directory, program);
  1218. auto escaped_name = escape_token(program);
  1219. if (cached_path.contains_slow(escaped_name))
  1220. continue;
  1221. if (access(program_path.characters(), X_OK) == 0)
  1222. cached_path.append({ RunnablePath::Kind::Executable, escaped_name });
  1223. }
  1224. }
  1225. }
  1226. quick_sort(cached_path);
  1227. }
  1228. void Shell::add_entry_to_cache(RunnablePath const& entry)
  1229. {
  1230. size_t index = 0;
  1231. auto match = binary_search(cached_path.span(), entry, &index, RunnablePathComparator {});
  1232. if (match)
  1233. return;
  1234. while (index < cached_path.size() && strcmp(cached_path[index].path.characters(), entry.path.characters()) < 0) {
  1235. index++;
  1236. }
  1237. cached_path.insert(index, entry);
  1238. }
  1239. void Shell::remove_entry_from_cache(StringView entry)
  1240. {
  1241. size_t index { 0 };
  1242. auto match = binary_search(cached_path.span(), entry, &index, RunnablePathComparator {});
  1243. if (match)
  1244. cached_path.remove(index);
  1245. }
  1246. ErrorOr<void> Shell::highlight(Line::Editor& editor) const
  1247. {
  1248. auto line = editor.line();
  1249. auto ast = parse(line, m_is_interactive);
  1250. if (!ast)
  1251. return {};
  1252. return ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  1253. }
  1254. Vector<Line::CompletionSuggestion> Shell::complete()
  1255. {
  1256. m_completion_stack_info = {};
  1257. return complete(m_editor->line(m_editor->cursor()));
  1258. }
  1259. Vector<Line::CompletionSuggestion> Shell::complete(StringView line)
  1260. {
  1261. auto ast = parse(line, m_is_interactive);
  1262. if (!ast)
  1263. return {};
  1264. return ast->complete_for_editor(*this, line.length()).release_value_but_fixme_should_propagate_errors();
  1265. }
  1266. Vector<Line::CompletionSuggestion> Shell::complete_path(StringView base, StringView part, size_t offset, ExecutableOnly executable_only, AST::Node const* command_node, AST::Node const* node, EscapeMode escape_mode)
  1267. {
  1268. auto token = offset ? part.substring_view(0, offset) : ""sv;
  1269. DeprecatedString path;
  1270. ssize_t last_slash = token.length() - 1;
  1271. while (last_slash >= 0 && token[last_slash] != '/')
  1272. --last_slash;
  1273. if (command_node) {
  1274. auto program_results = complete_via_program_itself(offset, command_node, node, escape_mode, {});
  1275. if (!program_results.is_error())
  1276. return program_results.release_value();
  1277. }
  1278. StringBuilder path_builder;
  1279. auto init_slash_part = token.substring_view(0, last_slash + 1);
  1280. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  1281. bool allow_direct_children = true;
  1282. // Depending on the base, we will have to prepend cwd.
  1283. if (base.is_empty()) {
  1284. // '' /foo -> absolute
  1285. // '' foo -> relative
  1286. if (!token.starts_with('/'))
  1287. path_builder.append(cwd);
  1288. path_builder.append('/');
  1289. path_builder.append(init_slash_part);
  1290. if (executable_only == ExecutableOnly::Yes && init_slash_part.is_empty())
  1291. allow_direct_children = false;
  1292. } else {
  1293. // /foo * -> absolute
  1294. // foo * -> relative
  1295. if (!base.starts_with('/'))
  1296. path_builder.append(cwd);
  1297. path_builder.append('/');
  1298. path_builder.append(base);
  1299. path_builder.append('/');
  1300. path_builder.append(init_slash_part);
  1301. }
  1302. path = path_builder.to_deprecated_string();
  1303. token = last_slash_part;
  1304. // the invariant part of the token is actually just the last segment
  1305. // e. in `cd /foo/bar', 'bar' is the invariant
  1306. // since we are not suggesting anything starting with
  1307. // `/foo/', but rather just `bar...'
  1308. auto token_length = escape_token(token, escape_mode).length();
  1309. size_t static_offset = 0;
  1310. auto invariant_offset = token_length;
  1311. if (m_editor)
  1312. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1313. // only suggest dot-files if path starts with a dot
  1314. Core::DirIterator files(path,
  1315. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1316. Vector<Line::CompletionSuggestion> suggestions;
  1317. while (files.has_next()) {
  1318. auto file = files.next_path();
  1319. if (file.starts_with(token)) {
  1320. struct stat program_status;
  1321. auto file_path = DeprecatedString::formatted("{}/{}", path, file);
  1322. int stat_error = stat(file_path.characters(), &program_status);
  1323. if (!stat_error && (executable_only == ExecutableOnly::No || access(file_path.characters(), X_OK) == 0)) {
  1324. if (S_ISDIR(program_status.st_mode)) {
  1325. suggestions.append({ escape_token(file, escape_mode), "/"sv });
  1326. } else {
  1327. if (!allow_direct_children && !file.contains('/'))
  1328. continue;
  1329. suggestions.append({ escape_token(file, escape_mode), " "sv });
  1330. }
  1331. suggestions.last().input_offset = token_length;
  1332. suggestions.last().invariant_offset = invariant_offset;
  1333. suggestions.last().static_offset = static_offset;
  1334. }
  1335. }
  1336. }
  1337. // The results of DirIterator are in the order they appear on-disk.
  1338. // Instead, return suggestions in lexicographical order.
  1339. quick_sort(suggestions, [](auto& a, auto& b) { return a.text_string < b.text_string; });
  1340. return suggestions;
  1341. }
  1342. Vector<Line::CompletionSuggestion> Shell::complete_program_name(StringView name, size_t offset, EscapeMode escape_mode)
  1343. {
  1344. auto match = binary_search(
  1345. cached_path.span(),
  1346. name,
  1347. nullptr,
  1348. [](auto& name, auto& program) {
  1349. return strncmp(
  1350. name.characters_without_null_termination(),
  1351. program.path.characters(),
  1352. name.length());
  1353. });
  1354. if (!match)
  1355. return complete_path(""sv, name, offset, ExecutableOnly::Yes, nullptr, nullptr, escape_mode);
  1356. DeprecatedString completion = match->path;
  1357. auto token_length = escape_token(name, escape_mode).length();
  1358. auto invariant_offset = token_length;
  1359. size_t static_offset = 0;
  1360. if (m_editor)
  1361. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1362. // Now that we have a program name starting with our token, we look at
  1363. // other program names starting with our token and cut off any mismatching
  1364. // characters.
  1365. Vector<Line::CompletionSuggestion> suggestions;
  1366. int index = match - cached_path.data();
  1367. for (int i = index - 1; i >= 0 && cached_path[i].path.starts_with(name); --i)
  1368. suggestions.append({ cached_path[i].path, " "sv });
  1369. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].path.starts_with(name); ++i)
  1370. suggestions.append({ cached_path[i].path, " "sv });
  1371. suggestions.append({ cached_path[index].path, " "sv });
  1372. for (auto& entry : suggestions) {
  1373. entry.input_offset = token_length;
  1374. entry.invariant_offset = invariant_offset;
  1375. entry.static_offset = static_offset;
  1376. }
  1377. return suggestions;
  1378. }
  1379. Vector<Line::CompletionSuggestion> Shell::complete_variable(StringView name, size_t offset)
  1380. {
  1381. Vector<Line::CompletionSuggestion> suggestions;
  1382. auto pattern = offset ? name.substring_view(0, offset) : ""sv;
  1383. auto invariant_offset = offset;
  1384. size_t static_offset = 0;
  1385. if (m_editor)
  1386. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1387. // Look at local variables.
  1388. for (auto& frame : m_local_frames) {
  1389. for (auto& variable : frame->local_variables) {
  1390. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1391. suggestions.append(variable.key);
  1392. }
  1393. }
  1394. // Look at the environment.
  1395. for (auto i = 0; environ[i]; ++i) {
  1396. StringView entry { environ[i], strlen(environ[i]) };
  1397. if (entry.starts_with(pattern)) {
  1398. auto parts = entry.split_view('=');
  1399. if (parts.is_empty() || parts.first().is_empty())
  1400. continue;
  1401. DeprecatedString name = parts.first();
  1402. if (suggestions.contains_slow(name))
  1403. continue;
  1404. suggestions.append(move(name));
  1405. }
  1406. }
  1407. for (auto& entry : suggestions) {
  1408. entry.input_offset = offset;
  1409. entry.invariant_offset = invariant_offset;
  1410. entry.static_offset = static_offset;
  1411. }
  1412. return suggestions;
  1413. }
  1414. Vector<Line::CompletionSuggestion> Shell::complete_user(StringView name, size_t offset)
  1415. {
  1416. Vector<Line::CompletionSuggestion> suggestions;
  1417. auto pattern = offset ? name.substring_view(0, offset) : ""sv;
  1418. auto invariant_offset = offset;
  1419. size_t static_offset = 0;
  1420. if (m_editor)
  1421. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1422. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1423. if (di.has_error())
  1424. return suggestions;
  1425. while (di.has_next()) {
  1426. DeprecatedString name = di.next_path();
  1427. if (name.starts_with(pattern)) {
  1428. suggestions.append(name);
  1429. auto& suggestion = suggestions.last();
  1430. suggestion.input_offset = offset;
  1431. suggestion.invariant_offset = invariant_offset;
  1432. suggestion.static_offset = static_offset;
  1433. }
  1434. }
  1435. return suggestions;
  1436. }
  1437. Vector<Line::CompletionSuggestion> Shell::complete_option(StringView program_name, StringView option, size_t offset, AST::Node const* command_node, AST::Node const* node)
  1438. {
  1439. if (command_node) {
  1440. auto program_results = complete_via_program_itself(offset, command_node, node, EscapeMode::Bareword, program_name);
  1441. if (!program_results.is_error())
  1442. return program_results.release_value();
  1443. }
  1444. size_t start = 0;
  1445. while (start < option.length() && option[start] == '-' && start < 2)
  1446. ++start;
  1447. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : ""sv;
  1448. auto invariant_offset = offset;
  1449. size_t static_offset = 0;
  1450. if (m_editor)
  1451. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1452. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1453. return {};
  1454. }
  1455. ErrorOr<Vector<Line::CompletionSuggestion>> Shell::complete_via_program_itself(size_t, AST::Node const* command_node, AST::Node const* node, EscapeMode, StringView known_program_name)
  1456. {
  1457. if (!command_node)
  1458. return Error::from_string_literal("Cannot complete null command");
  1459. if (command_node->would_execute())
  1460. return Error::from_string_literal("Refusing to complete nodes that would execute");
  1461. String program_name_storage;
  1462. if (known_program_name.is_null()) {
  1463. auto node = command_node->leftmost_trivial_literal();
  1464. if (!node)
  1465. return Error::from_string_literal("Cannot complete");
  1466. program_name_storage = TRY(TRY(const_cast<AST::Node&>(*node).run(*this))->resolve_as_string(*this));
  1467. known_program_name = program_name_storage;
  1468. }
  1469. AST::Command completion_command;
  1470. completion_command.argv.append(program_name_storage);
  1471. completion_command = TRY(expand_aliases({ completion_command })).last();
  1472. auto completion_utility_name = TRY(String::formatted("_complete_{}", completion_command.argv[0]));
  1473. if (binary_search(cached_path.span(), completion_utility_name, nullptr, RunnablePathComparator {}) != nullptr)
  1474. completion_command.argv[0] = completion_utility_name;
  1475. else if (!options.invoke_program_for_autocomplete)
  1476. return Error::from_string_literal("Refusing to use the program itself as completion source");
  1477. completion_command.argv.extend({ "--complete"_string, "--"_string });
  1478. struct Visitor : public AST::NodeVisitor {
  1479. Visitor(Shell& shell, AST::Position position)
  1480. : shell(shell)
  1481. , completion_position(position)
  1482. {
  1483. lists.empend();
  1484. }
  1485. Shell& shell;
  1486. AST::Position completion_position;
  1487. Vector<Vector<String>> lists;
  1488. bool fail { false };
  1489. void push_list() { lists.empend(); }
  1490. Vector<String> pop_list() { return lists.take_last(); }
  1491. Vector<String>& list() { return lists.last(); }
  1492. bool should_include(AST::Node const* node) const { return node->position().end_offset <= completion_position.end_offset; }
  1493. virtual void visit(AST::BarewordLiteral const* node) override
  1494. {
  1495. if (should_include(node))
  1496. list().append(node->text());
  1497. }
  1498. virtual void visit(AST::BraceExpansion const* node) override
  1499. {
  1500. if (should_include(node)) {
  1501. auto value = static_cast<AST::Node*>(const_cast<AST::BraceExpansion*>(node))->run(shell).release_value_but_fixme_should_propagate_errors();
  1502. auto entries = value->resolve_as_list(shell).release_value_but_fixme_should_propagate_errors();
  1503. list().extend(move(entries));
  1504. }
  1505. }
  1506. virtual void visit(AST::CommandLiteral const* node) override
  1507. {
  1508. if (should_include(node))
  1509. list().extend(node->command().argv);
  1510. }
  1511. virtual void visit(AST::DynamicEvaluate const* node) override
  1512. {
  1513. if (should_include(node))
  1514. fail = true;
  1515. }
  1516. virtual void visit(AST::DoubleQuotedString const* node) override
  1517. {
  1518. if (!should_include(node))
  1519. return;
  1520. push_list();
  1521. AST::NodeVisitor::visit(node);
  1522. auto list = pop_list();
  1523. StringBuilder builder;
  1524. builder.join(""sv, list);
  1525. this->list().append(builder.to_string().release_value_but_fixme_should_propagate_errors());
  1526. }
  1527. virtual void visit(AST::Glob const* node) override
  1528. {
  1529. if (should_include(node))
  1530. list().append(node->text());
  1531. }
  1532. virtual void visit(AST::Heredoc const* node) override
  1533. {
  1534. if (!should_include(node))
  1535. return;
  1536. push_list();
  1537. AST::NodeVisitor::visit(node);
  1538. auto list = pop_list();
  1539. StringBuilder builder;
  1540. builder.join(""sv, list);
  1541. this->list().append(builder.to_string().release_value_but_fixme_should_propagate_errors());
  1542. }
  1543. virtual void visit(AST::ImmediateExpression const* node) override
  1544. {
  1545. if (should_include(node))
  1546. fail = true;
  1547. }
  1548. virtual void visit(AST::Range const* node) override
  1549. {
  1550. if (!should_include(node))
  1551. return;
  1552. push_list();
  1553. node->start()->visit(*this);
  1554. list().append(pop_list().first());
  1555. }
  1556. virtual void visit(AST::SimpleVariable const* node) override
  1557. {
  1558. if (should_include(node)) {
  1559. auto values = static_cast<AST::Node*>(const_cast<AST::SimpleVariable*>(node))->run(shell).release_value_but_fixme_should_propagate_errors();
  1560. auto entries = values->resolve_as_list(shell).release_value_but_fixme_should_propagate_errors();
  1561. list().extend(move(entries));
  1562. }
  1563. }
  1564. virtual void visit(AST::SpecialVariable const* node) override
  1565. {
  1566. if (should_include(node)) {
  1567. auto values = static_cast<AST::Node*>(const_cast<AST::SpecialVariable*>(node))->run(shell).release_value_but_fixme_should_propagate_errors();
  1568. auto entries = values->resolve_as_list(shell).release_value_but_fixme_should_propagate_errors();
  1569. list().extend(move(entries));
  1570. }
  1571. }
  1572. virtual void visit(AST::Juxtaposition const* node) override
  1573. {
  1574. if (!should_include(node))
  1575. return;
  1576. push_list();
  1577. node->left()->visit(*this);
  1578. auto left = pop_list();
  1579. push_list();
  1580. node->right()->visit(*this);
  1581. auto right = pop_list();
  1582. StringBuilder builder;
  1583. for (auto& left_entry : left) {
  1584. for (auto& right_entry : right) {
  1585. builder.append(left_entry);
  1586. builder.append(right_entry);
  1587. list().append(builder.to_string().release_value_but_fixme_should_propagate_errors());
  1588. builder.clear();
  1589. }
  1590. }
  1591. }
  1592. virtual void visit(AST::StringLiteral const* node) override
  1593. {
  1594. if (should_include(node))
  1595. list().append(node->text());
  1596. }
  1597. virtual void visit(AST::Tilde const* node) override
  1598. {
  1599. if (should_include(node)) {
  1600. auto values = static_cast<AST::Node*>(const_cast<AST::Tilde*>(node))->run(shell).release_value_but_fixme_should_propagate_errors();
  1601. auto entries = values->resolve_as_list(shell).release_value_but_fixme_should_propagate_errors();
  1602. list().extend(move(entries));
  1603. }
  1604. }
  1605. virtual void visit(AST::PathRedirectionNode const*) override { }
  1606. virtual void visit(AST::CloseFdRedirection const*) override { }
  1607. virtual void visit(AST::Fd2FdRedirection const*) override { }
  1608. virtual void visit(AST::Execute const*) override { }
  1609. virtual void visit(AST::ReadRedirection const*) override { }
  1610. virtual void visit(AST::ReadWriteRedirection const*) override { }
  1611. virtual void visit(AST::WriteAppendRedirection const*) override { }
  1612. virtual void visit(AST::WriteRedirection const*) override { }
  1613. } visitor { *this, node ? node->position() : AST::Position() };
  1614. command_node->visit(visitor);
  1615. if (visitor.fail)
  1616. return Error::from_string_literal("Cannot complete");
  1617. completion_command.argv.extend(visitor.list());
  1618. auto devnull = "/dev/null"_string;
  1619. completion_command.should_wait = true;
  1620. completion_command.redirections.append(AST::PathRedirection::create(devnull, STDERR_FILENO, AST::PathRedirection::Write));
  1621. completion_command.redirections.append(AST::PathRedirection::create(devnull, STDIN_FILENO, AST::PathRedirection::Read));
  1622. auto execute_node = make_ref_counted<AST::Execute>(
  1623. AST::Position {},
  1624. make_ref_counted<AST::CommandLiteral>(AST::Position {}, move(completion_command)),
  1625. true);
  1626. Vector<Line::CompletionSuggestion> suggestions;
  1627. auto timer = TRY(Core::Timer::create_single_shot(300, [&] {
  1628. Core::EventLoop::current().quit(1);
  1629. }));
  1630. timer->start();
  1631. // Restrict the process to effectively readonly access to the FS.
  1632. auto scoped_promise = promise({
  1633. .exec_promises = "stdio rpath prot_exec map_fixed no_error",
  1634. .unveils = {
  1635. { "/", "rx" },
  1636. },
  1637. });
  1638. {
  1639. TemporaryChange change(m_is_interactive, false);
  1640. TRY(execute_node->for_each_entry(*this, [&](NonnullRefPtr<AST::Value> entry) -> ErrorOr<IterationDecision> {
  1641. auto result = TRY(entry->resolve_as_string(*this));
  1642. JsonParser parser(result);
  1643. auto parsed_result = parser.parse();
  1644. if (parsed_result.is_error())
  1645. return IterationDecision::Continue;
  1646. auto parsed = parsed_result.release_value();
  1647. if (parsed.is_object()) {
  1648. auto& object = parsed.as_object();
  1649. auto kind = object.get_deprecated_string("kind"sv).value_or("plain");
  1650. if (kind == "path") {
  1651. auto base = object.get_deprecated_string("base"sv).value_or("");
  1652. auto part = object.get_deprecated_string("part"sv).value_or("");
  1653. auto executable_only = object.get_bool("executable_only"sv).value_or(false) ? ExecutableOnly::Yes : ExecutableOnly::No;
  1654. suggestions.extend(complete_path(base, part, part.length(), executable_only, nullptr, nullptr));
  1655. } else if (kind == "program") {
  1656. auto name = object.get_deprecated_string("name"sv).value_or("");
  1657. suggestions.extend(complete_program_name(name, name.length()));
  1658. } else if (kind == "proxy") {
  1659. if (m_completion_stack_info.size_free() < 4 * KiB) {
  1660. dbgln("Not enough stack space, recursion?");
  1661. return IterationDecision::Continue;
  1662. }
  1663. auto argv = object.get_deprecated_string("argv"sv).value_or("");
  1664. dbgln("Proxy completion for {}", argv);
  1665. suggestions.extend(complete(argv));
  1666. } else if (kind == "plain") {
  1667. Line::CompletionSuggestion suggestion {
  1668. object.get_deprecated_string("completion"sv).value_or(""),
  1669. object.get_deprecated_string("trailing_trivia"sv).value_or(""),
  1670. object.get_deprecated_string("display_trivia"sv).value_or(""),
  1671. };
  1672. suggestion.static_offset = object.get_u64("static_offset"sv).value_or(0);
  1673. suggestion.invariant_offset = object.get_u64("invariant_offset"sv).value_or(0);
  1674. suggestion.allow_commit_without_listing = object.get_bool("allow_commit_without_listing"sv).value_or(true);
  1675. suggestions.append(move(suggestion));
  1676. } else {
  1677. dbgln("LibLine: Unhandled completion kind: {}", kind);
  1678. }
  1679. } else {
  1680. suggestions.append(parsed.to_deprecated_string());
  1681. }
  1682. return IterationDecision::Continue;
  1683. }));
  1684. }
  1685. auto pgid = getpgrp();
  1686. tcsetpgrp(STDOUT_FILENO, pgid);
  1687. tcsetpgrp(STDIN_FILENO, pgid);
  1688. if (suggestions.is_empty())
  1689. return Error::from_string_literal("No results");
  1690. return suggestions;
  1691. }
  1692. Vector<Line::CompletionSuggestion> Shell::complete_immediate_function_name(StringView name, size_t offset)
  1693. {
  1694. Vector<Line::CompletionSuggestion> suggestions;
  1695. auto invariant_offset = offset;
  1696. size_t static_offset = 0;
  1697. if (m_editor)
  1698. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1699. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(fn_name) \
  1700. if (auto name_view = #fn_name##sv; name_view.starts_with(name)) \
  1701. suggestions.append({ name_view, " "sv });
  1702. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  1703. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  1704. for (auto& entry : suggestions) {
  1705. entry.input_offset = offset;
  1706. entry.invariant_offset = invariant_offset;
  1707. entry.static_offset = static_offset;
  1708. }
  1709. return suggestions;
  1710. }
  1711. void Shell::bring_cursor_to_beginning_of_a_line() const
  1712. {
  1713. struct winsize ws;
  1714. if (m_editor) {
  1715. ws = m_editor->terminal_size();
  1716. } else {
  1717. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1718. // Very annoying assumptions.
  1719. ws.ws_col = 80;
  1720. ws.ws_row = 25;
  1721. }
  1722. }
  1723. // Black with Cyan background.
  1724. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1725. auto eol_mark_ptr = getenv("PROMPT_EOL_MARK");
  1726. DeprecatedString eol_mark = eol_mark_ptr ?: default_mark;
  1727. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1728. if (eol_mark_length >= ws.ws_col) {
  1729. eol_mark = default_mark;
  1730. eol_mark_length = 1;
  1731. }
  1732. fputs(eol_mark.characters(), stderr);
  1733. // We write a line's worth of whitespace to the terminal. This way, we ensure that
  1734. // the prompt ends up on a new line even if there is dangling output on the current line.
  1735. size_t fill_count = ws.ws_col - eol_mark_length;
  1736. auto fill_buffer = DeprecatedString::repeated(' ', fill_count);
  1737. fwrite(fill_buffer.characters(), 1, fill_count, stderr);
  1738. putc('\r', stderr);
  1739. }
  1740. bool Shell::has_history_event(StringView source)
  1741. {
  1742. struct : public AST::NodeVisitor {
  1743. virtual void visit(const AST::HistoryEvent* node) override
  1744. {
  1745. has_history_event = true;
  1746. AST::NodeVisitor::visit(node);
  1747. }
  1748. bool has_history_event { false };
  1749. } visitor;
  1750. auto ast = Parser { source, true }.parse();
  1751. if (!ast)
  1752. return false;
  1753. ast->visit(visitor);
  1754. return visitor.has_history_event;
  1755. }
  1756. void Shell::setup_keybinds()
  1757. {
  1758. m_editor->register_key_input_callback('\n', [this](Line::Editor& editor) {
  1759. auto ast = parse(editor.line(), false);
  1760. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1761. return true;
  1762. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1763. });
  1764. }
  1765. void Shell::set_user_prompt()
  1766. {
  1767. if (!has_function("PROMPT"sv))
  1768. return;
  1769. if (!m_prompt_command_node)
  1770. m_prompt_command_node = Parser { "shell_set_active_prompt -- ${join \"\\n\" $(PROMPT)}"sv }.parse();
  1771. (void)m_prompt_command_node->run(this);
  1772. }
  1773. bool Shell::read_single_line()
  1774. {
  1775. while (true) {
  1776. set_user_prompt();
  1777. restore_ios();
  1778. bring_cursor_to_beginning_of_a_line();
  1779. m_editor->initialize();
  1780. setup_keybinds();
  1781. auto line_result = m_editor->get_line(prompt());
  1782. if (line_result.is_error()) {
  1783. auto is_eof = line_result.error() == Line::Editor::Error::Eof;
  1784. auto is_empty = line_result.error() == Line::Editor::Error::Empty;
  1785. if (is_eof || is_empty) {
  1786. // Pretend the user tried to execute builtin_exit()
  1787. auto exit_code = run_command("exit"sv);
  1788. if (exit_code != 0) {
  1789. // If we didn't end up actually calling exit(), and the command didn't succeed, just pretend it's all okay
  1790. // unless we can't, then just quit anyway.
  1791. if (!is_empty)
  1792. continue;
  1793. }
  1794. }
  1795. Core::EventLoop::current().quit(1);
  1796. return false;
  1797. }
  1798. auto& line = line_result.value();
  1799. if (line.is_empty())
  1800. return true;
  1801. run_command(line);
  1802. if (!has_history_event(line))
  1803. m_editor->add_to_history(line);
  1804. return true;
  1805. }
  1806. }
  1807. void Shell::custom_event(Core::CustomEvent& event)
  1808. {
  1809. if (event.custom_type() == ReadLine) {
  1810. if (read_single_line())
  1811. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1812. return;
  1813. }
  1814. }
  1815. void Shell::notify_child_event()
  1816. {
  1817. Vector<u64> disowned_jobs;
  1818. // Workaround the fact that we can't receive *who* exactly changed state.
  1819. // The child might still be alive (and even running) when this signal is dispatched to us
  1820. // so just...repeat until we find a suitable child.
  1821. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1822. // until the next child event we can actually handle, so stop after spending a total of 5110us (~5ms) on it.
  1823. bool found_child = false;
  1824. size_t const max_tries = 10;
  1825. size_t valid_attempts = max_tries;
  1826. useconds_t backoff_usec = 20;
  1827. int backoff_multiplier = 2;
  1828. for (;;) {
  1829. if (found_child || --valid_attempts == 0)
  1830. break;
  1831. // Ignore stray SIGCHLD when there are no jobs.
  1832. if (jobs.is_empty())
  1833. return;
  1834. if (valid_attempts < max_tries - 1) {
  1835. usleep(backoff_usec);
  1836. backoff_usec *= backoff_multiplier;
  1837. }
  1838. for (auto& it : jobs) {
  1839. auto job_id = it.key;
  1840. auto& job = *it.value;
  1841. int wstatus = 0;
  1842. dbgln_if(SH_DEBUG, "waitpid({} = {}) = ...", job.pid(), job.cmd());
  1843. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1844. dbgln_if(SH_DEBUG, "... = {} - exited: {}, suspended: {}", child_pid, WIFEXITED(wstatus), WIFSTOPPED(wstatus));
  1845. if (child_pid < 0) {
  1846. if (errno == ECHILD) {
  1847. // The child process went away before we could process its death, just assume it exited all ok.
  1848. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1849. child_pid = job.pid();
  1850. } else {
  1851. VERIFY_NOT_REACHED();
  1852. }
  1853. }
  1854. if (child_pid == 0) {
  1855. // If the child existed, but wasn't dead.
  1856. if (job.is_suspended() || job.shell_did_continue()) {
  1857. // The job was suspended, and someone sent it a SIGCONT.
  1858. job.set_is_suspended(false);
  1859. if (job.shell_did_continue())
  1860. job.set_shell_did_continue(false);
  1861. found_child = true;
  1862. }
  1863. continue;
  1864. }
  1865. if (child_pid == job.pid()) {
  1866. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1867. auto signal = WTERMSIG(wstatus);
  1868. job.set_signalled(signal);
  1869. if (signal == SIGINT)
  1870. raise_error(ShellError::InternalControlFlowInterrupted, "Interrupted"sv, job.command().position);
  1871. else if (signal == SIGKILL)
  1872. raise_error(ShellError::InternalControlFlowKilled, "Interrupted"sv, job.command().position);
  1873. } else if (WIFEXITED(wstatus)) {
  1874. job.set_has_exit(WEXITSTATUS(wstatus));
  1875. } else if (WIFSTOPPED(wstatus)) {
  1876. job.unblock();
  1877. job.set_is_suspended(true);
  1878. }
  1879. found_child = true;
  1880. }
  1881. if (job.should_be_disowned())
  1882. disowned_jobs.append(job_id);
  1883. }
  1884. for (auto job_id : disowned_jobs) {
  1885. jobs.remove(job_id);
  1886. }
  1887. }
  1888. }
  1889. Shell::Shell()
  1890. : m_default_constructed(true)
  1891. {
  1892. push_frame("main", LocalFrameKind::FunctionOrGlobal).leak_frame();
  1893. int rc = gethostname(hostname, Shell::HostNameSize);
  1894. if (rc < 0)
  1895. perror("gethostname");
  1896. {
  1897. auto* pw = getpwuid(getuid());
  1898. if (pw) {
  1899. username = pw->pw_name;
  1900. home = pw->pw_dir;
  1901. setenv("HOME", pw->pw_dir, 1);
  1902. }
  1903. endpwent();
  1904. }
  1905. // For simplicity, start at the user's home directory.
  1906. this->cwd = home;
  1907. setenv("PWD", home.characters(), 1);
  1908. // Add the default PATH vars.
  1909. {
  1910. StringBuilder path;
  1911. auto const* path_env_ptr = getenv("PATH");
  1912. if (path_env_ptr != NULL)
  1913. path.append({ path_env_ptr, strlen(path_env_ptr) });
  1914. if (path.length())
  1915. path.append(":"sv);
  1916. path.append(DEFAULT_PATH_SV);
  1917. setenv("PATH", path.to_deprecated_string().characters(), true);
  1918. }
  1919. cache_path();
  1920. }
  1921. void Shell::initialize(bool attempt_interactive)
  1922. {
  1923. uid = getuid();
  1924. tcsetpgrp(0, getpgrp());
  1925. m_pid = getpid();
  1926. push_frame("main", LocalFrameKind::FunctionOrGlobal).leak_frame();
  1927. int rc = gethostname(hostname, Shell::HostNameSize);
  1928. if (rc < 0)
  1929. perror("gethostname");
  1930. auto istty = isatty(STDIN_FILENO);
  1931. m_is_interactive = attempt_interactive && istty;
  1932. if (istty) {
  1933. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1934. if (rc < 0)
  1935. perror("ttyname_r");
  1936. } else {
  1937. ttyname[0] = 0;
  1938. }
  1939. {
  1940. auto* cwd = getcwd(nullptr, 0);
  1941. this->cwd = cwd;
  1942. setenv("PWD", cwd, 1);
  1943. free(cwd);
  1944. }
  1945. {
  1946. auto* pw = getpwuid(getuid());
  1947. if (pw) {
  1948. username = pw->pw_name;
  1949. home = pw->pw_dir;
  1950. setenv("HOME", pw->pw_dir, 1);
  1951. }
  1952. endpwent();
  1953. }
  1954. directory_stack.append(cwd);
  1955. if (m_is_interactive) {
  1956. m_editor->load_history(get_history_path());
  1957. cache_path();
  1958. }
  1959. }
  1960. Shell::Shell(Line::Editor& editor, bool attempt_interactive, bool posix_mode)
  1961. : m_in_posix_mode(posix_mode)
  1962. , m_editor(editor)
  1963. {
  1964. initialize(attempt_interactive);
  1965. start_timer(3000);
  1966. }
  1967. Shell::~Shell()
  1968. {
  1969. destroy();
  1970. }
  1971. void Shell::destroy()
  1972. {
  1973. if (m_default_constructed)
  1974. return;
  1975. stop_all_jobs();
  1976. if (!m_is_interactive)
  1977. return;
  1978. m_editor->save_history(get_history_path());
  1979. }
  1980. void Shell::stop_all_jobs()
  1981. {
  1982. if (!jobs.is_empty()) {
  1983. if (m_is_interactive && !m_is_subshell)
  1984. printf("Killing active jobs\n");
  1985. for (auto& entry : jobs) {
  1986. if (entry.value->is_suspended()) {
  1987. dbgln_if(SH_DEBUG, "Job {} is suspended", entry.value->pid());
  1988. kill_job(entry.value, SIGCONT);
  1989. }
  1990. kill_job(entry.value, SIGHUP);
  1991. }
  1992. usleep(10000); // Wait for a bit before killing the job
  1993. for (auto& entry : jobs) {
  1994. dbgln_if(SH_DEBUG, "Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1995. kill_job(entry.value, SIGKILL);
  1996. }
  1997. jobs.clear();
  1998. }
  1999. }
  2000. u64 Shell::find_last_job_id() const
  2001. {
  2002. u64 job_id = 0;
  2003. for (auto& entry : jobs) {
  2004. if (entry.value->job_id() > job_id)
  2005. job_id = entry.value->job_id();
  2006. }
  2007. return job_id;
  2008. }
  2009. Job* Shell::find_job(u64 id, bool is_pid)
  2010. {
  2011. for (auto& entry : jobs) {
  2012. if (is_pid) {
  2013. if (entry.value->pid() == static_cast<int>(id))
  2014. return entry.value;
  2015. } else {
  2016. if (entry.value->job_id() == id)
  2017. return entry.value;
  2018. }
  2019. }
  2020. return nullptr;
  2021. }
  2022. void Shell::kill_job(Job const* job, int sig)
  2023. {
  2024. if (!job)
  2025. return;
  2026. if (killpg(job->pgid(), sig) < 0) {
  2027. if (kill(job->pid(), sig) < 0) {
  2028. if (errno != ESRCH)
  2029. perror("kill");
  2030. }
  2031. }
  2032. }
  2033. void Shell::possibly_print_error() const
  2034. {
  2035. switch (m_error) {
  2036. case ShellError::EvaluatedSyntaxError:
  2037. warnln("Shell Syntax Error: {}", m_error_description);
  2038. break;
  2039. case ShellError::InvalidSliceContentsError:
  2040. case ShellError::InvalidGlobError:
  2041. case ShellError::NonExhaustiveMatchRules:
  2042. warnln("Shell: {}", m_error_description);
  2043. break;
  2044. case ShellError::OpenFailure:
  2045. warnln("Shell: Open failed for {}", m_error_description);
  2046. break;
  2047. case ShellError::OutOfMemory:
  2048. warnln("Shell: Hit an OOM situation");
  2049. break;
  2050. case ShellError::LaunchError:
  2051. warnln("Shell: {}", m_error_description);
  2052. break;
  2053. case ShellError::PipeFailure:
  2054. warnln("Shell: pipe() failed for {}", m_error_description);
  2055. break;
  2056. case ShellError::WriteFailure:
  2057. warnln("Shell: write() failed for {}", m_error_description);
  2058. break;
  2059. case ShellError::InternalControlFlowBreak:
  2060. case ShellError::InternalControlFlowContinue:
  2061. case ShellError::InternalControlFlowReturn:
  2062. case ShellError::InternalControlFlowInterrupted:
  2063. case ShellError::InternalControlFlowKilled:
  2064. return;
  2065. case ShellError::None:
  2066. return;
  2067. }
  2068. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  2069. auto& source_position = m_source_position.value();
  2070. auto do_line = [&](auto line, auto& current_line) {
  2071. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  2072. warnln("{:>3}| {}", line, current_line);
  2073. if (is_in_range) {
  2074. warn("\x1b[31m");
  2075. size_t length_written_so_far = 0;
  2076. if (line == (i64)source_position.position->start_line.line_number) {
  2077. warn("{:~>{}}", "", 5 + source_position.position->start_line.line_column);
  2078. length_written_so_far += source_position.position->start_line.line_column;
  2079. } else {
  2080. warn("{:~>{}}", "", 5);
  2081. }
  2082. if (line == (i64)source_position.position->end_line.line_number) {
  2083. warn("{:^>{}}", "", source_position.position->end_line.line_column - length_written_so_far);
  2084. length_written_so_far += source_position.position->start_line.line_column;
  2085. } else {
  2086. warn("{:^>{}}", "", current_line.length() - length_written_so_far);
  2087. }
  2088. warnln("\x1b[0m");
  2089. }
  2090. };
  2091. int line = -1;
  2092. // FIXME: Support arbitrarily long lines?
  2093. auto line_buf_or_error = ByteBuffer::create_uninitialized(4 * KiB);
  2094. if (line_buf_or_error.is_error()) {
  2095. warnln("Shell: Internal error while trying to display source information: {} (while allocating line buffer for {})", line_buf_or_error.error(), source_position.source_file);
  2096. return;
  2097. }
  2098. auto line_buf = line_buf_or_error.release_value();
  2099. StringView current_line;
  2100. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  2101. if (source_position.source_file.has_value()) {
  2102. auto file_or_error = Core::File::open(*source_position.source_file, Core::File::OpenMode::Read);
  2103. if (file_or_error.is_error()) {
  2104. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file_or_error.error(), *source_position.source_file);
  2105. return;
  2106. }
  2107. auto file = Core::InputBufferedFile::create(file_or_error.release_value());
  2108. while (line < line_to_skip_to) {
  2109. if (file.value()->is_eof())
  2110. return;
  2111. auto current_line_or_error = file.value()->read_line(line_buf);
  2112. if (current_line_or_error.is_error()) {
  2113. warnln("Shell: Internal error while trying to display source information: {} (while reading line {} of '{}')", current_line_or_error.error(), line, source_position.source_file);
  2114. return;
  2115. }
  2116. current_line = current_line_or_error.release_value();
  2117. ++line;
  2118. }
  2119. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  2120. do_line(line, current_line);
  2121. if (file.value()->is_eof()) {
  2122. current_line = ""sv;
  2123. } else {
  2124. auto current_line_or_error = file.value()->read_line(line_buf);
  2125. if (current_line_or_error.is_error()) {
  2126. warnln("Shell: Internal error while trying to display source information: {} (while reading line {} of '{}')", current_line_or_error.error(), line, source_position.source_file);
  2127. return;
  2128. }
  2129. current_line = current_line_or_error.release_value();
  2130. }
  2131. }
  2132. } else if (!source_position.literal_source_text.is_empty()) {
  2133. GenericLexer lexer { source_position.literal_source_text };
  2134. while (line < line_to_skip_to) {
  2135. if (lexer.is_eof())
  2136. return;
  2137. current_line = lexer.consume_line();
  2138. ++line;
  2139. }
  2140. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  2141. do_line(line, current_line);
  2142. if (lexer.is_eof())
  2143. current_line = ""sv;
  2144. else
  2145. current_line = lexer.consume_line();
  2146. }
  2147. }
  2148. }
  2149. warnln();
  2150. }
  2151. Optional<int> Shell::resolve_job_spec(StringView str)
  2152. {
  2153. if (!str.starts_with('%'))
  2154. return {};
  2155. // %number -> job id <number>
  2156. if (auto number = str.substring_view(1).to_uint(); number.has_value())
  2157. return number.value();
  2158. // '%?str' -> iterate jobs and pick one with `str' in its command
  2159. // Note: must be quoted, since '?' will turn it into a glob - pretty ugly...
  2160. GenericLexer lexer { str.substring_view(1) };
  2161. if (!lexer.consume_specific('?'))
  2162. return {};
  2163. auto search_term = lexer.remaining();
  2164. for (auto& it : jobs) {
  2165. if (it.value->cmd().contains(search_term))
  2166. return it.key;
  2167. }
  2168. return {};
  2169. }
  2170. void Shell::timer_event(Core::TimerEvent& event)
  2171. {
  2172. event.accept();
  2173. if (m_is_subshell)
  2174. return;
  2175. auto const* autosave_env_ptr = getenv("HISTORY_AUTOSAVE_TIME_MS");
  2176. auto option = autosave_env_ptr != NULL ? StringView { autosave_env_ptr, strlen(autosave_env_ptr) } : StringView {};
  2177. auto time = option.to_uint();
  2178. if (!time.has_value() || time.value() == 0) {
  2179. m_history_autosave_time.clear();
  2180. stop_timer();
  2181. start_timer(3000);
  2182. return;
  2183. }
  2184. if (m_history_autosave_time != time) {
  2185. m_history_autosave_time = time.value();
  2186. stop_timer();
  2187. start_timer(m_history_autosave_time.value());
  2188. }
  2189. if (!m_history_autosave_time.has_value())
  2190. return;
  2191. if (m_editor && m_editor->is_history_dirty())
  2192. m_editor->save_history(get_history_path());
  2193. }
  2194. RefPtr<AST::Node> Shell::parse(StringView input, bool interactive, bool as_command) const
  2195. {
  2196. if (m_in_posix_mode) {
  2197. Posix::Parser parser(input);
  2198. if (as_command) {
  2199. auto node = parser.parse();
  2200. if constexpr (SHELL_POSIX_PARSER_DEBUG) {
  2201. dbgln("Parsed with the POSIX Parser:");
  2202. (void)node->dump(0);
  2203. }
  2204. return node;
  2205. }
  2206. return parser.parse_word_list();
  2207. }
  2208. Parser parser { input, interactive };
  2209. if (as_command)
  2210. return parser.parse();
  2211. auto nodes = parser.parse_as_multiple_expressions();
  2212. return make_ref_counted<AST::ListConcatenate>(
  2213. nodes.is_empty() ? AST::Position { 0, 0, { 0, 0 }, { 0, 0 } } : nodes.first()->position(),
  2214. move(nodes));
  2215. }
  2216. void FileDescriptionCollector::collect()
  2217. {
  2218. for (auto fd : m_fds)
  2219. close(fd);
  2220. m_fds.clear();
  2221. }
  2222. FileDescriptionCollector::~FileDescriptionCollector()
  2223. {
  2224. collect();
  2225. }
  2226. void FileDescriptionCollector::add(int fd)
  2227. {
  2228. m_fds.append(fd);
  2229. }
  2230. SavedFileDescriptors::SavedFileDescriptors(Vector<NonnullRefPtr<AST::Rewiring>> const& intended_rewirings)
  2231. {
  2232. for (auto& rewiring : intended_rewirings) {
  2233. int new_fd = dup(rewiring->new_fd);
  2234. if (new_fd < 0) {
  2235. if (errno != EBADF)
  2236. perror("dup");
  2237. // The fd that will be overwritten isn't open right now,
  2238. // it will be cleaned up by the exec()-side collector
  2239. // and we have nothing to do here, so just ignore this error.
  2240. continue;
  2241. }
  2242. auto flags = fcntl(new_fd, F_GETFD);
  2243. auto rc = fcntl(new_fd, F_SETFD, flags | FD_CLOEXEC);
  2244. VERIFY(rc == 0);
  2245. m_saves.append({ rewiring->new_fd, new_fd });
  2246. m_collector.add(new_fd);
  2247. }
  2248. }
  2249. SavedFileDescriptors::~SavedFileDescriptors()
  2250. {
  2251. for (auto& save : m_saves) {
  2252. if (dup2(save.saved, save.original) < 0) {
  2253. perror("dup2(~SavedFileDescriptors)");
  2254. continue;
  2255. }
  2256. }
  2257. }
  2258. }