Shell.cpp 82 KB

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