Shell.cpp 84 KB

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