Shell.cpp 92 KB

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