Shell.cpp 86 KB

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