Shell.cpp 85 KB

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