Shell.cpp 88 KB

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