Shell.cpp 78 KB

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