Shell.cpp 85 KB

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