Shell.cpp 89 KB

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