Shell.cpp 91 KB

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