Shell.cpp 91 KB

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