Shell.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536
  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;"sv);
  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, strlen(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 = "/"sv;
  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"sv)) {
  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({ RunnablePath::Kind::Function, 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. Optional<Shell::RunnablePath> Shell::runnable_path_for(StringView name)
  443. {
  444. auto parts = name.split_view('/');
  445. auto path = name.to_string();
  446. if (parts.size() > 1) {
  447. auto file = Core::File::open(path.characters(), Core::OpenMode::ReadOnly);
  448. if (!file.is_error() && !file.value()->is_directory() && access(path.characters(), X_OK) == 0)
  449. return RunnablePath { RunnablePath::Kind::Executable, name };
  450. }
  451. auto* found = binary_search(cached_path.span(), path, nullptr, RunnablePathComparator {});
  452. if (!found)
  453. return {};
  454. return *found;
  455. }
  456. Optional<String> Shell::help_path_for(Vector<RunnablePath> visited, Shell::RunnablePath const& runnable_path)
  457. {
  458. switch (runnable_path.kind) {
  459. case RunnablePath::Kind::Executable: {
  460. LexicalPath lexical_path(runnable_path.path);
  461. return lexical_path.basename();
  462. }
  463. case RunnablePath::Kind::Alias: {
  464. if (visited.contains_slow(runnable_path))
  465. return {}; // Break out of an alias loop
  466. auto resolved = resolve_alias(runnable_path.path);
  467. auto* runnable = binary_search(cached_path.span(), resolved, nullptr, RunnablePathComparator {});
  468. if (!runnable)
  469. return {};
  470. visited.append(runnable_path);
  471. return help_path_for(visited, *runnable);
  472. }
  473. default:
  474. return {};
  475. }
  476. }
  477. int Shell::run_command(StringView cmd, Optional<SourcePosition> source_position_override)
  478. {
  479. // The default-constructed mode of the shell
  480. // should not be used for execution!
  481. VERIFY(!m_default_constructed);
  482. take_error();
  483. if (!last_return_code.has_value())
  484. last_return_code = 0;
  485. ScopedValueRollback source_position_rollback { m_source_position };
  486. if (source_position_override.has_value())
  487. m_source_position = move(source_position_override);
  488. if (!m_source_position.has_value())
  489. m_source_position = SourcePosition { .source_file = {}, .literal_source_text = cmd, .position = {} };
  490. if (cmd.is_empty())
  491. return 0;
  492. auto command = Parser(cmd, m_is_interactive).parse();
  493. if (!command)
  494. return 0;
  495. if constexpr (SH_DEBUG) {
  496. dbgln("Command follows");
  497. command->dump(0);
  498. }
  499. if (command->is_syntax_error()) {
  500. auto& error_node = command->syntax_error_node();
  501. auto& position = error_node.position();
  502. raise_error(ShellError::EvaluatedSyntaxError, error_node.error_text(), position);
  503. }
  504. if (!has_error(ShellError::None)) {
  505. possibly_print_error();
  506. take_error();
  507. return 1;
  508. }
  509. tcgetattr(0, &termios);
  510. (void)command->run(*this);
  511. if (!has_error(ShellError::None)) {
  512. possibly_print_error();
  513. take_error();
  514. return 1;
  515. }
  516. return last_return_code.value_or(0);
  517. }
  518. ErrorOr<RefPtr<Job>> Shell::run_command(const AST::Command& command)
  519. {
  520. FileDescriptionCollector fds;
  521. if (options.verbose)
  522. warnln("+ {}", command);
  523. // If the command is empty, store the redirections and apply them to all later commands.
  524. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  525. m_global_redirections.extend(command.redirections);
  526. for (auto& next_in_chain : command.next_chain)
  527. run_tail(command, next_in_chain, last_return_code.value_or(0));
  528. return nullptr;
  529. }
  530. // Resolve redirections.
  531. NonnullRefPtrVector<AST::Rewiring> rewirings;
  532. auto resolve_redirection = [&](auto& redirection) -> ErrorOr<void> {
  533. auto rewiring = TRY(redirection.apply());
  534. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseNew)
  535. rewirings.append(*rewiring);
  536. if (rewiring->fd_action == AST::Rewiring::Close::Old) {
  537. fds.add(rewiring->old_fd);
  538. } else if (rewiring->fd_action == AST::Rewiring::Close::New) {
  539. if (rewiring->new_fd != -1)
  540. fds.add(rewiring->new_fd);
  541. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseNew) {
  542. fds.add(rewiring->new_fd);
  543. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshNew) {
  544. VERIFY(rewiring->other_pipe_end);
  545. int pipe_fd[2];
  546. int rc = pipe(pipe_fd);
  547. if (rc < 0)
  548. return Error::from_syscall("pipe"sv, rc);
  549. rewiring->new_fd = pipe_fd[1];
  550. rewiring->other_pipe_end->new_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  551. fds.add(pipe_fd[1]);
  552. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshOld) {
  553. VERIFY(rewiring->other_pipe_end);
  554. int pipe_fd[2];
  555. int rc = pipe(pipe_fd);
  556. if (rc < 0)
  557. return Error::from_syscall("pipe"sv, rc);
  558. rewiring->old_fd = pipe_fd[1];
  559. rewiring->other_pipe_end->old_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  560. fds.add(pipe_fd[1]);
  561. }
  562. return {};
  563. };
  564. auto apply_rewirings = [&]() -> ErrorOr<void> {
  565. for (auto& rewiring : rewirings) {
  566. dbgln_if(SH_DEBUG, "in {}<{}>, dup2({}, {})", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.old_fd, rewiring.new_fd);
  567. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  568. if (rc < 0)
  569. return Error::from_syscall("dup2"sv, rc);
  570. // {new,old}_fd is closed via the `fds` collector, but rewiring.other_pipe_end->{new,old}_fd
  571. // isn't yet in that collector when the first child spawns.
  572. if (rewiring.other_pipe_end) {
  573. if (rewiring.fd_action == AST::Rewiring::Close::RefreshNew) {
  574. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->new_fd) < 0)
  575. perror("close other pipe end");
  576. } else if (rewiring.fd_action == AST::Rewiring::Close::RefreshOld) {
  577. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->old_fd) < 0)
  578. perror("close other pipe end");
  579. }
  580. }
  581. }
  582. return {};
  583. };
  584. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, false };
  585. for (auto& redirection : m_global_redirections)
  586. TRY(resolve_redirection(redirection));
  587. for (auto& redirection : command.redirections)
  588. TRY(resolve_redirection(redirection));
  589. if (int local_return_code = 0; command.should_wait && run_builtin(command, rewirings, local_return_code)) {
  590. last_return_code = local_return_code;
  591. for (auto& next_in_chain : command.next_chain)
  592. run_tail(command, next_in_chain, *last_return_code);
  593. return nullptr;
  594. }
  595. auto can_be_run_in_current_process = command.should_wait && !command.pipeline && !command.argv.is_empty();
  596. if (can_be_run_in_current_process && has_function(command.argv.first())) {
  597. SavedFileDescriptors fds { rewirings };
  598. for (auto& rewiring : rewirings)
  599. TRY(Core::System::dup2(rewiring.old_fd, rewiring.new_fd));
  600. if (int local_return_code = 0; invoke_function(command, local_return_code)) {
  601. last_return_code = local_return_code;
  602. for (auto& next_in_chain : command.next_chain)
  603. run_tail(command, next_in_chain, *last_return_code);
  604. return nullptr;
  605. }
  606. }
  607. if (command.argv.is_empty()
  608. && !command.next_chain.is_empty()
  609. && command.should_immediately_execute_next
  610. && command.redirections.is_empty()
  611. && command.next_chain.first().node->should_override_execution_in_current_process()) {
  612. for (auto& next_in_chain : command.next_chain)
  613. run_tail(command, next_in_chain, last_return_code.value_or(0));
  614. return nullptr;
  615. }
  616. Vector<char const*> argv;
  617. Vector<String> copy_argv = command.argv;
  618. argv.ensure_capacity(command.argv.size() + 1);
  619. for (auto& arg : copy_argv)
  620. argv.append(arg.characters());
  621. argv.append(nullptr);
  622. auto sync_pipe = TRY(Core::System::pipe2(0));
  623. auto child = TRY(Core::System::fork());
  624. if (child == 0) {
  625. close(sync_pipe[1]);
  626. m_pid = getpid();
  627. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  628. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, true };
  629. if (auto result = apply_rewirings(); result.is_error()) {
  630. warnln("Shell: Failed to apply rewirings in {}: {}", copy_argv[0], result.error());
  631. _exit(126);
  632. }
  633. fds.collect();
  634. u8 c;
  635. while (read(sync_pipe[0], &c, 1) < 0) {
  636. if (errno != EINTR) {
  637. warnln("Shell: Failed to sync in {}: {}", copy_argv[0], Error::from_syscall("read"sv, -errno));
  638. // There's nothing interesting we can do here.
  639. break;
  640. }
  641. }
  642. dbgln_if(SH_DEBUG, "Synced up with parent, we're good to exec()");
  643. close(sync_pipe[0]);
  644. if (!m_is_subshell && command.should_wait)
  645. tcsetattr(0, TCSANOW, &default_termios);
  646. m_is_subshell = true;
  647. if (command.should_immediately_execute_next) {
  648. VERIFY(command.argv.is_empty());
  649. Core::EventLoop mainloop;
  650. setup_signals();
  651. for (auto& next_in_chain : command.next_chain)
  652. run_tail(command, next_in_chain, 0);
  653. _exit(last_return_code.value_or(0));
  654. }
  655. if (int local_return_code = 0; run_builtin(command, {}, local_return_code))
  656. _exit(local_return_code);
  657. if (int local_return_code = 0; invoke_function(command, local_return_code))
  658. _exit(local_return_code);
  659. // We no longer need the jobs here.
  660. jobs.clear();
  661. execute_process(move(argv));
  662. VERIFY_NOT_REACHED();
  663. }
  664. close(sync_pipe[0]);
  665. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  666. if (command.pipeline) {
  667. if (is_first) {
  668. command.pipeline->pgid = child;
  669. }
  670. }
  671. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  672. if (!m_is_subshell || command.pipeline) {
  673. auto result = Core::System::setpgid(child, pgid);
  674. if (result.is_error() && m_is_interactive)
  675. warnln("Shell: {}", result.error());
  676. if (!m_is_subshell) {
  677. // There's no reason to care about the errors here
  678. // either we're in a tty, we're interactive, and this works
  679. // or we're not, and it fails - in which case, we don't need
  680. // stdin/stdout handoff to child processes anyway.
  681. tcsetpgrp(STDOUT_FILENO, pgid);
  682. tcsetpgrp(STDIN_FILENO, pgid);
  683. }
  684. }
  685. while (write(sync_pipe[1], "x", 1) < 0) {
  686. if (errno != EINTR) {
  687. warnln("Shell: Failed to sync with {}: {}", copy_argv[0], Error::from_syscall("write"sv, -errno));
  688. // There's nothing interesting we can do here.
  689. break;
  690. }
  691. }
  692. close(sync_pipe[1]);
  693. StringBuilder cmd;
  694. cmd.join(' ', command.argv);
  695. auto command_copy = AST::Command(command);
  696. // Clear the next chain if it's to be immediately executed
  697. // as the child will run this chain.
  698. if (command.should_immediately_execute_next)
  699. command_copy.next_chain.clear();
  700. auto job = Job::create(child, pgid, cmd.build(), find_last_job_id() + 1, move(command_copy));
  701. jobs.set((u64)child, job);
  702. job->on_exit = [this](auto job) {
  703. if (!job->exited())
  704. return;
  705. if (job->is_running_in_background() && job->should_announce_exit())
  706. warnln("Shell: Job {} ({}) exited\n", job->job_id(), job->cmd());
  707. else if (job->signaled() && job->should_announce_signal())
  708. warnln("Shell: Job {} ({}) {}\n", job->job_id(), job->cmd(), strsignal(job->termination_signal()));
  709. last_return_code = job->exit_code();
  710. job->disown();
  711. if (m_editor && job->exit_code() == 0 && is_allowed_to_modify_termios(job->command())) {
  712. m_editor->refetch_default_termios();
  713. default_termios = m_editor->default_termios();
  714. termios = m_editor->termios();
  715. }
  716. run_tail(job);
  717. };
  718. fds.collect();
  719. return *job;
  720. }
  721. void Shell::execute_process(Vector<char const*>&& argv)
  722. {
  723. for (auto& promise : m_active_promises) {
  724. MUST(Core::System::pledge("stdio rpath exec"sv, promise.data.exec_promises));
  725. for (auto& item : promise.data.unveils)
  726. MUST(Core::System::unveil(item.path, item.access));
  727. }
  728. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  729. if (rc < 0) {
  730. auto parts = StringView { argv[0], strlen(argv[0]) }.split_view('/');
  731. if (parts.size() == 1) {
  732. // If this is a path in the current directory and it caused execvp() to fail,
  733. // simply don't attempt to execute it, see #6774.
  734. warnln("{}: Command not found.", argv[0]);
  735. _exit(127);
  736. }
  737. int saved_errno = errno;
  738. struct stat st;
  739. if (stat(argv[0], &st)) {
  740. warnln("stat({}): {}", argv[0], strerror(errno));
  741. // Return code 127 on command not found.
  742. _exit(127);
  743. }
  744. if (!(st.st_mode & S_IXUSR)) {
  745. warnln("{}: Not executable", argv[0]);
  746. // Return code 126 when file is not executable.
  747. _exit(126);
  748. }
  749. if (saved_errno == ENOENT) {
  750. do {
  751. auto file_result = Core::File::open(argv[0], Core::OpenMode::ReadOnly);
  752. if (file_result.is_error())
  753. break;
  754. auto& file = file_result.value();
  755. auto line = file->read_line();
  756. if (!line.starts_with("#!"sv))
  757. break;
  758. GenericLexer shebang_lexer { line.substring_view(2) };
  759. auto shebang = shebang_lexer.consume_until(is_any_of("\n\r"sv)).to_string();
  760. argv.prepend(shebang.characters());
  761. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  762. if (rc < 0) {
  763. warnln("{}: Invalid interpreter \"{}\": {}", argv[0], shebang.characters(), strerror(errno));
  764. _exit(126);
  765. }
  766. } while (false);
  767. warnln("{}: Command not found.", argv[0]);
  768. } else {
  769. if (S_ISDIR(st.st_mode)) {
  770. warnln("Shell: {}: Is a directory", argv[0]);
  771. _exit(126);
  772. }
  773. warnln("execvp({}): {}", argv[0], strerror(saved_errno));
  774. }
  775. _exit(126);
  776. }
  777. VERIFY_NOT_REACHED();
  778. }
  779. void Shell::run_tail(const AST::Command& invoking_command, const AST::NodeWithAction& next_in_chain, int head_exit_code)
  780. {
  781. if (m_error != ShellError::None) {
  782. possibly_print_error();
  783. if (!is_control_flow(m_error))
  784. take_error();
  785. return;
  786. }
  787. auto evaluate = [&] {
  788. if (next_in_chain.node->would_execute()) {
  789. (void)next_in_chain.node->run(*this);
  790. return;
  791. }
  792. auto node = next_in_chain.node;
  793. if (!invoking_command.should_wait)
  794. node = adopt_ref(static_cast<AST::Node&>(*new AST::Background(next_in_chain.node->position(), move(node))));
  795. (void)adopt_ref(static_cast<AST::Node&>(*new AST::Execute(next_in_chain.node->position(), move(node))))->run(*this);
  796. };
  797. switch (next_in_chain.action) {
  798. case AST::NodeWithAction::And:
  799. if (head_exit_code == 0)
  800. evaluate();
  801. break;
  802. case AST::NodeWithAction::Or:
  803. if (head_exit_code != 0)
  804. evaluate();
  805. break;
  806. case AST::NodeWithAction::Sequence:
  807. evaluate();
  808. break;
  809. }
  810. }
  811. void Shell::run_tail(RefPtr<Job> job)
  812. {
  813. if (auto cmd = job->command_ptr()) {
  814. deferred_invoke([=, this] {
  815. for (auto& next_in_chain : cmd->next_chain) {
  816. run_tail(*cmd, next_in_chain, job->exit_code());
  817. }
  818. });
  819. }
  820. }
  821. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  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. NonnullRefPtrVector<Job> spawned_jobs;
  830. for (auto& command : commands) {
  831. if constexpr (SH_DEBUG) {
  832. dbgln("Command");
  833. for (auto& arg : command.argv)
  834. dbgln("argv: {}", arg);
  835. for (auto& redir : command.redirections) {
  836. if (redir.is_path_redirection()) {
  837. auto path_redir = (const AST::PathRedirection*)&redir;
  838. dbgln("redir path '{}' <-({})-> {}", path_redir->path, (int)path_redir->direction, path_redir->fd);
  839. } else if (redir.is_fd_redirection()) {
  840. auto* fdredir = (const AST::FdRedirection*)&redir;
  841. dbgln("redir fd {} -> {}", fdredir->old_fd, fdredir->new_fd);
  842. } else if (redir.is_close_redirection()) {
  843. auto close_redir = (const AST::CloseRedirection*)&redir;
  844. dbgln("close fd {}", close_redir->fd);
  845. } else {
  846. VERIFY_NOT_REACHED();
  847. }
  848. }
  849. }
  850. auto job_result = run_command(command);
  851. if (job_result.is_error()) {
  852. raise_error(ShellError::LaunchError, String::formatted("{} while running '{}'", job_result.error(), command.argv.first()), command.position);
  853. break;
  854. }
  855. auto job = job_result.release_value();
  856. if (!job)
  857. continue;
  858. spawned_jobs.append(*job);
  859. if (command.should_wait) {
  860. block_on_job(job);
  861. } else {
  862. job->set_running_in_background(true);
  863. if (!command.is_pipe_source && command.should_notify_if_in_background)
  864. job->set_should_announce_exit(true);
  865. }
  866. }
  867. if (m_error != ShellError::None) {
  868. possibly_print_error();
  869. if (!is_control_flow(m_error))
  870. take_error();
  871. }
  872. return spawned_jobs;
  873. }
  874. bool Shell::run_file(String const& filename, bool explicitly_invoked)
  875. {
  876. TemporaryChange script_change { current_script, filename };
  877. TemporaryChange interactive_change { m_is_interactive, false };
  878. TemporaryChange<Optional<SourcePosition>> source_change { m_source_position, SourcePosition { .source_file = filename, .literal_source_text = {}, .position = {} } };
  879. auto file_result = Core::File::open(filename, Core::OpenMode::ReadOnly);
  880. if (file_result.is_error()) {
  881. auto error = String::formatted("'{}': {}", escape_token_for_single_quotes(filename), file_result.error());
  882. if (explicitly_invoked)
  883. raise_error(ShellError::OpenFailure, error);
  884. else
  885. dbgln("open() failed for {}", error);
  886. return false;
  887. }
  888. auto file = file_result.value();
  889. auto data = file->read_all();
  890. return run_command(data) == 0;
  891. }
  892. bool Shell::is_allowed_to_modify_termios(const AST::Command& command) const
  893. {
  894. if (command.argv.is_empty())
  895. return false;
  896. auto value = lookup_local_variable("PROGRAMS_ALLOWED_TO_MODIFY_DEFAULT_TERMIOS"sv);
  897. if (!value)
  898. return false;
  899. return value->resolve_as_list(*this).contains_slow(command.argv[0]);
  900. }
  901. void Shell::restore_ios()
  902. {
  903. if (m_is_subshell)
  904. return;
  905. tcsetattr(0, TCSANOW, &termios);
  906. tcsetpgrp(STDOUT_FILENO, m_pid);
  907. tcsetpgrp(STDIN_FILENO, m_pid);
  908. }
  909. void Shell::block_on_pipeline(RefPtr<AST::Pipeline> pipeline)
  910. {
  911. if (!pipeline)
  912. return;
  913. for (auto& it : jobs) {
  914. if (auto cmd = it.value->command_ptr(); cmd->pipeline == pipeline && cmd->is_pipe_source)
  915. block_on_job(it.value);
  916. }
  917. }
  918. void Shell::block_on_job(RefPtr<Job> job)
  919. {
  920. TemporaryChange<Job const*> current_job { m_current_job, job.ptr() };
  921. if (!job)
  922. return;
  923. if (job->is_suspended() && !job->shell_did_continue())
  924. return; // We cannot wait for a suspended job.
  925. ScopeGuard io_restorer { [&]() {
  926. if (job->exited() && !job->is_running_in_background()) {
  927. restore_ios();
  928. }
  929. } };
  930. bool job_exited { false };
  931. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  932. if (old_exit)
  933. old_exit(job);
  934. job_exited = true;
  935. };
  936. if (job->exited())
  937. return;
  938. while (!job_exited)
  939. Core::EventLoop::current().pump();
  940. // If the job is part of a pipeline, wait for the rest of the members too.
  941. if (auto command = job->command_ptr())
  942. block_on_pipeline(command->pipeline);
  943. }
  944. String Shell::get_history_path()
  945. {
  946. if (auto histfile = getenv("HISTFILE"))
  947. return { histfile };
  948. return String::formatted("{}/.history", home);
  949. }
  950. String Shell::escape_token_for_single_quotes(StringView token)
  951. {
  952. // `foo bar \n '` -> `'foo bar \n '"'"`
  953. StringBuilder builder;
  954. builder.append("'"sv);
  955. auto started_single_quote = true;
  956. for (auto c : token) {
  957. switch (c) {
  958. case '\'':
  959. builder.append("\"'\""sv);
  960. started_single_quote = false;
  961. continue;
  962. default:
  963. builder.append(c);
  964. if (!started_single_quote) {
  965. started_single_quote = true;
  966. builder.append("'"sv);
  967. }
  968. break;
  969. }
  970. }
  971. if (started_single_quote)
  972. builder.append("'"sv);
  973. return builder.build();
  974. }
  975. String Shell::escape_token_for_double_quotes(StringView token)
  976. {
  977. // `foo bar \n $x 'blah "hello` -> `"foo bar \\n $x 'blah \"hello"`
  978. StringBuilder builder;
  979. builder.append('"');
  980. for (auto c : token) {
  981. switch (c) {
  982. case '\"':
  983. builder.append("\\\""sv);
  984. continue;
  985. case '\\':
  986. builder.append("\\\\"sv);
  987. continue;
  988. default:
  989. builder.append(c);
  990. break;
  991. }
  992. }
  993. builder.append('"');
  994. return builder.build();
  995. }
  996. Shell::SpecialCharacterEscapeMode Shell::special_character_escape_mode(u32 code_point, EscapeMode mode)
  997. {
  998. switch (code_point) {
  999. case '\'':
  1000. if (mode == EscapeMode::DoubleQuotedString)
  1001. return SpecialCharacterEscapeMode::Untouched;
  1002. return SpecialCharacterEscapeMode::Escaped;
  1003. case '"':
  1004. case '$':
  1005. case '\\':
  1006. if (mode == EscapeMode::SingleQuotedString)
  1007. return SpecialCharacterEscapeMode::Untouched;
  1008. return SpecialCharacterEscapeMode::Escaped;
  1009. case '|':
  1010. case '>':
  1011. case '<':
  1012. case '(':
  1013. case ')':
  1014. case '{':
  1015. case '}':
  1016. case '&':
  1017. case ';':
  1018. case '?':
  1019. case '*':
  1020. case ' ':
  1021. if (mode == EscapeMode::SingleQuotedString || mode == EscapeMode::DoubleQuotedString)
  1022. return SpecialCharacterEscapeMode::Untouched;
  1023. return SpecialCharacterEscapeMode::Escaped;
  1024. case '\n':
  1025. case '\t':
  1026. case '\r':
  1027. return SpecialCharacterEscapeMode::QuotedAsEscape;
  1028. default:
  1029. // FIXME: Should instead use unicode's "graphic" property (categories L, M, N, P, S, Zs)
  1030. if (is_ascii(code_point))
  1031. return is_ascii_printable(code_point) ? SpecialCharacterEscapeMode::Untouched : SpecialCharacterEscapeMode::QuotedAsHex;
  1032. return SpecialCharacterEscapeMode::Untouched;
  1033. }
  1034. }
  1035. static String do_escape(Shell::EscapeMode escape_mode, auto& token)
  1036. {
  1037. StringBuilder builder;
  1038. for (auto c : token) {
  1039. static_assert(sizeof(c) == sizeof(u32) || sizeof(c) == sizeof(u8));
  1040. switch (Shell::special_character_escape_mode(c, escape_mode)) {
  1041. case Shell::SpecialCharacterEscapeMode::Untouched:
  1042. if constexpr (sizeof(c) == sizeof(u8))
  1043. builder.append(c);
  1044. else
  1045. builder.append(Utf32View { &c, 1 });
  1046. break;
  1047. case Shell::SpecialCharacterEscapeMode::Escaped:
  1048. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1049. builder.append("'"sv);
  1050. builder.append('\\');
  1051. builder.append(c);
  1052. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1053. builder.append("'"sv);
  1054. break;
  1055. case Shell::SpecialCharacterEscapeMode::QuotedAsEscape:
  1056. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1057. builder.append("'"sv);
  1058. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1059. builder.append("\""sv);
  1060. switch (c) {
  1061. case '\n':
  1062. builder.append(R"(\n)"sv);
  1063. break;
  1064. case '\t':
  1065. builder.append(R"(\t)"sv);
  1066. break;
  1067. case '\r':
  1068. builder.append(R"(\r)"sv);
  1069. break;
  1070. default:
  1071. VERIFY_NOT_REACHED();
  1072. }
  1073. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1074. builder.append("\""sv);
  1075. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1076. builder.append("'"sv);
  1077. break;
  1078. case Shell::SpecialCharacterEscapeMode::QuotedAsHex:
  1079. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1080. builder.append("'"sv);
  1081. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1082. builder.append("\""sv);
  1083. if (c <= NumericLimits<u8>::max())
  1084. builder.appendff(R"(\x{:0>2x})", static_cast<u8>(c));
  1085. else
  1086. builder.appendff(R"(\u{:0>8x})", static_cast<u32>(c));
  1087. if (escape_mode != Shell::EscapeMode::DoubleQuotedString)
  1088. builder.append("\""sv);
  1089. if (escape_mode == Shell::EscapeMode::SingleQuotedString)
  1090. builder.append("'"sv);
  1091. break;
  1092. }
  1093. }
  1094. return builder.build();
  1095. }
  1096. String Shell::escape_token(Utf32View token, EscapeMode escape_mode)
  1097. {
  1098. return do_escape(escape_mode, token);
  1099. }
  1100. String Shell::escape_token(StringView token, EscapeMode escape_mode)
  1101. {
  1102. Utf8View view { token };
  1103. if (view.validate())
  1104. return do_escape(escape_mode, view);
  1105. return do_escape(escape_mode, token);
  1106. }
  1107. String Shell::unescape_token(StringView token)
  1108. {
  1109. StringBuilder builder;
  1110. enum {
  1111. Free,
  1112. Escaped
  1113. } state { Free };
  1114. for (auto c : token) {
  1115. switch (state) {
  1116. case Escaped:
  1117. builder.append(c);
  1118. state = Free;
  1119. break;
  1120. case Free:
  1121. if (c == '\\')
  1122. state = Escaped;
  1123. else
  1124. builder.append(c);
  1125. break;
  1126. }
  1127. }
  1128. if (state == Escaped)
  1129. builder.append('\\');
  1130. return builder.build();
  1131. }
  1132. void Shell::cache_path()
  1133. {
  1134. if (!m_is_interactive)
  1135. return;
  1136. if (!cached_path.is_empty())
  1137. cached_path.clear_with_capacity();
  1138. // Add shell builtins to the cache.
  1139. for (auto const& builtin_name : builtin_names)
  1140. cached_path.append({ RunnablePath::Kind::Builtin, escape_token(builtin_name) });
  1141. // Add functions to the cache.
  1142. for (auto& function : m_functions) {
  1143. auto name = escape_token(function.key);
  1144. if (cached_path.contains_slow(name))
  1145. continue;
  1146. cached_path.append({ RunnablePath::Kind::Function, name });
  1147. }
  1148. // Add aliases to the cache.
  1149. for (auto const& alias : m_aliases) {
  1150. auto name = escape_token(alias.key);
  1151. if (cached_path.contains_slow(name))
  1152. continue;
  1153. cached_path.append({ RunnablePath::Kind::Alias, name });
  1154. }
  1155. // TODO: Can we make this rely on Core::File::resolve_executable_from_environment()?
  1156. String path = getenv("PATH");
  1157. if (!path.is_empty()) {
  1158. auto directories = path.split(':');
  1159. for (auto const& directory : directories) {
  1160. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1161. while (programs.has_next()) {
  1162. auto program = programs.next_path();
  1163. auto program_path = String::formatted("{}/{}", directory, program);
  1164. auto escaped_name = escape_token(program);
  1165. if (cached_path.contains_slow(escaped_name))
  1166. continue;
  1167. if (access(program_path.characters(), X_OK) == 0)
  1168. cached_path.append({ RunnablePath::Kind::Executable, escaped_name });
  1169. }
  1170. }
  1171. }
  1172. quick_sort(cached_path);
  1173. }
  1174. void Shell::add_entry_to_cache(RunnablePath const& entry)
  1175. {
  1176. size_t index = 0;
  1177. auto match = binary_search(cached_path.span(), entry, &index, RunnablePathComparator {});
  1178. if (match)
  1179. return;
  1180. while (index < cached_path.size() && strcmp(cached_path[index].path.characters(), entry.path.characters()) < 0) {
  1181. index++;
  1182. }
  1183. cached_path.insert(index, entry);
  1184. }
  1185. void Shell::remove_entry_from_cache(StringView entry)
  1186. {
  1187. size_t index { 0 };
  1188. auto match = binary_search(cached_path.span(), entry, &index, RunnablePathComparator {});
  1189. if (match)
  1190. cached_path.remove(index);
  1191. }
  1192. void Shell::highlight(Line::Editor& editor) const
  1193. {
  1194. auto line = editor.line();
  1195. Parser parser(line, m_is_interactive);
  1196. auto ast = parser.parse();
  1197. if (!ast)
  1198. return;
  1199. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  1200. }
  1201. Vector<Line::CompletionSuggestion> Shell::complete()
  1202. {
  1203. m_completion_stack_info = {};
  1204. return complete(m_editor->line(m_editor->cursor()));
  1205. }
  1206. Vector<Line::CompletionSuggestion> Shell::complete(StringView line)
  1207. {
  1208. Parser parser(line, m_is_interactive);
  1209. auto ast = parser.parse();
  1210. if (!ast)
  1211. return {};
  1212. return ast->complete_for_editor(*this, line.length());
  1213. }
  1214. 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)
  1215. {
  1216. auto token = offset ? part.substring_view(0, offset) : ""sv;
  1217. String path;
  1218. ssize_t last_slash = token.length() - 1;
  1219. while (last_slash >= 0 && token[last_slash] != '/')
  1220. --last_slash;
  1221. if (command_node) {
  1222. auto program_results = complete_via_program_itself(offset, command_node, node, escape_mode, {});
  1223. if (!program_results.is_error())
  1224. return program_results.release_value();
  1225. }
  1226. StringBuilder path_builder;
  1227. auto init_slash_part = token.substring_view(0, last_slash + 1);
  1228. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  1229. bool allow_direct_children = true;
  1230. // Depending on the base, we will have to prepend cwd.
  1231. if (base.is_empty()) {
  1232. // '' /foo -> absolute
  1233. // '' foo -> relative
  1234. if (!token.starts_with('/'))
  1235. path_builder.append(cwd);
  1236. path_builder.append('/');
  1237. path_builder.append(init_slash_part);
  1238. if (executable_only == ExecutableOnly::Yes && init_slash_part.is_empty())
  1239. allow_direct_children = false;
  1240. } else {
  1241. // /foo * -> absolute
  1242. // foo * -> relative
  1243. if (!base.starts_with('/'))
  1244. path_builder.append(cwd);
  1245. path_builder.append('/');
  1246. path_builder.append(base);
  1247. path_builder.append('/');
  1248. path_builder.append(init_slash_part);
  1249. }
  1250. path = path_builder.build();
  1251. token = last_slash_part;
  1252. // the invariant part of the token is actually just the last segment
  1253. // e. in `cd /foo/bar', 'bar' is the invariant
  1254. // since we are not suggesting anything starting with
  1255. // `/foo/', but rather just `bar...'
  1256. auto token_length = escape_token(token, escape_mode).length();
  1257. size_t static_offset = 0;
  1258. auto invariant_offset = token_length;
  1259. if (m_editor)
  1260. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1261. // only suggest dot-files if path starts with a dot
  1262. Core::DirIterator files(path,
  1263. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1264. Vector<Line::CompletionSuggestion> suggestions;
  1265. while (files.has_next()) {
  1266. auto file = files.next_path();
  1267. if (file.starts_with(token)) {
  1268. struct stat program_status;
  1269. auto file_path = String::formatted("{}/{}", path, file);
  1270. int stat_error = stat(file_path.characters(), &program_status);
  1271. if (!stat_error && (executable_only == ExecutableOnly::No || access(file_path.characters(), X_OK) == 0)) {
  1272. if (S_ISDIR(program_status.st_mode)) {
  1273. suggestions.append({ escape_token(file, escape_mode), "/"sv });
  1274. } else {
  1275. if (!allow_direct_children && !file.contains('/'))
  1276. continue;
  1277. suggestions.append({ escape_token(file, escape_mode), " "sv });
  1278. }
  1279. suggestions.last().input_offset = token_length;
  1280. suggestions.last().invariant_offset = invariant_offset;
  1281. suggestions.last().static_offset = static_offset;
  1282. }
  1283. }
  1284. }
  1285. // The results of DirIterator are in the order they appear on-disk.
  1286. // Instead, return suggestions in lexicographical order.
  1287. quick_sort(suggestions, [](auto& a, auto& b) { return a.text_string < b.text_string; });
  1288. return suggestions;
  1289. }
  1290. Vector<Line::CompletionSuggestion> Shell::complete_program_name(StringView name, size_t offset, EscapeMode escape_mode)
  1291. {
  1292. auto match = binary_search(
  1293. cached_path.span(),
  1294. name,
  1295. nullptr,
  1296. [](auto& name, auto& program) {
  1297. return strncmp(
  1298. name.characters_without_null_termination(),
  1299. program.path.characters(),
  1300. name.length());
  1301. });
  1302. if (!match)
  1303. return complete_path(""sv, name, offset, ExecutableOnly::Yes, nullptr, nullptr, escape_mode);
  1304. String completion = match->path;
  1305. auto token_length = escape_token(name, escape_mode).length();
  1306. auto invariant_offset = token_length;
  1307. size_t static_offset = 0;
  1308. if (m_editor)
  1309. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1310. // Now that we have a program name starting with our token, we look at
  1311. // other program names starting with our token and cut off any mismatching
  1312. // characters.
  1313. Vector<Line::CompletionSuggestion> suggestions;
  1314. int index = match - cached_path.data();
  1315. for (int i = index - 1; i >= 0 && cached_path[i].path.starts_with(name); --i)
  1316. suggestions.append({ cached_path[i].path, " "sv });
  1317. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].path.starts_with(name); ++i)
  1318. suggestions.append({ cached_path[i].path, " "sv });
  1319. suggestions.append({ cached_path[index].path, " "sv });
  1320. for (auto& entry : suggestions) {
  1321. entry.input_offset = token_length;
  1322. entry.invariant_offset = invariant_offset;
  1323. entry.static_offset = static_offset;
  1324. }
  1325. return suggestions;
  1326. }
  1327. Vector<Line::CompletionSuggestion> Shell::complete_variable(StringView name, size_t offset)
  1328. {
  1329. Vector<Line::CompletionSuggestion> suggestions;
  1330. auto pattern = offset ? name.substring_view(0, offset) : ""sv;
  1331. auto invariant_offset = offset;
  1332. size_t static_offset = 0;
  1333. if (m_editor)
  1334. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1335. // Look at local variables.
  1336. for (auto& frame : m_local_frames) {
  1337. for (auto& variable : frame.local_variables) {
  1338. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1339. suggestions.append(variable.key);
  1340. }
  1341. }
  1342. // Look at the environment.
  1343. for (auto i = 0; environ[i]; ++i) {
  1344. StringView entry { environ[i], strlen(environ[i]) };
  1345. if (entry.starts_with(pattern)) {
  1346. auto parts = entry.split_view('=');
  1347. if (parts.is_empty() || parts.first().is_empty())
  1348. continue;
  1349. String name = parts.first();
  1350. if (suggestions.contains_slow(name))
  1351. continue;
  1352. suggestions.append(move(name));
  1353. }
  1354. }
  1355. for (auto& entry : suggestions) {
  1356. entry.input_offset = offset;
  1357. entry.invariant_offset = invariant_offset;
  1358. entry.static_offset = static_offset;
  1359. }
  1360. return suggestions;
  1361. }
  1362. Vector<Line::CompletionSuggestion> Shell::complete_user(StringView name, size_t offset)
  1363. {
  1364. Vector<Line::CompletionSuggestion> suggestions;
  1365. auto pattern = offset ? name.substring_view(0, offset) : ""sv;
  1366. auto invariant_offset = offset;
  1367. size_t static_offset = 0;
  1368. if (m_editor)
  1369. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1370. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1371. if (di.has_error())
  1372. return suggestions;
  1373. while (di.has_next()) {
  1374. String name = di.next_path();
  1375. if (name.starts_with(pattern)) {
  1376. suggestions.append(name);
  1377. auto& suggestion = suggestions.last();
  1378. suggestion.input_offset = offset;
  1379. suggestion.invariant_offset = invariant_offset;
  1380. suggestion.static_offset = static_offset;
  1381. }
  1382. }
  1383. return suggestions;
  1384. }
  1385. Vector<Line::CompletionSuggestion> Shell::complete_option(StringView program_name, StringView option, size_t offset, AST::Node const* command_node, AST::Node const* node)
  1386. {
  1387. if (command_node) {
  1388. auto program_results = complete_via_program_itself(offset, command_node, node, EscapeMode::Bareword, program_name);
  1389. if (!program_results.is_error())
  1390. return program_results.release_value();
  1391. }
  1392. size_t start = 0;
  1393. while (start < option.length() && option[start] == '-' && start < 2)
  1394. ++start;
  1395. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : ""sv;
  1396. auto invariant_offset = offset;
  1397. size_t static_offset = 0;
  1398. if (m_editor)
  1399. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1400. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1401. return {};
  1402. }
  1403. 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)
  1404. {
  1405. if (!command_node)
  1406. return Error::from_string_literal("Cannot complete null command");
  1407. if (command_node->would_execute())
  1408. return Error::from_string_literal("Refusing to complete nodes that would execute");
  1409. String program_name_storage;
  1410. if (known_program_name.is_null()) {
  1411. auto node = command_node->leftmost_trivial_literal();
  1412. if (!node)
  1413. return Error::from_string_literal("Cannot complete");
  1414. program_name_storage = node->run(*this)->resolve_as_string(*this);
  1415. known_program_name = program_name_storage;
  1416. }
  1417. auto program_name = known_program_name;
  1418. AST::Command completion_command;
  1419. completion_command.argv.append(program_name);
  1420. completion_command = expand_aliases({ completion_command }).last();
  1421. auto completion_utility_name = String::formatted("_complete_{}", completion_command.argv[0]);
  1422. if (binary_search(cached_path.span(), completion_utility_name, nullptr, RunnablePathComparator {}) != nullptr)
  1423. completion_command.argv[0] = completion_utility_name;
  1424. else if (!options.invoke_program_for_autocomplete)
  1425. return Error::from_string_literal("Refusing to use the program itself as completion source");
  1426. completion_command.argv.extend({ "--complete", "--" });
  1427. struct Visitor : public AST::NodeVisitor {
  1428. Visitor(Shell& shell, AST::Position position)
  1429. : shell(shell)
  1430. , completion_position(position)
  1431. {
  1432. lists.empend();
  1433. }
  1434. Shell& shell;
  1435. AST::Position completion_position;
  1436. Vector<Vector<String>> lists;
  1437. bool fail { false };
  1438. void push_list() { lists.empend(); }
  1439. Vector<String> pop_list() { return lists.take_last(); }
  1440. Vector<String>& list() { return lists.last(); }
  1441. bool should_include(AST::Node const* node) const { return node->position().end_offset <= completion_position.end_offset; }
  1442. virtual void visit(AST::BarewordLiteral const* node) override
  1443. {
  1444. if (should_include(node))
  1445. list().append(node->text());
  1446. }
  1447. virtual void visit(AST::BraceExpansion const* node) override
  1448. {
  1449. if (should_include(node))
  1450. list().extend(static_cast<AST::Node*>(const_cast<AST::BraceExpansion*>(node))->run(shell)->resolve_as_list(shell));
  1451. }
  1452. virtual void visit(AST::CommandLiteral const* node) override
  1453. {
  1454. if (should_include(node))
  1455. list().extend(node->command().argv);
  1456. }
  1457. virtual void visit(AST::DynamicEvaluate const* node) override
  1458. {
  1459. if (should_include(node))
  1460. fail = true;
  1461. }
  1462. virtual void visit(AST::DoubleQuotedString const* node) override
  1463. {
  1464. if (!should_include(node))
  1465. return;
  1466. push_list();
  1467. AST::NodeVisitor::visit(node);
  1468. auto list = pop_list();
  1469. StringBuilder builder;
  1470. builder.join(""sv, list);
  1471. this->list().append(builder.build());
  1472. }
  1473. virtual void visit(AST::Glob const* node) override
  1474. {
  1475. if (should_include(node))
  1476. list().append(node->text());
  1477. }
  1478. virtual void visit(AST::Heredoc const* node) override
  1479. {
  1480. if (!should_include(node))
  1481. return;
  1482. push_list();
  1483. AST::NodeVisitor::visit(node);
  1484. auto list = pop_list();
  1485. StringBuilder builder;
  1486. builder.join(""sv, list);
  1487. this->list().append(builder.build());
  1488. }
  1489. virtual void visit(AST::ImmediateExpression const* node) override
  1490. {
  1491. if (should_include(node))
  1492. fail = true;
  1493. }
  1494. virtual void visit(AST::Range const* node) override
  1495. {
  1496. if (!should_include(node))
  1497. return;
  1498. push_list();
  1499. node->start()->visit(*this);
  1500. list().append(pop_list().first());
  1501. }
  1502. virtual void visit(AST::SimpleVariable const* node) override
  1503. {
  1504. if (should_include(node))
  1505. list().extend(static_cast<AST::Node*>(const_cast<AST::SimpleVariable*>(node))->run(shell)->resolve_as_list(shell));
  1506. }
  1507. virtual void visit(AST::SpecialVariable const* node) override
  1508. {
  1509. if (should_include(node))
  1510. list().extend(static_cast<AST::Node*>(const_cast<AST::SpecialVariable*>(node))->run(shell)->resolve_as_list(shell));
  1511. }
  1512. virtual void visit(AST::Juxtaposition const* node) override
  1513. {
  1514. if (!should_include(node))
  1515. return;
  1516. push_list();
  1517. node->left()->visit(*this);
  1518. auto left = pop_list();
  1519. push_list();
  1520. node->right()->visit(*this);
  1521. auto right = pop_list();
  1522. StringBuilder builder;
  1523. for (auto& left_entry : left) {
  1524. for (auto& right_entry : right) {
  1525. builder.append(left_entry);
  1526. builder.append(right_entry);
  1527. list().append(builder.build());
  1528. builder.clear();
  1529. }
  1530. }
  1531. }
  1532. virtual void visit(AST::StringLiteral const* node) override
  1533. {
  1534. if (should_include(node))
  1535. list().append(node->text());
  1536. }
  1537. virtual void visit(AST::Tilde const* node) override
  1538. {
  1539. if (should_include(node))
  1540. list().extend(static_cast<AST::Node*>(const_cast<AST::Tilde*>(node))->run(shell)->resolve_as_list(shell));
  1541. }
  1542. virtual void visit(AST::PathRedirectionNode const*) override { }
  1543. virtual void visit(AST::CloseFdRedirection const*) override { }
  1544. virtual void visit(AST::Fd2FdRedirection const*) override { }
  1545. virtual void visit(AST::Execute const*) override { }
  1546. virtual void visit(AST::ReadRedirection const*) override { }
  1547. virtual void visit(AST::ReadWriteRedirection const*) override { }
  1548. virtual void visit(AST::WriteAppendRedirection const*) override { }
  1549. virtual void visit(AST::WriteRedirection const*) override { }
  1550. } visitor { *this, node ? node->position() : AST::Position() };
  1551. command_node->visit(visitor);
  1552. if (visitor.fail)
  1553. return Error::from_string_literal("Cannot complete");
  1554. completion_command.argv.extend(visitor.list());
  1555. completion_command.should_wait = true;
  1556. completion_command.redirections.append(AST::PathRedirection::create("/dev/null", STDERR_FILENO, AST::PathRedirection::Write));
  1557. completion_command.redirections.append(AST::PathRedirection::create("/dev/null", STDIN_FILENO, AST::PathRedirection::Read));
  1558. auto execute_node = make_ref_counted<AST::Execute>(
  1559. AST::Position {},
  1560. make_ref_counted<AST::CommandLiteral>(AST::Position {}, move(completion_command)),
  1561. true);
  1562. Vector<Line::CompletionSuggestion> suggestions;
  1563. auto timer = Core::Timer::create_single_shot(300, [&] {
  1564. Core::EventLoop::current().quit(1);
  1565. });
  1566. timer->start();
  1567. // Restrict the process to effectively readonly access to the FS.
  1568. auto scoped_promise = promise({
  1569. .exec_promises = "stdio rpath prot_exec no_error",
  1570. .unveils = {
  1571. { "/", "rx" },
  1572. },
  1573. });
  1574. {
  1575. TemporaryChange change(m_is_interactive, false);
  1576. execute_node->for_each_entry(*this, [&](NonnullRefPtr<AST::Value> entry) -> IterationDecision {
  1577. auto result = entry->resolve_as_string(*this);
  1578. JsonParser parser(result);
  1579. auto parsed_result = parser.parse();
  1580. if (parsed_result.is_error())
  1581. return IterationDecision::Continue;
  1582. auto parsed = parsed_result.release_value();
  1583. if (parsed.is_object()) {
  1584. auto& object = parsed.as_object();
  1585. auto kind = object.get("kind"sv).as_string_or("plain");
  1586. if (kind == "path") {
  1587. auto base = object.get("base"sv).as_string_or("");
  1588. auto part = object.get("part"sv).as_string_or("");
  1589. auto executable_only = object.get("executable_only"sv).to_bool(false) ? ExecutableOnly::Yes : ExecutableOnly::No;
  1590. suggestions.extend(complete_path(base, part, part.length(), executable_only, nullptr, nullptr));
  1591. } else if (kind == "program") {
  1592. auto name = object.get("name"sv).as_string_or("");
  1593. suggestions.extend(complete_program_name(name, name.length()));
  1594. } else if (kind == "proxy") {
  1595. if (m_completion_stack_info.size_free() < 4 * KiB) {
  1596. dbgln("Not enough stack space, recursion?");
  1597. return IterationDecision::Continue;
  1598. }
  1599. auto argv = object.get("argv"sv).as_string_or("");
  1600. dbgln("Proxy completion for {}", argv);
  1601. suggestions.extend(complete(argv));
  1602. } else if (kind == "plain") {
  1603. Line::CompletionSuggestion suggestion {
  1604. object.get("completion"sv).as_string_or(""),
  1605. object.get("trailing_trivia"sv).as_string_or(""),
  1606. object.get("display_trivia"sv).as_string_or(""),
  1607. };
  1608. suggestion.static_offset = object.get("static_offset"sv).to_u64(0);
  1609. suggestion.invariant_offset = object.get("invariant_offset"sv).to_u64(0);
  1610. suggestion.allow_commit_without_listing = object.get("allow_commit_without_listing"sv).to_bool(true);
  1611. suggestions.append(move(suggestion));
  1612. } else {
  1613. dbgln("LibLine: Unhandled completion kind: {}", kind);
  1614. }
  1615. } else {
  1616. suggestions.append(parsed.to_string());
  1617. }
  1618. return IterationDecision::Continue;
  1619. });
  1620. }
  1621. auto pgid = getpgrp();
  1622. tcsetpgrp(STDOUT_FILENO, pgid);
  1623. tcsetpgrp(STDIN_FILENO, pgid);
  1624. if (suggestions.is_empty())
  1625. return Error::from_string_literal("No results");
  1626. return suggestions;
  1627. }
  1628. Vector<Line::CompletionSuggestion> Shell::complete_immediate_function_name(StringView name, size_t offset)
  1629. {
  1630. Vector<Line::CompletionSuggestion> suggestions;
  1631. auto invariant_offset = offset;
  1632. size_t static_offset = 0;
  1633. if (m_editor)
  1634. m_editor->transform_suggestion_offsets(invariant_offset, static_offset);
  1635. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(fn_name) \
  1636. if (auto name_view = #fn_name##sv; name_view.starts_with(name)) \
  1637. suggestions.append({ name_view, " "sv });
  1638. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  1639. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  1640. for (auto& entry : suggestions) {
  1641. entry.input_offset = offset;
  1642. entry.invariant_offset = invariant_offset;
  1643. entry.static_offset = static_offset;
  1644. }
  1645. return suggestions;
  1646. }
  1647. void Shell::bring_cursor_to_beginning_of_a_line() const
  1648. {
  1649. struct winsize ws;
  1650. if (m_editor) {
  1651. ws = m_editor->terminal_size();
  1652. } else {
  1653. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1654. // Very annoying assumptions.
  1655. ws.ws_col = 80;
  1656. ws.ws_row = 25;
  1657. }
  1658. }
  1659. // Black with Cyan background.
  1660. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1661. String eol_mark = getenv("PROMPT_EOL_MARK");
  1662. if (eol_mark.is_null())
  1663. eol_mark = default_mark;
  1664. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1665. if (eol_mark_length >= ws.ws_col) {
  1666. eol_mark = default_mark;
  1667. eol_mark_length = 1;
  1668. }
  1669. fputs(eol_mark.characters(), stderr);
  1670. // We write a line's worth of whitespace to the terminal. This way, we ensure that
  1671. // the prompt ends up on a new line even if there is dangling output on the current line.
  1672. size_t fill_count = ws.ws_col - eol_mark_length;
  1673. auto fill_buffer = String::repeated(' ', fill_count);
  1674. fwrite(fill_buffer.characters(), 1, fill_count, stderr);
  1675. putc('\r', stderr);
  1676. }
  1677. bool Shell::has_history_event(StringView source)
  1678. {
  1679. struct : public AST::NodeVisitor {
  1680. virtual void visit(const AST::HistoryEvent* node) override
  1681. {
  1682. has_history_event = true;
  1683. AST::NodeVisitor::visit(node);
  1684. }
  1685. bool has_history_event { false };
  1686. } visitor;
  1687. auto ast = Parser { source, true }.parse();
  1688. if (!ast)
  1689. return false;
  1690. ast->visit(visitor);
  1691. return visitor.has_history_event;
  1692. }
  1693. bool Shell::read_single_line()
  1694. {
  1695. while (true) {
  1696. restore_ios();
  1697. bring_cursor_to_beginning_of_a_line();
  1698. auto line_result = m_editor->get_line(prompt());
  1699. if (line_result.is_error()) {
  1700. auto is_eof = line_result.error() == Line::Editor::Error::Eof;
  1701. auto is_empty = line_result.error() == Line::Editor::Error::Empty;
  1702. if (is_eof || is_empty) {
  1703. // Pretend the user tried to execute builtin_exit()
  1704. auto exit_code = run_command("exit"sv);
  1705. if (exit_code != 0) {
  1706. // If we didn't end up actually calling exit(), and the command didn't succeed, just pretend it's all okay
  1707. // unless we can't, then just quit anyway.
  1708. if (!is_empty)
  1709. continue;
  1710. }
  1711. }
  1712. Core::EventLoop::current().quit(1);
  1713. return false;
  1714. }
  1715. auto& line = line_result.value();
  1716. if (line.is_empty())
  1717. return true;
  1718. run_command(line);
  1719. if (!has_history_event(line))
  1720. m_editor->add_to_history(line);
  1721. return true;
  1722. }
  1723. }
  1724. void Shell::custom_event(Core::CustomEvent& event)
  1725. {
  1726. if (event.custom_type() == ReadLine) {
  1727. if (read_single_line())
  1728. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1729. return;
  1730. }
  1731. }
  1732. void Shell::notify_child_event()
  1733. {
  1734. Vector<u64> disowned_jobs;
  1735. // Workaround the fact that we can't receive *who* exactly changed state.
  1736. // The child might still be alive (and even running) when this signal is dispatched to us
  1737. // so just...repeat until we find a suitable child.
  1738. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1739. // until the next child event we can actually handle, so stop after spending a total of 5110us (~5ms) on it.
  1740. bool found_child = false;
  1741. size_t const max_tries = 10;
  1742. size_t valid_attempts = max_tries;
  1743. useconds_t backoff_usec = 20;
  1744. int backoff_multiplier = 2;
  1745. for (;;) {
  1746. if (found_child || --valid_attempts == 0)
  1747. break;
  1748. // Ignore stray SIGCHLD when there are no jobs.
  1749. if (jobs.is_empty())
  1750. return;
  1751. if (valid_attempts < max_tries - 1) {
  1752. usleep(backoff_usec);
  1753. backoff_usec *= backoff_multiplier;
  1754. }
  1755. for (auto& it : jobs) {
  1756. auto job_id = it.key;
  1757. auto& job = *it.value;
  1758. int wstatus = 0;
  1759. dbgln_if(SH_DEBUG, "waitpid({} = {}) = ...", job.pid(), job.cmd());
  1760. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1761. dbgln_if(SH_DEBUG, "... = {} - exited: {}, suspended: {}", child_pid, WIFEXITED(wstatus), WIFSTOPPED(wstatus));
  1762. if (child_pid < 0) {
  1763. if (errno == ECHILD) {
  1764. // The child process went away before we could process its death, just assume it exited all ok.
  1765. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1766. child_pid = job.pid();
  1767. } else {
  1768. VERIFY_NOT_REACHED();
  1769. }
  1770. }
  1771. if (child_pid == 0) {
  1772. // If the child existed, but wasn't dead.
  1773. if (job.is_suspended() || job.shell_did_continue()) {
  1774. // The job was suspended, and someone sent it a SIGCONT.
  1775. job.set_is_suspended(false);
  1776. if (job.shell_did_continue())
  1777. job.set_shell_did_continue(false);
  1778. found_child = true;
  1779. }
  1780. continue;
  1781. }
  1782. if (child_pid == job.pid()) {
  1783. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1784. auto signal = WTERMSIG(wstatus);
  1785. job.set_signalled(signal);
  1786. if (signal == SIGINT)
  1787. raise_error(ShellError::InternalControlFlowInterrupted, "Interrupted"sv, job.command().position);
  1788. else if (signal == SIGKILL)
  1789. raise_error(ShellError::InternalControlFlowKilled, "Interrupted"sv, job.command().position);
  1790. } else if (WIFEXITED(wstatus)) {
  1791. job.set_has_exit(WEXITSTATUS(wstatus));
  1792. } else if (WIFSTOPPED(wstatus)) {
  1793. job.unblock();
  1794. job.set_is_suspended(true);
  1795. }
  1796. found_child = true;
  1797. }
  1798. if (job.should_be_disowned())
  1799. disowned_jobs.append(job_id);
  1800. }
  1801. for (auto job_id : disowned_jobs) {
  1802. jobs.remove(job_id);
  1803. }
  1804. }
  1805. }
  1806. Shell::Shell()
  1807. : m_default_constructed(true)
  1808. {
  1809. push_frame("main").leak_frame();
  1810. int rc = gethostname(hostname, Shell::HostNameSize);
  1811. if (rc < 0)
  1812. perror("gethostname");
  1813. {
  1814. auto* pw = getpwuid(getuid());
  1815. if (pw) {
  1816. username = pw->pw_name;
  1817. home = pw->pw_dir;
  1818. setenv("HOME", pw->pw_dir, 1);
  1819. }
  1820. endpwent();
  1821. }
  1822. // For simplicity, start at the user's home directory.
  1823. this->cwd = home;
  1824. setenv("PWD", home.characters(), 1);
  1825. // Add the default PATH vars.
  1826. {
  1827. StringBuilder path;
  1828. auto const* path_env_ptr = getenv("PATH");
  1829. if (path_env_ptr != NULL)
  1830. path.append({ path_env_ptr, strlen(path_env_ptr) });
  1831. if (path.length())
  1832. path.append(":"sv);
  1833. path.append(DEFAULT_PATH_SV);
  1834. setenv("PATH", path.to_string().characters(), true);
  1835. }
  1836. cache_path();
  1837. }
  1838. Shell::Shell(Line::Editor& editor, bool attempt_interactive)
  1839. : m_editor(editor)
  1840. {
  1841. uid = getuid();
  1842. tcsetpgrp(0, getpgrp());
  1843. m_pid = getpid();
  1844. push_frame("main").leak_frame();
  1845. int rc = gethostname(hostname, Shell::HostNameSize);
  1846. if (rc < 0)
  1847. perror("gethostname");
  1848. auto istty = isatty(STDIN_FILENO);
  1849. m_is_interactive = attempt_interactive && istty;
  1850. if (istty) {
  1851. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1852. if (rc < 0)
  1853. perror("ttyname_r");
  1854. } else {
  1855. ttyname[0] = 0;
  1856. }
  1857. {
  1858. auto* cwd = getcwd(nullptr, 0);
  1859. this->cwd = cwd;
  1860. setenv("PWD", cwd, 1);
  1861. free(cwd);
  1862. }
  1863. {
  1864. auto* pw = getpwuid(getuid());
  1865. if (pw) {
  1866. username = pw->pw_name;
  1867. home = pw->pw_dir;
  1868. setenv("HOME", pw->pw_dir, 1);
  1869. }
  1870. endpwent();
  1871. }
  1872. directory_stack.append(cwd);
  1873. if (m_is_interactive) {
  1874. m_editor->load_history(get_history_path());
  1875. cache_path();
  1876. }
  1877. m_editor->register_key_input_callback('\n', [](Line::Editor& editor) {
  1878. auto ast = Parser(editor.line()).parse();
  1879. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1880. return true;
  1881. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1882. });
  1883. start_timer(3000);
  1884. }
  1885. Shell::~Shell()
  1886. {
  1887. if (m_default_constructed)
  1888. return;
  1889. stop_all_jobs();
  1890. if (!m_is_interactive)
  1891. return;
  1892. m_editor->save_history(get_history_path());
  1893. }
  1894. void Shell::stop_all_jobs()
  1895. {
  1896. if (!jobs.is_empty()) {
  1897. if (m_is_interactive && !m_is_subshell)
  1898. printf("Killing active jobs\n");
  1899. for (auto& entry : jobs) {
  1900. if (entry.value->is_suspended()) {
  1901. dbgln_if(SH_DEBUG, "Job {} is suspended", entry.value->pid());
  1902. kill_job(entry.value, SIGCONT);
  1903. }
  1904. kill_job(entry.value, SIGHUP);
  1905. }
  1906. usleep(10000); // Wait for a bit before killing the job
  1907. for (auto& entry : jobs) {
  1908. dbgln_if(SH_DEBUG, "Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1909. kill_job(entry.value, SIGKILL);
  1910. }
  1911. jobs.clear();
  1912. }
  1913. }
  1914. u64 Shell::find_last_job_id() const
  1915. {
  1916. u64 job_id = 0;
  1917. for (auto& entry : jobs) {
  1918. if (entry.value->job_id() > job_id)
  1919. job_id = entry.value->job_id();
  1920. }
  1921. return job_id;
  1922. }
  1923. Job const* Shell::find_job(u64 id, bool is_pid)
  1924. {
  1925. for (auto& entry : jobs) {
  1926. if (is_pid) {
  1927. if (entry.value->pid() == static_cast<int>(id))
  1928. return entry.value;
  1929. } else {
  1930. if (entry.value->job_id() == id)
  1931. return entry.value;
  1932. }
  1933. }
  1934. return nullptr;
  1935. }
  1936. void Shell::kill_job(Job const* job, int sig)
  1937. {
  1938. if (!job)
  1939. return;
  1940. if (killpg(job->pgid(), sig) < 0) {
  1941. if (kill(job->pid(), sig) < 0) {
  1942. if (errno != ESRCH)
  1943. perror("kill");
  1944. }
  1945. }
  1946. }
  1947. void Shell::save_to(JsonObject& object)
  1948. {
  1949. Core::Object::save_to(object);
  1950. object.set("working_directory", cwd);
  1951. object.set("username", username);
  1952. object.set("user_home_path", home);
  1953. object.set("user_id", uid);
  1954. object.set("directory_stack_size", directory_stack.size());
  1955. object.set("cd_history_size", cd_history.size());
  1956. // Jobs.
  1957. JsonArray job_objects;
  1958. for (auto& job_entry : jobs) {
  1959. JsonObject job_object;
  1960. job_object.set("pid", job_entry.value->pid());
  1961. job_object.set("pgid", job_entry.value->pgid());
  1962. job_object.set("running_time", job_entry.value->timer().elapsed());
  1963. job_object.set("command", job_entry.value->cmd());
  1964. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1965. job_objects.append(move(job_object));
  1966. }
  1967. object.set("jobs", move(job_objects));
  1968. }
  1969. void Shell::possibly_print_error() const
  1970. {
  1971. switch (m_error) {
  1972. case ShellError::EvaluatedSyntaxError:
  1973. warnln("Shell Syntax Error: {}", m_error_description);
  1974. break;
  1975. case ShellError::InvalidSliceContentsError:
  1976. case ShellError::InvalidGlobError:
  1977. case ShellError::NonExhaustiveMatchRules:
  1978. warnln("Shell: {}", m_error_description);
  1979. break;
  1980. case ShellError::OpenFailure:
  1981. warnln("Shell: Open failed for {}", m_error_description);
  1982. break;
  1983. case ShellError::OutOfMemory:
  1984. warnln("Shell: Hit an OOM situation");
  1985. break;
  1986. case ShellError::LaunchError:
  1987. warnln("Shell: {}", m_error_description);
  1988. break;
  1989. case ShellError::InternalControlFlowBreak:
  1990. case ShellError::InternalControlFlowContinue:
  1991. case ShellError::InternalControlFlowInterrupted:
  1992. case ShellError::InternalControlFlowKilled:
  1993. return;
  1994. case ShellError::None:
  1995. return;
  1996. }
  1997. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  1998. auto& source_position = m_source_position.value();
  1999. auto do_line = [&](auto line, auto& current_line) {
  2000. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  2001. warnln("{:>3}| {}", line, current_line);
  2002. if (is_in_range) {
  2003. warn("\x1b[31m");
  2004. size_t length_written_so_far = 0;
  2005. if (line == (i64)source_position.position->start_line.line_number) {
  2006. warn("{:~>{}}", "", 5 + source_position.position->start_line.line_column);
  2007. length_written_so_far += source_position.position->start_line.line_column;
  2008. } else {
  2009. warn("{:~>{}}", "", 5);
  2010. }
  2011. if (line == (i64)source_position.position->end_line.line_number) {
  2012. warn("{:^>{}}", "", source_position.position->end_line.line_column - length_written_so_far);
  2013. length_written_so_far += source_position.position->start_line.line_column;
  2014. } else {
  2015. warn("{:^>{}}", "", current_line.length() - length_written_so_far);
  2016. }
  2017. warnln("\x1b[0m");
  2018. }
  2019. };
  2020. int line = -1;
  2021. String current_line;
  2022. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  2023. if (!source_position.source_file.is_null()) {
  2024. auto file = Core::File::open(source_position.source_file, Core::OpenMode::ReadOnly);
  2025. if (file.is_error()) {
  2026. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file.error(), source_position.source_file);
  2027. return;
  2028. }
  2029. while (line < line_to_skip_to) {
  2030. if (file.value()->eof())
  2031. return;
  2032. current_line = file.value()->read_line();
  2033. ++line;
  2034. }
  2035. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  2036. do_line(line, current_line);
  2037. if (file.value()->eof())
  2038. current_line = "";
  2039. else
  2040. current_line = file.value()->read_line();
  2041. }
  2042. } else if (!source_position.literal_source_text.is_empty()) {
  2043. GenericLexer lexer { source_position.literal_source_text };
  2044. while (line < line_to_skip_to) {
  2045. if (lexer.is_eof())
  2046. return;
  2047. current_line = lexer.consume_line();
  2048. ++line;
  2049. }
  2050. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  2051. do_line(line, current_line);
  2052. if (lexer.is_eof())
  2053. current_line = "";
  2054. else
  2055. current_line = lexer.consume_line();
  2056. }
  2057. }
  2058. }
  2059. warnln();
  2060. }
  2061. Optional<int> Shell::resolve_job_spec(StringView str)
  2062. {
  2063. if (!str.starts_with('%'))
  2064. return {};
  2065. // %number -> job id <number>
  2066. if (auto number = str.substring_view(1).to_uint(); number.has_value())
  2067. return number.value();
  2068. // '%?str' -> iterate jobs and pick one with `str' in its command
  2069. // Note: must be quoted, since '?' will turn it into a glob - pretty ugly...
  2070. GenericLexer lexer { str.substring_view(1) };
  2071. if (!lexer.consume_specific('?'))
  2072. return {};
  2073. auto search_term = lexer.remaining();
  2074. for (auto& it : jobs) {
  2075. if (it.value->cmd().contains(search_term))
  2076. return it.key;
  2077. }
  2078. return {};
  2079. }
  2080. void Shell::timer_event(Core::TimerEvent& event)
  2081. {
  2082. event.accept();
  2083. if (m_is_subshell)
  2084. return;
  2085. auto const* autosave_env_ptr = getenv("HISTORY_AUTOSAVE_TIME_MS");
  2086. auto option = autosave_env_ptr != NULL ? StringView { autosave_env_ptr, strlen(autosave_env_ptr) } : StringView {};
  2087. auto time = option.to_uint();
  2088. if (!time.has_value() || time.value() == 0) {
  2089. m_history_autosave_time.clear();
  2090. stop_timer();
  2091. start_timer(3000);
  2092. return;
  2093. }
  2094. if (m_history_autosave_time != time) {
  2095. m_history_autosave_time = time.value();
  2096. stop_timer();
  2097. start_timer(m_history_autosave_time.value());
  2098. }
  2099. if (!m_history_autosave_time.has_value())
  2100. return;
  2101. if (m_editor && m_editor->is_history_dirty())
  2102. m_editor->save_history(get_history_path());
  2103. }
  2104. void FileDescriptionCollector::collect()
  2105. {
  2106. for (auto fd : m_fds)
  2107. close(fd);
  2108. m_fds.clear();
  2109. }
  2110. FileDescriptionCollector::~FileDescriptionCollector()
  2111. {
  2112. collect();
  2113. }
  2114. void FileDescriptionCollector::add(int fd)
  2115. {
  2116. m_fds.append(fd);
  2117. }
  2118. SavedFileDescriptors::SavedFileDescriptors(NonnullRefPtrVector<AST::Rewiring> const& intended_rewirings)
  2119. {
  2120. for (auto& rewiring : intended_rewirings) {
  2121. int new_fd = dup(rewiring.new_fd);
  2122. if (new_fd < 0) {
  2123. if (errno != EBADF)
  2124. perror("dup");
  2125. // The fd that will be overwritten isn't open right now,
  2126. // it will be cleaned up by the exec()-side collector
  2127. // and we have nothing to do here, so just ignore this error.
  2128. continue;
  2129. }
  2130. auto flags = fcntl(new_fd, F_GETFD);
  2131. auto rc = fcntl(new_fd, F_SETFD, flags | FD_CLOEXEC);
  2132. VERIFY(rc == 0);
  2133. m_saves.append({ rewiring.new_fd, new_fd });
  2134. m_collector.add(new_fd);
  2135. }
  2136. }
  2137. SavedFileDescriptors::~SavedFileDescriptors()
  2138. {
  2139. for (auto& save : m_saves) {
  2140. if (dup2(save.saved, save.original) < 0) {
  2141. perror("dup2(~SavedFileDescriptors)");
  2142. continue;
  2143. }
  2144. }
  2145. }
  2146. }