Shell.cpp 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742
  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/StdLibExtras.h>
  19. #include <AK/StringBuilder.h>
  20. #include <AK/TemporaryChange.h>
  21. #include <AK/Tuple.h>
  22. #include <AK/URL.h>
  23. #include <LibCore/DateTime.h>
  24. #include <LibCore/DirIterator.h>
  25. #include <LibCore/Environment.h>
  26. #include <LibCore/Event.h>
  27. #include <LibCore/EventLoop.h>
  28. #include <LibCore/File.h>
  29. #include <LibCore/System.h>
  30. #include <LibCore/Timer.h>
  31. #include <LibFileSystem/FileSystem.h>
  32. #include <LibLine/Editor.h>
  33. #include <Shell/PosixParser.h>
  34. #include <errno.h>
  35. #include <fcntl.h>
  36. #include <inttypes.h>
  37. #include <pwd.h>
  38. #include <signal.h>
  39. #include <stdio.h>
  40. #include <stdlib.h>
  41. #include <string.h>
  42. #include <sys/mman.h>
  43. #include <sys/stat.h>
  44. #include <sys/utsname.h>
  45. #include <sys/wait.h>
  46. #include <termios.h>
  47. #include <unistd.h>
  48. static bool s_disable_hyperlinks = false;
  49. extern char** environ;
  50. namespace Shell {
  51. void Shell::setup_signals()
  52. {
  53. if (m_should_reinstall_signal_handlers) {
  54. Core::EventLoop::register_signal(SIGCHLD, [this](int) {
  55. dbgln_if(SH_DEBUG, "SIGCHLD!");
  56. notify_child_event();
  57. });
  58. Core::EventLoop::register_signal(SIGTSTP, [this](auto) {
  59. auto job = current_job();
  60. kill_job(job, SIGTSTP);
  61. if (job) {
  62. job->set_is_suspended(true);
  63. job->unblock();
  64. }
  65. });
  66. }
  67. }
  68. void Shell::print_path(StringView path)
  69. {
  70. if (s_disable_hyperlinks || !m_is_interactive || !isatty(STDOUT_FILENO)) {
  71. out("{}", path);
  72. return;
  73. }
  74. auto url = URL::create_with_file_scheme(path, {}, hostname);
  75. out("\033]8;;{}\033\\{}\033]8;;\033\\", url.serialize(), path);
  76. }
  77. ByteString Shell::prompt() const
  78. {
  79. if (m_next_scheduled_prompt_text.has_value())
  80. return m_next_scheduled_prompt_text.release_value();
  81. auto const* ps1 = getenv("PROMPT");
  82. if (!ps1) {
  83. if (uid == 0)
  84. return "# ";
  85. StringBuilder builder;
  86. builder.appendff("\033]0;{}@{}:{}\007", username, hostname, cwd);
  87. builder.appendff("\033[31;1m{}\033[0m@\033[37;1m{}\033[0m:\033[32;1m{}\033[0m$> ", username, hostname, cwd);
  88. return builder.to_byte_string();
  89. }
  90. StringBuilder builder;
  91. GenericLexer lexer { { ps1, strlen(ps1) } };
  92. while (!lexer.is_eof()) {
  93. builder.append(lexer.consume_until('\\'));
  94. if (!lexer.consume_specific('\\') || lexer.is_eof())
  95. break;
  96. if (lexer.consume_specific('X')) {
  97. builder.append("\033]0;"sv);
  98. } else if (lexer.consume_specific('a')) {
  99. builder.append(0x07);
  100. } else if (lexer.consume_specific('e')) {
  101. builder.append(0x1b);
  102. } else if (lexer.consume_specific('u')) {
  103. builder.append(username);
  104. } else if (lexer.consume_specific('h')) {
  105. builder.append({ hostname, strlen(hostname) });
  106. } else if (lexer.consume_specific('w') || lexer.consume_specific('W')) {
  107. ByteString const home_path = getenv("HOME");
  108. if (cwd.starts_with(home_path)) {
  109. builder.append('~');
  110. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  111. } else {
  112. builder.append(cwd);
  113. }
  114. } else if (auto const number_string = lexer.consume_while(is_ascii_digit); !number_string.is_empty()) {
  115. if (lexer.is_eof())
  116. break;
  117. auto const next_char = lexer.consume();
  118. if (next_char != 'w' && next_char != 'W')
  119. continue;
  120. auto const max_component_count = number_string.to_number<unsigned>().value();
  121. ByteString const home_path = getenv("HOME");
  122. auto const should_collapse_path = cwd.starts_with(home_path);
  123. auto const should_use_ellipsis = (next_char == 'w');
  124. auto const path = should_collapse_path ? cwd.substring_view(home_path.length(), cwd.length() - home_path.length())
  125. : cwd.view();
  126. auto const parts = path.split_view('/');
  127. auto const start_index = (max_component_count < parts.size()) ? parts.size() - max_component_count : 0;
  128. if (start_index == 0 || (start_index == 1 && should_use_ellipsis)) {
  129. if (should_collapse_path)
  130. builder.append('~');
  131. builder.append(path);
  132. continue;
  133. }
  134. if (should_use_ellipsis) {
  135. if (should_collapse_path)
  136. builder.append("~/"sv);
  137. builder.append(".../"sv);
  138. }
  139. for (auto i = start_index; i < parts.size(); ++i) {
  140. if (i != start_index)
  141. builder.append('/');
  142. builder.append(parts[i]);
  143. }
  144. } else if (lexer.consume_specific('p')) {
  145. builder.append(uid == 0 ? '#' : '$');
  146. } else if (lexer.consume_specific('t')) {
  147. builder.append(Core::DateTime::now().to_byte_string("%H:%M:%S"sv));
  148. } else if (lexer.consume_specific('T')) {
  149. builder.append(Core::DateTime::now().to_byte_string("%I:%M:%S"sv));
  150. } else if (lexer.consume_specific('@')) {
  151. builder.append(Core::DateTime::now().to_byte_string("%I:%M %p"sv));
  152. } else if (lexer.consume_specific("D{"sv)) {
  153. auto format = lexer.consume_until('}');
  154. if (!lexer.consume_specific('}'))
  155. continue;
  156. if (format.is_empty())
  157. format = "%y-%m-%d"sv;
  158. builder.append(Core::DateTime::now().to_byte_string(format));
  159. } else if (lexer.consume_specific('j')) {
  160. builder.appendff("{}", jobs.size());
  161. } else if (lexer.consume_specific('!')) {
  162. if (m_editor)
  163. builder.appendff("{}", m_editor->history().size() + 1);
  164. else
  165. builder.append('!');
  166. } else if (lexer.consume_specific('\\')) {
  167. builder.append('\\');
  168. } else {
  169. lexer.consume();
  170. }
  171. }
  172. return builder.to_byte_string();
  173. }
  174. ByteString Shell::expand_tilde(StringView expression)
  175. {
  176. VERIFY(expression.starts_with('~'));
  177. StringBuilder login_name;
  178. size_t first_slash_index = expression.length();
  179. for (size_t i = 1; i < expression.length(); ++i) {
  180. if (expression[i] == '/') {
  181. first_slash_index = i;
  182. break;
  183. }
  184. login_name.append(expression[i]);
  185. }
  186. StringBuilder path;
  187. for (size_t i = first_slash_index; i < expression.length(); ++i)
  188. path.append(expression[i]);
  189. if (login_name.is_empty()) {
  190. char const* home = getenv("HOME");
  191. if (!home) {
  192. auto passwd = getpwuid(getuid());
  193. VERIFY(passwd && passwd->pw_dir);
  194. return ByteString::formatted("{}/{}", passwd->pw_dir, path.to_byte_string());
  195. }
  196. return ByteString::formatted("{}/{}", home, path.to_byte_string());
  197. }
  198. auto passwd = getpwnam(login_name.to_byte_string().characters());
  199. if (!passwd)
  200. return expression;
  201. VERIFY(passwd->pw_dir);
  202. return ByteString::formatted("{}/{}", passwd->pw_dir, path.to_byte_string());
  203. }
  204. bool Shell::is_glob(StringView s)
  205. {
  206. for (size_t i = 0; i < s.length(); i++) {
  207. char c = s.characters_without_null_termination()[i];
  208. if (c == '*' || c == '?')
  209. return true;
  210. }
  211. return false;
  212. }
  213. ErrorOr<Vector<ByteString>> Shell::expand_globs(StringView path, StringView base)
  214. {
  215. auto explicitly_set_base = false;
  216. if (path.starts_with('/')) {
  217. base = "/"sv;
  218. explicitly_set_base = true;
  219. }
  220. auto parts = path.split_view('/', SplitBehavior::KeepTrailingSeparator);
  221. struct stat statbuf = TRY(Core::System::lstat(base));
  222. StringBuilder resolved_base_path_builder;
  223. resolved_base_path_builder.append(TRY(FileSystem::real_path(base)));
  224. if (S_ISDIR(statbuf.st_mode))
  225. resolved_base_path_builder.append('/');
  226. auto resolved_base = resolved_base_path_builder.string_view();
  227. auto results = expand_globs(move(parts), resolved_base);
  228. if (explicitly_set_base && base == "/")
  229. resolved_base = resolved_base.substring_view(1, resolved_base.length() - 1);
  230. for (auto& entry : results) {
  231. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  232. if (entry.is_empty())
  233. entry = ".";
  234. }
  235. // Make the output predictable and nice.
  236. quick_sort(results);
  237. return results;
  238. }
  239. Vector<ByteString> Shell::expand_globs(Vector<StringView> path_segments, StringView base)
  240. {
  241. if (path_segments.is_empty()) {
  242. ByteString base_str = base;
  243. struct stat statbuf;
  244. if (lstat(base_str.characters(), &statbuf) < 0)
  245. return {};
  246. return { move(base_str) };
  247. }
  248. auto first_segment = path_segments.take_first();
  249. if (is_glob(first_segment)) {
  250. Vector<ByteString> result;
  251. auto const is_glob_directory = first_segment.ends_with('/');
  252. if (is_glob_directory)
  253. first_segment = first_segment.substring_view(0, first_segment.length() - 1);
  254. Core::DirIterator di(base);
  255. if (di.has_error())
  256. return {};
  257. while (di.has_next()) {
  258. auto const entry = di.next().release_value();
  259. auto const path = entry.name;
  260. if (is_glob_directory && entry.type != Core::DirectoryEntry::Type::Directory)
  261. continue;
  262. // Dotfiles have to be explicitly requested
  263. if (path[0] == '.' && first_segment[0] != '.')
  264. continue;
  265. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  266. StringBuilder builder;
  267. builder.append(base);
  268. if (!base.ends_with('/'))
  269. builder.append('/');
  270. builder.append(path);
  271. if (is_glob_directory)
  272. builder.append('/');
  273. result.extend(expand_globs(path_segments, builder.string_view()));
  274. }
  275. }
  276. return result;
  277. } else {
  278. StringBuilder builder;
  279. builder.append(base);
  280. if (!base.ends_with('/'))
  281. builder.append('/');
  282. builder.append(first_segment);
  283. return expand_globs(move(path_segments), builder.string_view());
  284. }
  285. }
  286. ErrorOr<Vector<AST::Command>> Shell::expand_aliases(Vector<AST::Command> initial_commands)
  287. {
  288. Vector<AST::Command> commands;
  289. Function<ErrorOr<void>(AST::Command&)> resolve_aliases_and_append = [&](auto& command) -> ErrorOr<void> {
  290. if (!command.argv.is_empty()) {
  291. auto alias = resolve_alias(command.argv[0]);
  292. if (alias.has_value()) {
  293. auto argv0 = command.argv.take_first();
  294. auto subcommand_ast = parse(*alias, false);
  295. if (subcommand_ast) {
  296. while (subcommand_ast->is_execute()) {
  297. auto* ast = static_cast<AST::Execute*>(subcommand_ast.ptr());
  298. subcommand_ast = ast->command();
  299. }
  300. auto subcommand_nonnull = subcommand_ast.release_nonnull();
  301. NonnullRefPtr<AST::Node> substitute = adopt_ref(*new AST::Join(subcommand_nonnull->position(),
  302. subcommand_nonnull,
  303. adopt_ref(*new AST::CommandLiteral(subcommand_nonnull->position(), command))));
  304. auto res = TRY(substitute->run(*this));
  305. for (auto& subst_command : TRY(res->resolve_as_commands(*this))) {
  306. if (!subst_command.argv.is_empty() && subst_command.argv.first() == argv0) // Disallow an alias resolving to itself.
  307. commands.append(subst_command);
  308. else
  309. TRY(resolve_aliases_and_append(subst_command));
  310. }
  311. } else {
  312. commands.append(command);
  313. }
  314. } else {
  315. commands.append(command);
  316. }
  317. } else {
  318. commands.append(command);
  319. }
  320. return {};
  321. };
  322. for (auto& command : initial_commands)
  323. TRY(resolve_aliases_and_append(command));
  324. return commands;
  325. }
  326. ByteString Shell::resolve_path(ByteString path) const
  327. {
  328. if (!path.starts_with('/'))
  329. path = ByteString::formatted("{}/{}", cwd, path);
  330. return FileSystem::real_path(path).release_value_but_fixme_should_propagate_errors();
  331. }
  332. Shell::LocalFrame* Shell::find_frame_containing_local_variable(StringView name)
  333. {
  334. for (size_t i = m_local_frames.size(); i > 0; --i) {
  335. auto& frame = m_local_frames[i - 1];
  336. if (frame->local_variables.contains(name))
  337. return frame;
  338. }
  339. return nullptr;
  340. }
  341. ErrorOr<RefPtr<AST::Value const>> Shell::look_up_local_variable(StringView name) const
  342. {
  343. if (auto* frame = find_frame_containing_local_variable(name))
  344. return frame->local_variables.get(name).value();
  345. if (auto index = name.to_number<unsigned>(); index.has_value())
  346. return get_argument(index.value());
  347. return nullptr;
  348. }
  349. ErrorOr<RefPtr<AST::Value const>> Shell::get_argument(size_t index) const
  350. {
  351. if (index == 0) {
  352. auto current_script_string = TRY(String::from_byte_string(current_script));
  353. return adopt_ref(*new AST::StringValue(current_script_string));
  354. }
  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<ByteString> Shell::local_variable_or(StringView name, ByteString 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_byte_string();
  376. }
  377. return replacement;
  378. }
  379. void Shell::set_local_variable(ByteString 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(ByteString name, Vector<ByteString> 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<ByteString> 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, ByteString::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(ByteString::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. ByteString 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(ByteString 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<ByteString> 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<ByteString> 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<ByteString> copy_argv;
  663. argv.ensure_capacity(command.argv.size() + 1);
  664. for (auto& arg : command.argv) {
  665. copy_argv.append(arg.to_byte_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_byte_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<ByteString> 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_byte_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, ByteString::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(ByteString 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 = ByteString::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 = ByteString::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. ByteString Shell::get_history_path()
  1029. {
  1030. if (auto histfile = getenv("HISTFILE"))
  1031. return { histfile };
  1032. return ByteString::formatted("{}/.history", home);
  1033. }
  1034. ByteString 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_byte_string();
  1058. }
  1059. ByteString 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_byte_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. template<typename... Offsets>
  1120. static ByteString do_escape(Shell::EscapeMode escape_mode, auto& token, Offsets&... offsets)
  1121. {
  1122. StringBuilder builder;
  1123. size_t offset_from_original = 0;
  1124. auto set_offset = [&](auto& offset) {
  1125. offset.value() = builder.length();
  1126. offset.clear();
  1127. return true;
  1128. };
  1129. auto check_offset = [&](auto& offset) {
  1130. if (offset == offset_from_original)
  1131. set_offset(offset);
  1132. };
  1133. auto maybe_offsets = Tuple { Optional<Offsets&> { offsets }... };
  1134. auto check_offsets = [&] {
  1135. maybe_offsets.apply_as_args([&]<typename... Args>(Args&... args) {
  1136. (check_offset(args), ...);
  1137. });
  1138. };
  1139. for (auto c : token) {
  1140. static_assert(sizeof(c) == sizeof(u32) || sizeof(c) == sizeof(u8));
  1141. check_offsets();
  1142. offset_from_original++;
  1143. switch (Shell::special_character_escape_mode(c, escape_mode)) {
  1144. case Shell::SpecialCharacterEscapeMode::Untouched:
  1145. if constexpr (sizeof(c) == sizeof(u8))
  1146. builder.append(c);
  1147. else
  1148. builder.append(Utf32View { &c, 1 });
  1149. break;
  1150. case Shell::SpecialCharacterEscapeMode::Escaped:
  1151. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1152. builder.append("'"sv);
  1153. builder.append('\\');
  1154. builder.append(c);
  1155. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1156. builder.append("'"sv);
  1157. break;
  1158. case Shell::SpecialCharacterEscapeMode::QuotedAsEscape:
  1159. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1160. builder.append("'"sv);
  1161. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1162. builder.append("\""sv);
  1163. switch (c) {
  1164. case '\n':
  1165. builder.append(R"(\n)"sv);
  1166. break;
  1167. case '\t':
  1168. builder.append(R"(\t)"sv);
  1169. break;
  1170. case '\r':
  1171. builder.append(R"(\r)"sv);
  1172. break;
  1173. default:
  1174. VERIFY_NOT_REACHED();
  1175. }
  1176. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1177. builder.append("\""sv);
  1178. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1179. builder.append("'"sv);
  1180. break;
  1181. case Shell::SpecialCharacterEscapeMode::QuotedAsHex:
  1182. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1183. builder.append("'"sv);
  1184. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1185. builder.append("\""sv);
  1186. if (c <= NumericLimits<u8>::max())
  1187. builder.appendff(R"(\x{:0>2x})", static_cast<u8>(c));
  1188. else
  1189. builder.appendff(R"(\u{:0>8x})", static_cast<u32>(c));
  1190. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1191. builder.append("\""sv);
  1192. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1193. builder.append("'"sv);
  1194. break;
  1195. }
  1196. }
  1197. check_offsets();
  1198. return builder.to_byte_string();
  1199. }
  1200. ByteString Shell::escape_token(Utf32View token, EscapeMode escape_mode)
  1201. {
  1202. return do_escape(escape_mode, token);
  1203. }
  1204. ByteString Shell::escape_token(StringView token, EscapeMode escape_mode)
  1205. {
  1206. Utf8View view { token };
  1207. if (view.validate())
  1208. return do_escape(escape_mode, view);
  1209. return do_escape(escape_mode, token);
  1210. }
  1211. ByteString Shell::unescape_token(StringView token)
  1212. {
  1213. StringBuilder builder;
  1214. enum {
  1215. Free,
  1216. Escaped
  1217. } state { Free };
  1218. for (auto c : token) {
  1219. switch (state) {
  1220. case Escaped:
  1221. builder.append(c);
  1222. state = Free;
  1223. break;
  1224. case Free:
  1225. if (c == '\\')
  1226. state = Escaped;
  1227. else
  1228. builder.append(c);
  1229. break;
  1230. }
  1231. }
  1232. if (state == Escaped)
  1233. builder.append('\\');
  1234. return builder.to_byte_string();
  1235. }
  1236. void Shell::cache_path()
  1237. {
  1238. if (!m_is_interactive)
  1239. return;
  1240. if (!cached_path.is_empty())
  1241. cached_path.clear_with_capacity();
  1242. // Add shell builtins to the cache.
  1243. for (auto const& builtin_name : builtin_names)
  1244. cached_path.append({ RunnablePath::Kind::Builtin, escape_token(builtin_name) });
  1245. // Add functions to the cache.
  1246. for (auto& function : m_functions) {
  1247. auto name = escape_token(function.key);
  1248. if (cached_path.contains_slow(name))
  1249. continue;
  1250. cached_path.append({ RunnablePath::Kind::Function, name });
  1251. }
  1252. // Add aliases to the cache.
  1253. for (auto const& alias : m_aliases) {
  1254. auto name = escape_token(alias.key);
  1255. if (cached_path.contains_slow(name))
  1256. continue;
  1257. cached_path.append({ RunnablePath::Kind::Alias, name });
  1258. }
  1259. // TODO: Can we make this rely on Core::System::resolve_executable_from_environment()?
  1260. ByteString path = getenv("PATH");
  1261. if (!path.is_empty()) {
  1262. auto directories = path.split(':');
  1263. for (auto const& directory : directories) {
  1264. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1265. while (programs.has_next()) {
  1266. auto program = programs.next_path();
  1267. auto program_path = ByteString::formatted("{}/{}", directory, program);
  1268. auto escaped_name = escape_token(program);
  1269. if (cached_path.contains_slow(escaped_name))
  1270. continue;
  1271. if (access(program_path.characters(), X_OK) == 0)
  1272. cached_path.append({ RunnablePath::Kind::Executable, escaped_name });
  1273. }
  1274. }
  1275. }
  1276. quick_sort(cached_path);
  1277. }
  1278. void Shell::add_entry_to_cache(RunnablePath const& entry)
  1279. {
  1280. size_t index = 0;
  1281. auto match = binary_search(cached_path.span(), entry, &index, RunnablePathComparator {});
  1282. if (match)
  1283. return;
  1284. while (index < cached_path.size() && strcmp(cached_path[index].path.characters(), entry.path.characters()) < 0) {
  1285. index++;
  1286. }
  1287. cached_path.insert(index, entry);
  1288. }
  1289. void Shell::remove_entry_from_cache(StringView entry)
  1290. {
  1291. size_t index { 0 };
  1292. auto match = binary_search(cached_path.span(), entry, &index, RunnablePathComparator {});
  1293. if (match)
  1294. cached_path.remove(index);
  1295. }
  1296. ErrorOr<void> Shell::highlight(Line::Editor& editor) const
  1297. {
  1298. auto line = editor.line();
  1299. auto ast = parse(line, m_is_interactive);
  1300. if (!ast)
  1301. return {};
  1302. return ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  1303. }
  1304. Vector<Line::CompletionSuggestion> Shell::complete()
  1305. {
  1306. m_completion_stack_info = {};
  1307. return complete(m_editor->line(m_editor->cursor()));
  1308. }
  1309. Vector<Line::CompletionSuggestion> Shell::complete(StringView line)
  1310. {
  1311. auto ast = parse(line, m_is_interactive);
  1312. if (!ast)
  1313. return {};
  1314. return ast->complete_for_editor(*this, line.length()).release_value_but_fixme_should_propagate_errors();
  1315. }
  1316. 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)
  1317. {
  1318. auto token = offset ? part.substring_view(0, offset) : ""sv;
  1319. ByteString path;
  1320. ssize_t last_slash = token.length() - 1;
  1321. while (last_slash >= 0 && token[last_slash] != '/')
  1322. --last_slash;
  1323. if (command_node) {
  1324. auto program_results = complete_via_program_itself(offset, command_node, node, escape_mode, {});
  1325. if (!program_results.is_error())
  1326. return program_results.release_value();
  1327. }
  1328. StringBuilder path_builder;
  1329. auto init_slash_part = token.substring_view(0, last_slash + 1);
  1330. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  1331. bool allow_direct_children = true;
  1332. // Depending on the base, we will have to prepend cwd.
  1333. if (base.is_empty()) {
  1334. // '' /foo -> absolute
  1335. // '' foo -> relative
  1336. if (!token.starts_with('/'))
  1337. path_builder.append(cwd);
  1338. path_builder.append('/');
  1339. path_builder.append(init_slash_part);
  1340. if (executable_only == ExecutableOnly::Yes && init_slash_part.is_empty())
  1341. allow_direct_children = false;
  1342. } else {
  1343. // /foo * -> absolute
  1344. // foo * -> relative
  1345. if (!base.starts_with('/'))
  1346. path_builder.append(cwd);
  1347. path_builder.append('/');
  1348. path_builder.append(base);
  1349. path_builder.append('/');
  1350. path_builder.append(init_slash_part);
  1351. }
  1352. path = path_builder.to_byte_string();
  1353. token = last_slash_part;
  1354. // the invariant part of the token is actually just the last segment
  1355. // e. in `cd /foo/bar', 'bar' is the invariant
  1356. // since we are not suggesting anything starting with
  1357. // `/foo/', but rather just `bar...'
  1358. auto token_length = escape_token(token, escape_mode).length();
  1359. size_t static_offset = 0;
  1360. auto invariant_offset = token_length;
  1361. if (m_editor)
  1362. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1363. // only suggest dot-files if path starts with a dot
  1364. Core::DirIterator files(path,
  1365. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1366. Vector<Line::CompletionSuggestion> suggestions;
  1367. while (files.has_next()) {
  1368. auto file = files.next_path();
  1369. if (file.starts_with(token)) {
  1370. struct stat program_status;
  1371. auto file_path = ByteString::formatted("{}/{}", path, file);
  1372. int stat_error = stat(file_path.characters(), &program_status);
  1373. if (!stat_error && (executable_only == ExecutableOnly::No || access(file_path.characters(), X_OK) == 0)) {
  1374. if (S_ISDIR(program_status.st_mode)) {
  1375. suggestions.append({ escape_token(file, escape_mode), "/"sv });
  1376. } else {
  1377. if (!allow_direct_children && !file.contains('/'))
  1378. continue;
  1379. suggestions.append({ escape_token(file, escape_mode), " "sv });
  1380. }
  1381. suggestions.last().input_offset = token_length;
  1382. suggestions.last().invariant_offset = invariant_offset;
  1383. suggestions.last().static_offset = static_offset;
  1384. }
  1385. }
  1386. }
  1387. // The results of DirIterator are in the order they appear on-disk.
  1388. // Instead, return suggestions in lexicographical order.
  1389. quick_sort(suggestions, [](auto& a, auto& b) { return a.text_string() < b.text_string(); });
  1390. return suggestions;
  1391. }
  1392. Vector<Line::CompletionSuggestion> Shell::complete_program_name(StringView name, size_t offset, EscapeMode escape_mode)
  1393. {
  1394. auto match = binary_search(
  1395. cached_path.span(),
  1396. name,
  1397. nullptr,
  1398. [](auto& name, auto& program) {
  1399. return strncmp(
  1400. name.characters_without_null_termination(),
  1401. program.path.characters(),
  1402. name.length());
  1403. });
  1404. if (!match)
  1405. return complete_path(""sv, name, offset, ExecutableOnly::Yes, nullptr, nullptr, escape_mode);
  1406. ByteString completion = match->path;
  1407. auto token_length = escape_token(name, escape_mode).length();
  1408. auto invariant_offset = token_length;
  1409. size_t static_offset = 0;
  1410. if (m_editor)
  1411. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1412. // Now that we have a program name starting with our token, we look at
  1413. // other program names starting with our token and cut off any mismatching
  1414. // characters.
  1415. Vector<Line::CompletionSuggestion> suggestions;
  1416. int index = match - cached_path.data();
  1417. for (int i = index - 1; i >= 0 && cached_path[i].path.starts_with(name); --i)
  1418. suggestions.append({ cached_path[i].path, " "sv });
  1419. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].path.starts_with(name); ++i)
  1420. suggestions.append({ cached_path[i].path, " "sv });
  1421. suggestions.append({ cached_path[index].path, " "sv });
  1422. for (auto& entry : suggestions) {
  1423. entry.input_offset = token_length;
  1424. entry.invariant_offset = invariant_offset;
  1425. entry.static_offset = static_offset;
  1426. }
  1427. return suggestions;
  1428. }
  1429. Vector<Line::CompletionSuggestion> Shell::complete_variable(StringView name, size_t offset)
  1430. {
  1431. Vector<Line::CompletionSuggestion> suggestions;
  1432. auto pattern = offset ? name.substring_view(0, offset) : ""sv;
  1433. auto invariant_offset = offset;
  1434. size_t static_offset = 0;
  1435. if (m_editor)
  1436. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1437. // Look at local variables.
  1438. for (auto& frame : m_local_frames) {
  1439. for (auto& variable : frame->local_variables) {
  1440. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1441. suggestions.append(variable.key);
  1442. }
  1443. }
  1444. // Look at the environment.
  1445. for (auto entry : Core::Environment::entries()) {
  1446. if (entry.full_entry.starts_with(pattern)) {
  1447. if (entry.name.is_empty())
  1448. continue;
  1449. auto name = entry.name.to_byte_string();
  1450. if (suggestions.contains_slow(name))
  1451. continue;
  1452. suggestions.append(move(name));
  1453. }
  1454. }
  1455. for (auto& entry : suggestions) {
  1456. entry.input_offset = offset;
  1457. entry.invariant_offset = invariant_offset;
  1458. entry.static_offset = static_offset;
  1459. }
  1460. return suggestions;
  1461. }
  1462. Vector<Line::CompletionSuggestion> Shell::complete_user(StringView name, size_t offset)
  1463. {
  1464. Vector<Line::CompletionSuggestion> suggestions;
  1465. auto pattern = offset ? name.substring_view(0, offset) : ""sv;
  1466. auto invariant_offset = offset;
  1467. size_t static_offset = 0;
  1468. if (m_editor)
  1469. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1470. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1471. if (di.has_error())
  1472. return suggestions;
  1473. while (di.has_next()) {
  1474. ByteString name = di.next_path();
  1475. if (name.starts_with(pattern)) {
  1476. suggestions.append(name);
  1477. auto& suggestion = suggestions.last();
  1478. suggestion.input_offset = offset;
  1479. suggestion.invariant_offset = invariant_offset;
  1480. suggestion.static_offset = static_offset;
  1481. }
  1482. }
  1483. return suggestions;
  1484. }
  1485. Vector<Line::CompletionSuggestion> Shell::complete_option(StringView program_name, StringView option, size_t offset, AST::Node const* command_node, AST::Node const* node)
  1486. {
  1487. if (command_node) {
  1488. auto program_results = complete_via_program_itself(offset, command_node, node, EscapeMode::Bareword, program_name);
  1489. if (!program_results.is_error())
  1490. return program_results.release_value();
  1491. }
  1492. size_t start = 0;
  1493. while (start < option.length() && option[start] == '-' && start < 2)
  1494. ++start;
  1495. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : ""sv;
  1496. auto invariant_offset = offset;
  1497. size_t static_offset = 0;
  1498. if (m_editor)
  1499. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1500. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1501. return {};
  1502. }
  1503. 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)
  1504. {
  1505. if (!command_node)
  1506. return Error::from_string_literal("Cannot complete null command");
  1507. if (command_node->would_execute())
  1508. return Error::from_string_literal("Refusing to complete nodes that would execute");
  1509. String program_name_storage;
  1510. if (known_program_name.is_null()) {
  1511. auto node = command_node->leftmost_trivial_literal();
  1512. if (!node)
  1513. return Error::from_string_literal("Cannot complete");
  1514. program_name_storage = TRY(TRY(const_cast<AST::Node&>(*node).run(*this))->resolve_as_string(*this));
  1515. known_program_name = program_name_storage;
  1516. }
  1517. AST::Command completion_command;
  1518. completion_command.argv.append(program_name_storage);
  1519. completion_command = TRY(expand_aliases({ completion_command })).last();
  1520. auto completion_utility_name = TRY(String::formatted("_complete_{}", completion_command.argv[0]));
  1521. if (binary_search(cached_path.span(), completion_utility_name, nullptr, RunnablePathComparator {}) != nullptr)
  1522. completion_command.argv[0] = completion_utility_name;
  1523. else if (!options.invoke_program_for_autocomplete)
  1524. return Error::from_string_literal("Refusing to use the program itself as completion source");
  1525. completion_command.argv.extend({ "--complete"_string, "--"_string });
  1526. struct Visitor : public AST::NodeVisitor {
  1527. Visitor(Shell& shell, AST::Position position)
  1528. : shell(shell)
  1529. , completion_position(position)
  1530. {
  1531. lists.empend();
  1532. }
  1533. Shell& shell;
  1534. AST::Position completion_position;
  1535. Vector<Vector<String>> lists;
  1536. bool fail { false };
  1537. void push_list() { lists.empend(); }
  1538. Vector<String> pop_list() { return lists.take_last(); }
  1539. Vector<String>& list() { return lists.last(); }
  1540. bool should_include(AST::Node const* node) const { return node->position().end_offset <= completion_position.end_offset; }
  1541. virtual void visit(AST::BarewordLiteral const* node) override
  1542. {
  1543. if (should_include(node))
  1544. list().append(node->text());
  1545. }
  1546. virtual void visit(AST::BraceExpansion const* node) override
  1547. {
  1548. if (should_include(node)) {
  1549. auto value = static_cast<AST::Node*>(const_cast<AST::BraceExpansion*>(node))->run(shell).release_value_but_fixme_should_propagate_errors();
  1550. auto entries = value->resolve_as_list(shell).release_value_but_fixme_should_propagate_errors();
  1551. list().extend(move(entries));
  1552. }
  1553. }
  1554. virtual void visit(AST::CommandLiteral const* node) override
  1555. {
  1556. if (should_include(node))
  1557. list().extend(node->command().argv);
  1558. }
  1559. virtual void visit(AST::DynamicEvaluate const* node) override
  1560. {
  1561. if (should_include(node))
  1562. fail = true;
  1563. }
  1564. virtual void visit(AST::DoubleQuotedString const* node) override
  1565. {
  1566. if (!should_include(node))
  1567. return;
  1568. push_list();
  1569. AST::NodeVisitor::visit(node);
  1570. auto list = pop_list();
  1571. StringBuilder builder;
  1572. builder.join(""sv, list);
  1573. this->list().append(builder.to_string().release_value_but_fixme_should_propagate_errors());
  1574. }
  1575. virtual void visit(AST::Glob const* node) override
  1576. {
  1577. if (should_include(node))
  1578. list().append(node->text());
  1579. }
  1580. virtual void visit(AST::Heredoc const* node) override
  1581. {
  1582. if (!should_include(node))
  1583. return;
  1584. push_list();
  1585. AST::NodeVisitor::visit(node);
  1586. auto list = pop_list();
  1587. StringBuilder builder;
  1588. builder.join(""sv, list);
  1589. this->list().append(builder.to_string().release_value_but_fixme_should_propagate_errors());
  1590. }
  1591. virtual void visit(AST::ImmediateExpression const* node) override
  1592. {
  1593. if (should_include(node))
  1594. fail = true;
  1595. }
  1596. virtual void visit(AST::Range const* node) override
  1597. {
  1598. if (!should_include(node))
  1599. return;
  1600. push_list();
  1601. node->start()->visit(*this);
  1602. list().append(pop_list().first());
  1603. }
  1604. virtual void visit(AST::SimpleVariable const* node) override
  1605. {
  1606. if (should_include(node)) {
  1607. auto values = static_cast<AST::Node*>(const_cast<AST::SimpleVariable*>(node))->run(shell).release_value_but_fixme_should_propagate_errors();
  1608. auto entries = values->resolve_as_list(shell).release_value_but_fixme_should_propagate_errors();
  1609. list().extend(move(entries));
  1610. }
  1611. }
  1612. virtual void visit(AST::SpecialVariable const* node) override
  1613. {
  1614. if (should_include(node)) {
  1615. auto values = static_cast<AST::Node*>(const_cast<AST::SpecialVariable*>(node))->run(shell).release_value_but_fixme_should_propagate_errors();
  1616. auto entries = values->resolve_as_list(shell).release_value_but_fixme_should_propagate_errors();
  1617. list().extend(move(entries));
  1618. }
  1619. }
  1620. virtual void visit(AST::Juxtaposition const* node) override
  1621. {
  1622. if (!should_include(node))
  1623. return;
  1624. push_list();
  1625. node->left()->visit(*this);
  1626. auto left = pop_list();
  1627. push_list();
  1628. node->right()->visit(*this);
  1629. auto right = pop_list();
  1630. StringBuilder builder;
  1631. for (auto& left_entry : left) {
  1632. for (auto& right_entry : right) {
  1633. builder.append(left_entry);
  1634. builder.append(right_entry);
  1635. list().append(builder.to_string().release_value_but_fixme_should_propagate_errors());
  1636. builder.clear();
  1637. }
  1638. }
  1639. }
  1640. virtual void visit(AST::StringLiteral const* node) override
  1641. {
  1642. if (should_include(node))
  1643. list().append(node->text());
  1644. }
  1645. virtual void visit(AST::Tilde const* node) override
  1646. {
  1647. if (should_include(node)) {
  1648. auto values = static_cast<AST::Node*>(const_cast<AST::Tilde*>(node))->run(shell).release_value_but_fixme_should_propagate_errors();
  1649. auto entries = values->resolve_as_list(shell).release_value_but_fixme_should_propagate_errors();
  1650. list().extend(move(entries));
  1651. }
  1652. }
  1653. virtual void visit(AST::PathRedirectionNode const*) override { }
  1654. virtual void visit(AST::CloseFdRedirection const*) override { }
  1655. virtual void visit(AST::Fd2FdRedirection const*) override { }
  1656. virtual void visit(AST::Execute const*) override { }
  1657. virtual void visit(AST::ReadRedirection const*) override { }
  1658. virtual void visit(AST::ReadWriteRedirection const*) override { }
  1659. virtual void visit(AST::WriteAppendRedirection const*) override { }
  1660. virtual void visit(AST::WriteRedirection const*) override { }
  1661. } visitor { *this, node ? node->position() : AST::Position() };
  1662. command_node->visit(visitor);
  1663. if (visitor.fail)
  1664. return Error::from_string_literal("Cannot complete");
  1665. completion_command.argv.extend(visitor.list());
  1666. auto devnull = "/dev/null"_string;
  1667. completion_command.should_wait = true;
  1668. completion_command.redirections.append(AST::PathRedirection::create(devnull, STDERR_FILENO, AST::PathRedirection::Write));
  1669. completion_command.redirections.append(AST::PathRedirection::create(devnull, STDIN_FILENO, AST::PathRedirection::Read));
  1670. auto execute_node = make_ref_counted<AST::Execute>(
  1671. AST::Position {},
  1672. make_ref_counted<AST::CommandLiteral>(AST::Position {}, move(completion_command)),
  1673. true);
  1674. Vector<Line::CompletionSuggestion> suggestions;
  1675. auto timer = TRY(Core::Timer::create_single_shot(300, [&] {
  1676. Core::EventLoop::current().quit(1);
  1677. }));
  1678. timer->start();
  1679. // Restrict the process to effectively readonly access to the FS.
  1680. auto scoped_promise = promise({
  1681. .exec_promises = "stdio rpath prot_exec map_fixed no_error",
  1682. .unveils = {
  1683. { "/", "rx" },
  1684. },
  1685. });
  1686. {
  1687. TemporaryChange change(m_is_interactive, false);
  1688. TRY(execute_node->for_each_entry(*this, [&](NonnullRefPtr<AST::Value> entry) -> ErrorOr<IterationDecision> {
  1689. auto result = TRY(entry->resolve_as_string(*this));
  1690. JsonParser parser(result);
  1691. auto parsed_result = parser.parse();
  1692. if (parsed_result.is_error())
  1693. return IterationDecision::Continue;
  1694. auto parsed = parsed_result.release_value();
  1695. if (parsed.is_object()) {
  1696. auto& object = parsed.as_object();
  1697. auto kind = object.get_byte_string("kind"sv).value_or("plain");
  1698. if (kind == "path") {
  1699. auto base = object.get_byte_string("base"sv).value_or("");
  1700. auto part = object.get_byte_string("part"sv).value_or("");
  1701. auto executable_only = object.get_bool("executable_only"sv).value_or(false) ? ExecutableOnly::Yes : ExecutableOnly::No;
  1702. suggestions.extend(complete_path(base, part, part.length(), executable_only, nullptr, nullptr));
  1703. } else if (kind == "program") {
  1704. auto name = object.get_byte_string("name"sv).value_or("");
  1705. suggestions.extend(complete_program_name(name, name.length()));
  1706. } else if (kind == "proxy") {
  1707. if (m_completion_stack_info.size_free() < 4 * KiB) {
  1708. dbgln("Not enough stack space, recursion?");
  1709. return IterationDecision::Continue;
  1710. }
  1711. auto argv = object.get_byte_string("argv"sv).value_or("");
  1712. dbgln("Proxy completion for {}", argv);
  1713. suggestions.extend(complete(argv));
  1714. } else if (kind == "plain") {
  1715. auto completion_text = object.get_byte_string("completion"sv).value_or("");
  1716. auto trailing_text = object.get_byte_string("trailing_trivia"sv).value_or("");
  1717. auto display_text = object.get_byte_string("display_trivia"sv).value_or("");
  1718. auto static_offset = object.get_u64("static_offset"sv).value_or(0);
  1719. auto invariant_offset = object.get_u64("invariant_offset"sv).value_or(0);
  1720. if (!object.get_bool("treat_as_code"sv).value_or(false)) {
  1721. completion_text = do_escape(EscapeMode::Bareword, completion_text, static_offset, invariant_offset);
  1722. }
  1723. Line::CompletionSuggestion suggestion { move(completion_text), move(trailing_text), move(display_text) };
  1724. suggestion.static_offset = static_offset;
  1725. suggestion.invariant_offset = invariant_offset;
  1726. suggestion.allow_commit_without_listing = object.get_bool("allow_commit_without_listing"sv).value_or(true);
  1727. suggestions.append(move(suggestion));
  1728. } else {
  1729. dbgln("LibLine: Unhandled completion kind: {}", kind);
  1730. }
  1731. } else {
  1732. suggestions.append(parsed.deprecated_to_byte_string());
  1733. }
  1734. return IterationDecision::Continue;
  1735. }));
  1736. }
  1737. auto pgid = getpgrp();
  1738. tcsetpgrp(STDOUT_FILENO, pgid);
  1739. tcsetpgrp(STDIN_FILENO, pgid);
  1740. return suggestions;
  1741. }
  1742. Vector<Line::CompletionSuggestion> Shell::complete_immediate_function_name(StringView name, size_t offset)
  1743. {
  1744. Vector<Line::CompletionSuggestion> suggestions;
  1745. auto invariant_offset = offset;
  1746. size_t static_offset = 0;
  1747. if (m_editor)
  1748. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1749. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(fn_name) \
  1750. if (auto name_view = #fn_name##sv; name_view.starts_with(name)) \
  1751. suggestions.append({ name_view, " "sv });
  1752. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  1753. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  1754. for (auto& entry : suggestions) {
  1755. entry.input_offset = offset;
  1756. entry.invariant_offset = invariant_offset;
  1757. entry.static_offset = static_offset;
  1758. }
  1759. return suggestions;
  1760. }
  1761. void Shell::bring_cursor_to_beginning_of_a_line() const
  1762. {
  1763. struct winsize ws;
  1764. if (m_editor) {
  1765. ws = m_editor->terminal_size();
  1766. } else {
  1767. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1768. // Very annoying assumptions.
  1769. ws.ws_col = 80;
  1770. ws.ws_row = 25;
  1771. }
  1772. }
  1773. // Black with Cyan background.
  1774. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1775. auto eol_mark_ptr = getenv("PROMPT_EOL_MARK");
  1776. ByteString eol_mark = eol_mark_ptr ?: default_mark;
  1777. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1778. if (eol_mark_length >= ws.ws_col) {
  1779. eol_mark = default_mark;
  1780. eol_mark_length = 1;
  1781. }
  1782. fputs(eol_mark.characters(), stderr);
  1783. // We write a line's worth of whitespace to the terminal. This way, we ensure that
  1784. // the prompt ends up on a new line even if there is dangling output on the current line.
  1785. size_t fill_count = ws.ws_col - eol_mark_length;
  1786. auto fill_buffer = ByteString::repeated(' ', fill_count);
  1787. fwrite(fill_buffer.characters(), 1, fill_count, stderr);
  1788. putc('\r', stderr);
  1789. }
  1790. bool Shell::has_history_event(StringView source)
  1791. {
  1792. struct : public AST::NodeVisitor {
  1793. virtual void visit(const AST::HistoryEvent* node) override
  1794. {
  1795. has_history_event = true;
  1796. AST::NodeVisitor::visit(node);
  1797. }
  1798. bool has_history_event { false };
  1799. } visitor;
  1800. auto ast = Parser { source, true }.parse();
  1801. if (!ast)
  1802. return false;
  1803. ast->visit(visitor);
  1804. return visitor.has_history_event;
  1805. }
  1806. void Shell::setup_keybinds()
  1807. {
  1808. m_editor->register_key_input_callback('\n', [this](Line::Editor& editor) {
  1809. auto ast = parse(editor.line(), m_is_interactive);
  1810. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1811. return true;
  1812. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1813. });
  1814. }
  1815. void Shell::set_user_prompt()
  1816. {
  1817. if (!has_function("PROMPT"sv))
  1818. return;
  1819. if (!m_prompt_command_node)
  1820. m_prompt_command_node = Parser { "shell_set_active_prompt -- ${join \"\\n\" $(PROMPT)}"sv }.parse();
  1821. (void)m_prompt_command_node->run(this);
  1822. }
  1823. bool Shell::read_single_line()
  1824. {
  1825. while (true) {
  1826. set_user_prompt();
  1827. restore_ios();
  1828. bring_cursor_to_beginning_of_a_line();
  1829. m_editor->initialize();
  1830. setup_keybinds();
  1831. auto line_result = m_editor->get_line(prompt());
  1832. if (line_result.is_error()) {
  1833. auto is_eof = line_result.error() == Line::Editor::Error::Eof;
  1834. auto is_empty = line_result.error() == Line::Editor::Error::Empty;
  1835. if (is_eof || is_empty) {
  1836. // Pretend the user tried to execute builtin_exit()
  1837. auto exit_code = run_command("exit"sv);
  1838. if (exit_code != 0) {
  1839. // If we didn't end up actually calling exit(), and the command didn't succeed, just pretend it's all okay
  1840. // unless we can't, then just quit anyway.
  1841. if (!is_empty)
  1842. continue;
  1843. }
  1844. }
  1845. Core::EventLoop::current().quit(1);
  1846. return false;
  1847. }
  1848. auto& line = line_result.value();
  1849. if (line.is_empty())
  1850. return true;
  1851. if (!has_history_event(line))
  1852. m_editor->add_to_history(line);
  1853. run_command(line);
  1854. return true;
  1855. }
  1856. }
  1857. void Shell::custom_event(Core::CustomEvent& event)
  1858. {
  1859. if (event.custom_type() == ReadLine) {
  1860. if (read_single_line())
  1861. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1862. return;
  1863. }
  1864. }
  1865. void Shell::notify_child_event()
  1866. {
  1867. Vector<u64> disowned_jobs;
  1868. // Workaround the fact that we can't receive *who* exactly changed state.
  1869. // The child might still be alive (and even running) when this signal is dispatched to us
  1870. // so just...repeat until we find a suitable child.
  1871. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1872. // until the next child event we can actually handle, so stop after spending a total of 5110us (~5ms) on it.
  1873. bool found_child = false;
  1874. size_t const max_tries = 10;
  1875. size_t valid_attempts = max_tries;
  1876. useconds_t backoff_usec = 20;
  1877. int backoff_multiplier = 2;
  1878. for (;;) {
  1879. if (found_child || --valid_attempts == 0)
  1880. break;
  1881. // Ignore stray SIGCHLD when there are no jobs.
  1882. if (jobs.is_empty())
  1883. return;
  1884. if (valid_attempts < max_tries - 1) {
  1885. usleep(backoff_usec);
  1886. backoff_usec *= backoff_multiplier;
  1887. }
  1888. for (auto& it : jobs) {
  1889. auto job_id = it.key;
  1890. auto& job = *it.value;
  1891. int wstatus = 0;
  1892. dbgln_if(SH_DEBUG, "waitpid({} = {}) = ...", job.pid(), job.cmd());
  1893. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1894. dbgln_if(SH_DEBUG, "... = {} - exited: {}, suspended: {}", child_pid, WIFEXITED(wstatus), WIFSTOPPED(wstatus));
  1895. if (child_pid < 0) {
  1896. if (errno == ECHILD) {
  1897. // The child process went away before we could process its death, just assume it exited all ok.
  1898. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1899. child_pid = job.pid();
  1900. } else {
  1901. VERIFY_NOT_REACHED();
  1902. }
  1903. }
  1904. if (child_pid == 0) {
  1905. // If the child existed, but wasn't dead.
  1906. if (job.is_suspended() || job.shell_did_continue()) {
  1907. // The job was suspended, and someone sent it a SIGCONT.
  1908. job.set_is_suspended(false);
  1909. if (job.shell_did_continue())
  1910. job.set_shell_did_continue(false);
  1911. found_child = true;
  1912. }
  1913. continue;
  1914. }
  1915. if (child_pid == job.pid()) {
  1916. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1917. auto signal = WTERMSIG(wstatus);
  1918. job.set_signalled(signal);
  1919. if (signal == SIGINT)
  1920. raise_error(ShellError::InternalControlFlowInterrupted, "Interrupted"sv, job.command().position);
  1921. else if (signal == SIGKILL)
  1922. raise_error(ShellError::InternalControlFlowKilled, "Interrupted"sv, job.command().position);
  1923. } else if (WIFEXITED(wstatus)) {
  1924. job.set_has_exit(WEXITSTATUS(wstatus));
  1925. } else if (WIFSTOPPED(wstatus)) {
  1926. job.unblock();
  1927. job.set_is_suspended(true);
  1928. }
  1929. found_child = true;
  1930. }
  1931. if (job.should_be_disowned())
  1932. disowned_jobs.append(job_id);
  1933. }
  1934. for (auto job_id : disowned_jobs) {
  1935. jobs.remove(job_id);
  1936. }
  1937. }
  1938. }
  1939. Shell::Shell()
  1940. : m_default_constructed(true)
  1941. {
  1942. push_frame("main", LocalFrameKind::FunctionOrGlobal).leak_frame();
  1943. int rc = gethostname(hostname, Shell::HostNameSize);
  1944. if (rc < 0)
  1945. perror("gethostname");
  1946. {
  1947. auto* pw = getpwuid(getuid());
  1948. if (pw) {
  1949. username = pw->pw_name;
  1950. home = pw->pw_dir;
  1951. setenv("HOME", pw->pw_dir, 1);
  1952. }
  1953. endpwent();
  1954. }
  1955. // For simplicity, start at the user's home directory.
  1956. this->cwd = home;
  1957. setenv("PWD", home.characters(), 1);
  1958. // Add the default PATH vars.
  1959. {
  1960. StringBuilder path;
  1961. auto const* path_env_ptr = getenv("PATH");
  1962. if (path_env_ptr != NULL)
  1963. path.append({ path_env_ptr, strlen(path_env_ptr) });
  1964. if (path.length())
  1965. path.append(":"sv);
  1966. path.append(DEFAULT_PATH_SV);
  1967. setenv("PATH", path.to_byte_string().characters(), true);
  1968. }
  1969. cache_path();
  1970. }
  1971. void Shell::initialize(bool attempt_interactive)
  1972. {
  1973. uid = getuid();
  1974. tcsetpgrp(0, getpgrp());
  1975. m_pid = getpid();
  1976. push_frame("main", LocalFrameKind::FunctionOrGlobal).leak_frame();
  1977. int rc = gethostname(hostname, Shell::HostNameSize);
  1978. if (rc < 0)
  1979. perror("gethostname");
  1980. auto istty = isatty(STDIN_FILENO);
  1981. m_is_interactive = attempt_interactive && istty;
  1982. if (istty) {
  1983. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1984. if (rc < 0)
  1985. perror("ttyname_r");
  1986. } else {
  1987. ttyname[0] = 0;
  1988. }
  1989. {
  1990. auto* cwd = getcwd(nullptr, 0);
  1991. this->cwd = cwd;
  1992. setenv("PWD", cwd, 1);
  1993. free(cwd);
  1994. }
  1995. {
  1996. auto* pw = getpwuid(getuid());
  1997. if (pw) {
  1998. username = pw->pw_name;
  1999. home = pw->pw_dir;
  2000. setenv("HOME", pw->pw_dir, 1);
  2001. }
  2002. endpwent();
  2003. }
  2004. directory_stack.append(cwd);
  2005. if (m_is_interactive) {
  2006. m_editor->load_history(get_history_path());
  2007. cache_path();
  2008. }
  2009. }
  2010. Shell::Shell(Line::Editor& editor, bool attempt_interactive, bool posix_mode)
  2011. : m_in_posix_mode(posix_mode)
  2012. , m_editor(editor)
  2013. {
  2014. initialize(attempt_interactive);
  2015. start_timer(3000);
  2016. }
  2017. Shell::~Shell()
  2018. {
  2019. destroy();
  2020. }
  2021. void Shell::destroy()
  2022. {
  2023. if (m_default_constructed)
  2024. return;
  2025. stop_all_jobs();
  2026. if (!m_is_interactive)
  2027. return;
  2028. m_editor->save_history(get_history_path());
  2029. }
  2030. void Shell::stop_all_jobs()
  2031. {
  2032. if (!jobs.is_empty()) {
  2033. if (m_is_interactive && !m_is_subshell)
  2034. printf("Killing active jobs\n");
  2035. for (auto& entry : jobs) {
  2036. if (entry.value->is_suspended()) {
  2037. dbgln_if(SH_DEBUG, "Job {} is suspended", entry.value->pid());
  2038. kill_job(entry.value, SIGCONT);
  2039. }
  2040. kill_job(entry.value, SIGHUP);
  2041. }
  2042. usleep(10000); // Wait for a bit before killing the job
  2043. for (auto& entry : jobs) {
  2044. dbgln_if(SH_DEBUG, "Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  2045. kill_job(entry.value, SIGKILL);
  2046. }
  2047. jobs.clear();
  2048. }
  2049. }
  2050. u64 Shell::find_last_job_id() const
  2051. {
  2052. u64 job_id = 0;
  2053. for (auto& entry : jobs) {
  2054. if (entry.value->job_id() > job_id)
  2055. job_id = entry.value->job_id();
  2056. }
  2057. return job_id;
  2058. }
  2059. Job* Shell::find_job(u64 id, bool is_pid)
  2060. {
  2061. for (auto& entry : jobs) {
  2062. if (is_pid) {
  2063. if (entry.value->pid() == static_cast<int>(id))
  2064. return entry.value;
  2065. } else {
  2066. if (entry.value->job_id() == id)
  2067. return entry.value;
  2068. }
  2069. }
  2070. return nullptr;
  2071. }
  2072. void Shell::kill_job(Job const* job, int sig)
  2073. {
  2074. if (!job)
  2075. return;
  2076. if (killpg(job->pgid(), sig) < 0) {
  2077. if (kill(job->pid(), sig) < 0) {
  2078. if (errno != ESRCH)
  2079. perror("kill");
  2080. }
  2081. }
  2082. }
  2083. void Shell::possibly_print_error() const
  2084. {
  2085. switch (m_error) {
  2086. case ShellError::EvaluatedSyntaxError:
  2087. warnln("Shell Syntax Error: {}", m_error_description);
  2088. break;
  2089. case ShellError::InvalidSliceContentsError:
  2090. case ShellError::InvalidGlobError:
  2091. case ShellError::NonExhaustiveMatchRules:
  2092. warnln("Shell: {}", m_error_description);
  2093. break;
  2094. case ShellError::OpenFailure:
  2095. warnln("Shell: Open failed for {}", m_error_description);
  2096. break;
  2097. case ShellError::OutOfMemory:
  2098. warnln("Shell: Hit an OOM situation");
  2099. break;
  2100. case ShellError::LaunchError:
  2101. warnln("Shell: {}", m_error_description);
  2102. break;
  2103. case ShellError::PipeFailure:
  2104. warnln("Shell: pipe() failed for {}", m_error_description);
  2105. break;
  2106. case ShellError::WriteFailure:
  2107. warnln("Shell: write() failed for {}", m_error_description);
  2108. break;
  2109. case ShellError::InternalControlFlowBreak:
  2110. case ShellError::InternalControlFlowContinue:
  2111. case ShellError::InternalControlFlowReturn:
  2112. case ShellError::InternalControlFlowInterrupted:
  2113. case ShellError::InternalControlFlowKilled:
  2114. return;
  2115. case ShellError::None:
  2116. return;
  2117. }
  2118. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  2119. auto& source_position = m_source_position.value();
  2120. auto do_line = [&](auto line, auto& current_line) {
  2121. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  2122. warnln("{:>3}| {}", line, current_line);
  2123. if (is_in_range) {
  2124. warn("\x1b[31m");
  2125. size_t length_written_so_far = 0;
  2126. if (line == (i64)source_position.position->start_line.line_number) {
  2127. warn("{:~>{}}", "", 5 + source_position.position->start_line.line_column);
  2128. length_written_so_far += source_position.position->start_line.line_column;
  2129. } else {
  2130. warn("{:~>{}}", "", 5);
  2131. }
  2132. if (line == (i64)source_position.position->end_line.line_number) {
  2133. warn("{:^>{}}", "", source_position.position->end_line.line_column - length_written_so_far);
  2134. length_written_so_far += source_position.position->start_line.line_column;
  2135. } else {
  2136. warn("{:^>{}}", "", current_line.length() - length_written_so_far);
  2137. }
  2138. warnln("\x1b[0m");
  2139. }
  2140. };
  2141. int line = -1;
  2142. // FIXME: Support arbitrarily long lines?
  2143. auto line_buf_or_error = ByteBuffer::create_uninitialized(4 * KiB);
  2144. if (line_buf_or_error.is_error()) {
  2145. warnln("Shell: Internal error while trying to display source information: {} (while allocating line buffer for {})", line_buf_or_error.error(), source_position.source_file);
  2146. return;
  2147. }
  2148. auto line_buf = line_buf_or_error.release_value();
  2149. StringView current_line;
  2150. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  2151. if (source_position.source_file.has_value()) {
  2152. auto file_or_error = Core::File::open(*source_position.source_file, Core::File::OpenMode::Read);
  2153. if (file_or_error.is_error()) {
  2154. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file_or_error.error(), *source_position.source_file);
  2155. return;
  2156. }
  2157. auto file = Core::InputBufferedFile::create(file_or_error.release_value());
  2158. while (line < line_to_skip_to) {
  2159. if (file.value()->is_eof())
  2160. return;
  2161. auto current_line_or_error = file.value()->read_line(line_buf);
  2162. if (current_line_or_error.is_error()) {
  2163. warnln("Shell: Internal error while trying to display source information: {} (while reading line {} of '{}')", current_line_or_error.error(), line, source_position.source_file);
  2164. return;
  2165. }
  2166. current_line = current_line_or_error.release_value();
  2167. ++line;
  2168. }
  2169. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  2170. do_line(line, current_line);
  2171. if (file.value()->is_eof()) {
  2172. current_line = ""sv;
  2173. } else {
  2174. auto current_line_or_error = file.value()->read_line(line_buf);
  2175. if (current_line_or_error.is_error()) {
  2176. warnln("Shell: Internal error while trying to display source information: {} (while reading line {} of '{}')", current_line_or_error.error(), line, source_position.source_file);
  2177. return;
  2178. }
  2179. current_line = current_line_or_error.release_value();
  2180. }
  2181. }
  2182. } else if (!source_position.literal_source_text.is_empty()) {
  2183. GenericLexer lexer { source_position.literal_source_text };
  2184. while (line < line_to_skip_to) {
  2185. if (lexer.is_eof())
  2186. return;
  2187. current_line = lexer.consume_line();
  2188. ++line;
  2189. }
  2190. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  2191. do_line(line, current_line);
  2192. if (lexer.is_eof())
  2193. current_line = ""sv;
  2194. else
  2195. current_line = lexer.consume_line();
  2196. }
  2197. }
  2198. }
  2199. warnln();
  2200. }
  2201. Optional<int> Shell::resolve_job_spec(StringView str)
  2202. {
  2203. if (!str.starts_with('%'))
  2204. return {};
  2205. // %number -> job id <number>
  2206. if (auto number = str.substring_view(1).to_number<unsigned>(); number.has_value())
  2207. return number.value();
  2208. // '%?str' -> iterate jobs and pick one with `str' in its command
  2209. // Note: must be quoted, since '?' will turn it into a glob - pretty ugly...
  2210. GenericLexer lexer { str.substring_view(1) };
  2211. if (!lexer.consume_specific('?'))
  2212. return {};
  2213. auto search_term = lexer.remaining();
  2214. for (auto& it : jobs) {
  2215. if (it.value->cmd().contains(search_term))
  2216. return it.key;
  2217. }
  2218. return {};
  2219. }
  2220. void Shell::timer_event(Core::TimerEvent& event)
  2221. {
  2222. event.accept();
  2223. if (m_is_subshell)
  2224. return;
  2225. auto const* autosave_env_ptr = getenv("HISTORY_AUTOSAVE_TIME_MS");
  2226. auto option = autosave_env_ptr != NULL ? StringView { autosave_env_ptr, strlen(autosave_env_ptr) } : StringView {};
  2227. auto time = option.to_number<unsigned>();
  2228. if (!time.has_value() || time.value() == 0) {
  2229. m_history_autosave_time.clear();
  2230. stop_timer();
  2231. start_timer(3000);
  2232. return;
  2233. }
  2234. if (m_history_autosave_time != time) {
  2235. m_history_autosave_time = time.value();
  2236. stop_timer();
  2237. start_timer(m_history_autosave_time.value());
  2238. }
  2239. if (!m_history_autosave_time.has_value())
  2240. return;
  2241. if (m_editor && m_editor->is_history_dirty())
  2242. m_editor->save_history(get_history_path());
  2243. }
  2244. RefPtr<AST::Node> Shell::parse(StringView input, bool interactive, bool as_command) const
  2245. {
  2246. if (m_in_posix_mode) {
  2247. Posix::Parser parser(input);
  2248. if (as_command) {
  2249. auto node = parser.parse();
  2250. if constexpr (SHELL_POSIX_PARSER_DEBUG) {
  2251. dbgln("Parsed with the POSIX Parser:");
  2252. (void)node->dump(0);
  2253. }
  2254. return node;
  2255. }
  2256. return parser.parse_word_list();
  2257. }
  2258. Parser parser { input, interactive };
  2259. if (as_command)
  2260. return parser.parse();
  2261. auto nodes = parser.parse_as_multiple_expressions();
  2262. return make_ref_counted<AST::ListConcatenate>(
  2263. nodes.is_empty() ? AST::Position { 0, 0, { 0, 0 }, { 0, 0 } } : nodes.first()->position(),
  2264. move(nodes));
  2265. }
  2266. void FileDescriptionCollector::collect()
  2267. {
  2268. for (auto fd : m_fds)
  2269. close(fd);
  2270. m_fds.clear();
  2271. }
  2272. FileDescriptionCollector::~FileDescriptionCollector()
  2273. {
  2274. collect();
  2275. }
  2276. void FileDescriptionCollector::add(int fd)
  2277. {
  2278. m_fds.append(fd);
  2279. }
  2280. SavedFileDescriptors::SavedFileDescriptors(Vector<NonnullRefPtr<AST::Rewiring>> const& intended_rewirings)
  2281. {
  2282. for (auto& rewiring : intended_rewirings) {
  2283. int new_fd = dup(rewiring->new_fd);
  2284. if (new_fd < 0) {
  2285. if (errno != EBADF)
  2286. perror("dup");
  2287. // The fd that will be overwritten isn't open right now,
  2288. // it will be cleaned up by the exec()-side collector
  2289. // and we have nothing to do here, so just ignore this error.
  2290. continue;
  2291. }
  2292. auto flags = fcntl(new_fd, F_GETFD);
  2293. auto rc = fcntl(new_fd, F_SETFD, flags | FD_CLOEXEC);
  2294. VERIFY(rc == 0);
  2295. m_saves.append({ rewiring->new_fd, new_fd });
  2296. m_collector.add(new_fd);
  2297. }
  2298. }
  2299. SavedFileDescriptors::~SavedFileDescriptors()
  2300. {
  2301. for (auto& save : m_saves) {
  2302. if (dup2(save.saved, save.original) < 0) {
  2303. perror("dup2(~SavedFileDescriptors)");
  2304. continue;
  2305. }
  2306. }
  2307. }
  2308. }