Shell.cpp 78 KB

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