Shell.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012
  1. /*
  2. * Copyright (c) 2020, The SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Shell.h"
  27. #include "Execution.h"
  28. #include "Formatter.h"
  29. #include <AK/Debug.h>
  30. #include <AK/Function.h>
  31. #include <AK/LexicalPath.h>
  32. #include <AK/ScopeGuard.h>
  33. #include <AK/ScopedValueRollback.h>
  34. #include <AK/StringBuilder.h>
  35. #include <AK/TemporaryChange.h>
  36. #include <LibCore/ArgsParser.h>
  37. #include <LibCore/DirIterator.h>
  38. #include <LibCore/Event.h>
  39. #include <LibCore/EventLoop.h>
  40. #include <LibCore/File.h>
  41. #include <LibLine/Editor.h>
  42. #include <errno.h>
  43. #include <fcntl.h>
  44. #include <inttypes.h>
  45. #include <pwd.h>
  46. #include <signal.h>
  47. #include <stdio.h>
  48. #include <stdlib.h>
  49. #include <string.h>
  50. #include <sys/mman.h>
  51. #include <sys/stat.h>
  52. #include <sys/utsname.h>
  53. #include <sys/wait.h>
  54. #include <termios.h>
  55. #include <unistd.h>
  56. static bool s_disable_hyperlinks = false;
  57. extern char** environ;
  58. namespace Shell {
  59. void Shell::setup_signals()
  60. {
  61. if (m_should_reinstall_signal_handlers) {
  62. Core::EventLoop::register_signal(SIGCHLD, [this](int) {
  63. dbgln_if(SH_DEBUG, "SIGCHLD!");
  64. notify_child_event();
  65. });
  66. Core::EventLoop::register_signal(SIGTSTP, [this](auto) {
  67. auto job = current_job();
  68. kill_job(job, SIGTSTP);
  69. if (job) {
  70. job->set_is_suspended(true);
  71. job->unblock();
  72. }
  73. });
  74. }
  75. }
  76. void Shell::print_path(const String& path)
  77. {
  78. if (s_disable_hyperlinks || !m_is_interactive) {
  79. printf("%s", path.characters());
  80. return;
  81. }
  82. printf("\033]8;;file://%s%s\033\\%s\033]8;;\033\\", hostname, path.characters(), path.characters());
  83. }
  84. String Shell::prompt() const
  85. {
  86. auto build_prompt = [&]() -> String {
  87. auto* ps1 = getenv("PROMPT");
  88. if (!ps1) {
  89. if (uid == 0)
  90. return "# ";
  91. StringBuilder builder;
  92. builder.appendf("\033]0;%s@%s:%s\007", username.characters(), hostname, cwd.characters());
  93. builder.appendf("\033[31;1m%s\033[0m@\033[37;1m%s\033[0m:\033[32;1m%s\033[0m$> ", username.characters(), hostname, cwd.characters());
  94. return builder.to_string();
  95. }
  96. StringBuilder builder;
  97. for (char* ptr = ps1; *ptr; ++ptr) {
  98. if (*ptr == '\\') {
  99. ++ptr;
  100. if (!*ptr)
  101. break;
  102. switch (*ptr) {
  103. case 'X':
  104. builder.append("\033]0;");
  105. break;
  106. case 'a':
  107. builder.append(0x07);
  108. break;
  109. case 'e':
  110. builder.append(0x1b);
  111. break;
  112. case 'u':
  113. builder.append(username);
  114. break;
  115. case 'h':
  116. builder.append(hostname);
  117. break;
  118. case 'w': {
  119. String home_path = getenv("HOME");
  120. if (cwd.starts_with(home_path)) {
  121. builder.append('~');
  122. builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
  123. } else {
  124. builder.append(cwd);
  125. }
  126. break;
  127. }
  128. case 'p':
  129. builder.append(uid == 0 ? '#' : '$');
  130. break;
  131. }
  132. continue;
  133. }
  134. builder.append(*ptr);
  135. }
  136. return builder.to_string();
  137. };
  138. return build_prompt();
  139. }
  140. String Shell::expand_tilde(const String& expression)
  141. {
  142. VERIFY(expression.starts_with('~'));
  143. StringBuilder login_name;
  144. size_t first_slash_index = expression.length();
  145. for (size_t i = 1; i < expression.length(); ++i) {
  146. if (expression[i] == '/') {
  147. first_slash_index = i;
  148. break;
  149. }
  150. login_name.append(expression[i]);
  151. }
  152. StringBuilder path;
  153. for (size_t i = first_slash_index; i < expression.length(); ++i)
  154. path.append(expression[i]);
  155. if (login_name.is_empty()) {
  156. const char* home = getenv("HOME");
  157. if (!home) {
  158. auto passwd = getpwuid(getuid());
  159. VERIFY(passwd && passwd->pw_dir);
  160. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  161. }
  162. return String::format("%s/%s", home, path.to_string().characters());
  163. }
  164. auto passwd = getpwnam(login_name.to_string().characters());
  165. if (!passwd)
  166. return expression;
  167. VERIFY(passwd->pw_dir);
  168. return String::format("%s/%s", passwd->pw_dir, path.to_string().characters());
  169. }
  170. bool Shell::is_glob(const StringView& s)
  171. {
  172. for (size_t i = 0; i < s.length(); i++) {
  173. char c = s.characters_without_null_termination()[i];
  174. if (c == '*' || c == '?')
  175. return true;
  176. }
  177. return false;
  178. }
  179. Vector<StringView> Shell::split_path(const StringView& path)
  180. {
  181. Vector<StringView> parts;
  182. size_t substart = 0;
  183. for (size_t i = 0; i < path.length(); i++) {
  184. char ch = path[i];
  185. if (ch != '/')
  186. continue;
  187. size_t sublen = i - substart;
  188. if (sublen != 0)
  189. parts.append(path.substring_view(substart, sublen));
  190. substart = i + 1;
  191. }
  192. size_t taillen = path.length() - substart;
  193. if (taillen != 0)
  194. parts.append(path.substring_view(substart, taillen));
  195. return parts;
  196. }
  197. Vector<String> Shell::expand_globs(const StringView& path, StringView base)
  198. {
  199. auto explicitly_set_base = false;
  200. if (path.starts_with('/')) {
  201. base = "/";
  202. explicitly_set_base = true;
  203. }
  204. auto parts = split_path(path);
  205. String base_string = base;
  206. struct stat statbuf;
  207. if (lstat(base_string.characters(), &statbuf) < 0) {
  208. perror("lstat");
  209. return {};
  210. }
  211. StringBuilder resolved_base_path_builder;
  212. resolved_base_path_builder.append(Core::File::real_path_for(base));
  213. if (S_ISDIR(statbuf.st_mode))
  214. resolved_base_path_builder.append('/');
  215. auto resolved_base = resolved_base_path_builder.string_view();
  216. auto results = expand_globs(move(parts), resolved_base);
  217. if (explicitly_set_base && base == "/")
  218. resolved_base = resolved_base.substring_view(1, resolved_base.length() - 1);
  219. for (auto& entry : results) {
  220. entry = entry.substring(resolved_base.length(), entry.length() - resolved_base.length());
  221. if (entry.is_empty())
  222. entry = ".";
  223. }
  224. // Make the output predictable and nice.
  225. quick_sort(results);
  226. return results;
  227. }
  228. Vector<String> Shell::expand_globs(Vector<StringView> path_segments, const StringView& base)
  229. {
  230. if (path_segments.is_empty()) {
  231. String base_str = base;
  232. struct stat statbuf;
  233. if (lstat(base_str.characters(), &statbuf) < 0)
  234. return {};
  235. return { move(base_str) };
  236. }
  237. auto first_segment = path_segments.take_first();
  238. if (is_glob(first_segment)) {
  239. Vector<String> result;
  240. Core::DirIterator di(base, Core::DirIterator::SkipParentAndBaseDir);
  241. if (di.has_error())
  242. return {};
  243. while (di.has_next()) {
  244. String path = di.next_path();
  245. // Dotfiles have to be explicitly requested
  246. if (path[0] == '.' && first_segment[0] != '.')
  247. continue;
  248. if (path.matches(first_segment, CaseSensitivity::CaseSensitive)) {
  249. StringBuilder builder;
  250. builder.append(base);
  251. if (!base.ends_with('/'))
  252. builder.append('/');
  253. builder.append(path);
  254. result.append(expand_globs(path_segments, builder.string_view()));
  255. }
  256. }
  257. return result;
  258. } else {
  259. StringBuilder builder;
  260. builder.append(base);
  261. if (!base.ends_with('/'))
  262. builder.append('/');
  263. builder.append(first_segment);
  264. return expand_globs(move(path_segments), builder.string_view());
  265. }
  266. }
  267. Vector<AST::Command> Shell::expand_aliases(Vector<AST::Command> initial_commands)
  268. {
  269. Vector<AST::Command> commands;
  270. Function<void(AST::Command&)> resolve_aliases_and_append = [&](auto& command) {
  271. if (!command.argv.is_empty()) {
  272. auto alias = resolve_alias(command.argv[0]);
  273. if (!alias.is_null()) {
  274. auto argv0 = command.argv.take_first();
  275. auto subcommand_ast = Parser { alias }.parse();
  276. if (subcommand_ast) {
  277. while (subcommand_ast->is_execute()) {
  278. auto* ast = static_cast<AST::Execute*>(subcommand_ast.ptr());
  279. subcommand_ast = ast->command();
  280. }
  281. auto subcommand_nonnull = subcommand_ast.release_nonnull();
  282. NonnullRefPtr<AST::Node> substitute = adopt(*new AST::Join(subcommand_nonnull->position(),
  283. subcommand_nonnull,
  284. adopt(*new AST::CommandLiteral(subcommand_nonnull->position(), command))));
  285. auto res = substitute->run(*this);
  286. for (auto& subst_command : res->resolve_as_commands(*this)) {
  287. if (!subst_command.argv.is_empty() && subst_command.argv.first() == argv0) // Disallow an alias resolving to itself.
  288. commands.append(subst_command);
  289. else
  290. resolve_aliases_and_append(subst_command);
  291. }
  292. } else {
  293. commands.append(command);
  294. }
  295. } else {
  296. commands.append(command);
  297. }
  298. } else {
  299. commands.append(command);
  300. }
  301. };
  302. for (auto& command : initial_commands)
  303. resolve_aliases_and_append(command);
  304. return commands;
  305. }
  306. String Shell::resolve_path(String path) const
  307. {
  308. if (!path.starts_with('/'))
  309. path = String::format("%s/%s", cwd.characters(), path.characters());
  310. return Core::File::real_path_for(path);
  311. }
  312. Shell::LocalFrame* Shell::find_frame_containing_local_variable(const String& name)
  313. {
  314. for (size_t i = m_local_frames.size(); i > 0; --i) {
  315. auto& frame = m_local_frames[i - 1];
  316. if (frame.local_variables.contains(name))
  317. return &frame;
  318. }
  319. return nullptr;
  320. }
  321. RefPtr<AST::Value> Shell::lookup_local_variable(const String& name)
  322. {
  323. if (auto* frame = find_frame_containing_local_variable(name))
  324. return frame->local_variables.get(name).value();
  325. if (auto index = name.to_uint(); index.has_value())
  326. return get_argument(index.value());
  327. return nullptr;
  328. }
  329. RefPtr<AST::Value> Shell::get_argument(size_t index)
  330. {
  331. if (index == 0)
  332. return adopt(*new AST::StringValue(current_script));
  333. --index;
  334. if (auto argv = lookup_local_variable("ARGV")) {
  335. if (argv->is_list_without_resolution()) {
  336. AST::ListValue* list = static_cast<AST::ListValue*>(argv.ptr());
  337. if (list->values().size() <= index)
  338. return nullptr;
  339. return list->values().at(index);
  340. }
  341. if (index != 0)
  342. return nullptr;
  343. return argv;
  344. }
  345. return nullptr;
  346. }
  347. String Shell::local_variable_or(const String& name, const String& replacement)
  348. {
  349. auto value = lookup_local_variable(name);
  350. if (value) {
  351. StringBuilder builder;
  352. builder.join(" ", value->resolve_as_list(*this));
  353. return builder.to_string();
  354. }
  355. return replacement;
  356. }
  357. void Shell::set_local_variable(const String& name, RefPtr<AST::Value> value, bool only_in_current_frame)
  358. {
  359. if (!only_in_current_frame) {
  360. if (auto* frame = find_frame_containing_local_variable(name)) {
  361. frame->local_variables.set(name, move(value));
  362. return;
  363. }
  364. }
  365. m_local_frames.last().local_variables.set(name, move(value));
  366. }
  367. void Shell::unset_local_variable(const String& name, bool only_in_current_frame)
  368. {
  369. if (!only_in_current_frame) {
  370. if (auto* frame = find_frame_containing_local_variable(name))
  371. frame->local_variables.remove(name);
  372. return;
  373. }
  374. m_local_frames.last().local_variables.remove(name);
  375. }
  376. void Shell::define_function(String name, Vector<String> argnames, RefPtr<AST::Node> body)
  377. {
  378. add_entry_to_cache(name);
  379. m_functions.set(name, { name, move(argnames), move(body) });
  380. }
  381. bool Shell::has_function(const String& name)
  382. {
  383. return m_functions.contains(name);
  384. }
  385. bool Shell::invoke_function(const AST::Command& command, int& retval)
  386. {
  387. if (command.argv.is_empty())
  388. return false;
  389. StringView name = command.argv.first();
  390. TemporaryChange<String> script_change { current_script, name };
  391. auto function_option = m_functions.get(name);
  392. if (!function_option.has_value())
  393. return false;
  394. auto& function = function_option.value();
  395. if (!function.body) {
  396. retval = 0;
  397. return true;
  398. }
  399. if (command.argv.size() - 1 < function.arguments.size()) {
  400. raise_error(ShellError::EvaluatedSyntaxError, String::formatted("Expected at least {} arguments to {}, but got {}", function.arguments.size(), function.name, command.argv.size() - 1), command.position);
  401. retval = 1;
  402. return true;
  403. }
  404. auto frame = push_frame(String::formatted("function {}", function.name));
  405. size_t index = 0;
  406. for (auto& arg : function.arguments) {
  407. ++index;
  408. set_local_variable(arg, adopt(*new AST::StringValue(command.argv[index])), true);
  409. }
  410. auto argv = command.argv;
  411. argv.take_first();
  412. set_local_variable("ARGV", adopt(*new AST::ListValue(move(argv))), true);
  413. Core::EventLoop loop;
  414. setup_signals();
  415. function.body->run(*this);
  416. retval = last_return_code;
  417. return true;
  418. }
  419. String Shell::format(const StringView& source, ssize_t& cursor) const
  420. {
  421. Formatter formatter(source, cursor);
  422. auto result = formatter.format();
  423. cursor = formatter.cursor();
  424. return result;
  425. }
  426. Shell::Frame Shell::push_frame(String name)
  427. {
  428. m_local_frames.append(make<LocalFrame>(name, decltype(LocalFrame::local_variables) {}));
  429. dbgln_if(SH_DEBUG, "New frame '{}' at {:p}", name, &m_local_frames.last());
  430. return { m_local_frames, m_local_frames.last() };
  431. }
  432. void Shell::pop_frame()
  433. {
  434. VERIFY(m_local_frames.size() > 1);
  435. m_local_frames.take_last();
  436. }
  437. Shell::Frame::~Frame()
  438. {
  439. if (!should_destroy_frame)
  440. return;
  441. if (&frames.last() != &frame) {
  442. dbgln("Frame destruction order violation near {:p} (container = {:p}) in '{}'", &frame, this, frame.name);
  443. dbgln("Current frames:");
  444. for (auto& frame : frames)
  445. dbgln("- {:p}: {}", &frame, frame.name);
  446. VERIFY_NOT_REACHED();
  447. }
  448. frames.take_last();
  449. }
  450. String Shell::resolve_alias(const String& name) const
  451. {
  452. return m_aliases.get(name).value_or({});
  453. }
  454. bool Shell::is_runnable(const StringView& name)
  455. {
  456. if (access(name.to_string().characters(), X_OK) == 0)
  457. return true;
  458. return binary_search(
  459. cached_path.span(),
  460. name.to_string(),
  461. nullptr,
  462. [](auto& name, auto& program) { return strcmp(name.characters(), program.characters()); });
  463. }
  464. int Shell::run_command(const StringView& cmd, Optional<SourcePosition> source_position_override)
  465. {
  466. // The default-constructed mode of the shell
  467. // should not be used for execution!
  468. VERIFY(!m_default_constructed);
  469. take_error();
  470. ScopedValueRollback source_position_rollback { m_source_position };
  471. if (source_position_override.has_value())
  472. m_source_position = move(source_position_override);
  473. if (!m_source_position.has_value())
  474. m_source_position = SourcePosition { .source_file = {}, .literal_source_text = cmd, .position = {} };
  475. if (cmd.is_empty())
  476. return 0;
  477. auto command = Parser(cmd, m_is_interactive).parse();
  478. if (!command)
  479. return 0;
  480. if constexpr (SH_DEBUG) {
  481. dbgln("Command follows");
  482. command->dump(0);
  483. }
  484. if (command->is_syntax_error()) {
  485. auto& error_node = command->syntax_error_node();
  486. auto& position = error_node.position();
  487. raise_error(ShellError::EvaluatedSyntaxError, error_node.error_text(), position);
  488. }
  489. if (!has_error(ShellError::None)) {
  490. possibly_print_error();
  491. take_error();
  492. return 1;
  493. }
  494. tcgetattr(0, &termios);
  495. command->run(*this);
  496. if (!has_error(ShellError::None)) {
  497. possibly_print_error();
  498. take_error();
  499. return 1;
  500. }
  501. return last_return_code;
  502. }
  503. RefPtr<Job> Shell::run_command(const AST::Command& command)
  504. {
  505. FileDescriptionCollector fds;
  506. if (options.verbose)
  507. warnln("+ {}", command);
  508. // If the command is empty, store the redirections and apply them to all later commands.
  509. if (command.argv.is_empty() && !command.should_immediately_execute_next) {
  510. m_global_redirections.append(command.redirections);
  511. for (auto& next_in_chain : command.next_chain)
  512. run_tail(command, next_in_chain, last_return_code);
  513. return nullptr;
  514. }
  515. // Resolve redirections.
  516. NonnullRefPtrVector<AST::Rewiring> rewirings;
  517. auto resolve_redirection = [&](auto& redirection) -> IterationDecision {
  518. auto rewiring_result = redirection.apply();
  519. if (rewiring_result.is_error()) {
  520. if (!rewiring_result.error().is_empty())
  521. fprintf(stderr, "error: %s\n", rewiring_result.error().characters());
  522. return IterationDecision::Break;
  523. }
  524. auto& rewiring = rewiring_result.value();
  525. if (rewiring->fd_action != AST::Rewiring::Close::ImmediatelyCloseNew)
  526. rewirings.append(*rewiring);
  527. if (rewiring->fd_action == AST::Rewiring::Close::Old) {
  528. fds.add(rewiring->old_fd);
  529. } else if (rewiring->fd_action == AST::Rewiring::Close::New) {
  530. if (rewiring->new_fd != -1)
  531. fds.add(rewiring->new_fd);
  532. } else if (rewiring->fd_action == AST::Rewiring::Close::ImmediatelyCloseNew) {
  533. fds.add(rewiring->new_fd);
  534. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshNew) {
  535. VERIFY(rewiring->other_pipe_end);
  536. int pipe_fd[2];
  537. int rc = pipe(pipe_fd);
  538. if (rc < 0) {
  539. perror("pipe(RedirRefresh)");
  540. return IterationDecision::Break;
  541. }
  542. rewiring->new_fd = pipe_fd[1];
  543. rewiring->other_pipe_end->new_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  544. fds.add(pipe_fd[1]);
  545. } else if (rewiring->fd_action == AST::Rewiring::Close::RefreshOld) {
  546. VERIFY(rewiring->other_pipe_end);
  547. int pipe_fd[2];
  548. int rc = pipe(pipe_fd);
  549. if (rc < 0) {
  550. perror("pipe(RedirRefresh)");
  551. return IterationDecision::Break;
  552. }
  553. rewiring->old_fd = pipe_fd[1];
  554. rewiring->other_pipe_end->old_fd = pipe_fd[0]; // This fd will be added to the collection on one of the next iterations.
  555. fds.add(pipe_fd[1]);
  556. }
  557. return IterationDecision::Continue;
  558. };
  559. auto apply_rewirings = [&] {
  560. for (auto& rewiring : rewirings) {
  561. dbgln_if(SH_DEBUG, "in {}<{}>, dup2({}, {})", command.argv.is_empty() ? "(<Empty>)" : command.argv[0].characters(), getpid(), rewiring.old_fd, rewiring.new_fd);
  562. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  563. if (rc < 0) {
  564. perror("dup2(run)");
  565. return IterationDecision::Break;
  566. }
  567. // {new,old}_fd is closed via the `fds` collector, but rewiring.other_pipe_end->{new,old}_fd
  568. // isn't yet in that collector when the first child spawns.
  569. if (rewiring.other_pipe_end) {
  570. if (rewiring.fd_action == AST::Rewiring::Close::RefreshNew) {
  571. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->new_fd) < 0)
  572. perror("close other pipe end");
  573. } else if (rewiring.fd_action == AST::Rewiring::Close::RefreshOld) {
  574. if (rewiring.other_pipe_end && close(rewiring.other_pipe_end->old_fd) < 0)
  575. perror("close other pipe end");
  576. }
  577. }
  578. }
  579. return IterationDecision::Continue;
  580. };
  581. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, false };
  582. for (auto& redirection : m_global_redirections) {
  583. if (resolve_redirection(redirection) == IterationDecision::Break)
  584. return nullptr;
  585. }
  586. for (auto& redirection : command.redirections) {
  587. if (resolve_redirection(redirection) == IterationDecision::Break)
  588. return nullptr;
  589. }
  590. if (command.should_wait && run_builtin(command, rewirings, last_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. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  600. if (rc < 0) {
  601. perror("dup2(run)");
  602. return nullptr;
  603. }
  604. }
  605. if (invoke_function(command, last_return_code)) {
  606. for (auto& next_in_chain : command.next_chain)
  607. run_tail(command, next_in_chain, last_return_code);
  608. return nullptr;
  609. }
  610. }
  611. if (command.argv.is_empty()
  612. && !command.next_chain.is_empty()
  613. && command.should_immediately_execute_next
  614. && command.redirections.is_empty()
  615. && command.next_chain.first().node->should_override_execution_in_current_process()) {
  616. for (auto& next_in_chain : command.next_chain)
  617. run_tail(command, next_in_chain, last_return_code);
  618. return nullptr;
  619. }
  620. Vector<const char*> argv;
  621. Vector<String> copy_argv = command.argv;
  622. argv.ensure_capacity(command.argv.size() + 1);
  623. for (auto& arg : copy_argv)
  624. argv.append(arg.characters());
  625. argv.append(nullptr);
  626. int sync_pipe[2];
  627. if (pipe(sync_pipe) < 0) {
  628. perror("pipe");
  629. return nullptr;
  630. }
  631. pid_t child = fork();
  632. if (child < 0) {
  633. perror("fork");
  634. return nullptr;
  635. }
  636. if (child == 0) {
  637. close(sync_pipe[1]);
  638. m_is_subshell = true;
  639. m_pid = getpid();
  640. Core::EventLoop::notify_forked(Core::EventLoop::ForkEvent::Child);
  641. TemporaryChange signal_handler_install { m_should_reinstall_signal_handlers, true };
  642. if (apply_rewirings() == IterationDecision::Break)
  643. _exit(126);
  644. fds.collect();
  645. u8 c;
  646. while (read(sync_pipe[0], &c, 1) < 0) {
  647. if (errno != EINTR) {
  648. perror("read");
  649. // There's nothing interesting we can do here.
  650. break;
  651. }
  652. }
  653. dbgln_if(SH_DEBUG, "Synced up with parent, we're good to exec()");
  654. close(sync_pipe[0]);
  655. if (!m_is_subshell && command.should_wait)
  656. tcsetattr(0, TCSANOW, &default_termios);
  657. if (command.should_immediately_execute_next) {
  658. VERIFY(command.argv.is_empty());
  659. Core::EventLoop mainloop;
  660. setup_signals();
  661. for (auto& next_in_chain : command.next_chain)
  662. run_tail(command, next_in_chain, 0);
  663. _exit(last_return_code);
  664. }
  665. if (run_builtin(command, {}, last_return_code))
  666. _exit(last_return_code);
  667. if (invoke_function(command, last_return_code))
  668. _exit(last_return_code);
  669. // We no longer need the jobs here.
  670. jobs.clear();
  671. execute_process(move(argv));
  672. VERIFY_NOT_REACHED();
  673. }
  674. close(sync_pipe[0]);
  675. bool is_first = !command.pipeline || (command.pipeline && command.pipeline->pgid == -1);
  676. if (command.pipeline) {
  677. if (is_first) {
  678. command.pipeline->pgid = child;
  679. }
  680. }
  681. pid_t pgid = is_first ? child : (command.pipeline ? command.pipeline->pgid : child);
  682. if (!m_is_subshell || command.pipeline) {
  683. if (setpgid(child, pgid) < 0 && m_is_interactive)
  684. perror("setpgid");
  685. if (!m_is_subshell) {
  686. // There's no reason to care about the errors here
  687. // either we're in a tty, we're interactive, and this works
  688. // or we're not, and it fails - in which case, we don't need
  689. // stdin/stdout handoff to child processes anyway.
  690. tcsetpgrp(STDOUT_FILENO, pgid);
  691. tcsetpgrp(STDIN_FILENO, pgid);
  692. }
  693. }
  694. while (write(sync_pipe[1], "x", 1) < 0) {
  695. if (errno != EINTR) {
  696. perror("write");
  697. // There's nothing interesting we can do here.
  698. break;
  699. }
  700. }
  701. close(sync_pipe[1]);
  702. StringBuilder cmd;
  703. cmd.join(" ", command.argv);
  704. auto command_copy = AST::Command(command);
  705. // Clear the next chain if it's to be immediately executed
  706. // as the child will run this chain.
  707. if (command.should_immediately_execute_next)
  708. command_copy.next_chain.clear();
  709. auto job = Job::create(child, pgid, cmd.build(), find_last_job_id() + 1, move(command_copy));
  710. jobs.set((u64)child, job);
  711. job->on_exit = [this](auto job) {
  712. if (!job->exited())
  713. return;
  714. if (job->is_running_in_background() && job->should_announce_exit())
  715. warnln("Shell: Job {} ({}) exited\n", job->job_id(), job->cmd().characters());
  716. else if (job->signaled() && job->should_announce_signal())
  717. warnln("Shell: Job {} ({}) {}\n", job->job_id(), job->cmd().characters(), strsignal(job->termination_signal()));
  718. last_return_code = job->exit_code();
  719. job->disown();
  720. run_tail(job);
  721. };
  722. fds.collect();
  723. return *job;
  724. }
  725. void Shell::execute_process(Vector<const char*>&& argv)
  726. {
  727. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  728. if (rc < 0) {
  729. int saved_errno = errno;
  730. struct stat st;
  731. if (stat(argv[0], &st)) {
  732. fprintf(stderr, "stat(%s): %s\n", argv[0], strerror(errno));
  733. // Return code 127 on command not found.
  734. _exit(127);
  735. }
  736. if (!(st.st_mode & S_IXUSR)) {
  737. fprintf(stderr, "%s: Not executable\n", argv[0]);
  738. // Return code 126 when file is not executable.
  739. _exit(126);
  740. }
  741. if (saved_errno == ENOENT) {
  742. int shebang_fd = open(argv[0], O_RDONLY);
  743. auto close_argv = ScopeGuard([shebang_fd]() { if (shebang_fd >= 0) close(shebang_fd); });
  744. char shebang[256] {};
  745. ssize_t num_read = -1;
  746. if ((shebang_fd >= 0) && ((num_read = read(shebang_fd, shebang, sizeof(shebang))) >= 2) && (StringView(shebang).starts_with("#!"))) {
  747. StringView shebang_path_view(&shebang[2], num_read - 2);
  748. Optional<size_t> newline_pos = shebang_path_view.find_first_of("\n\r");
  749. shebang[newline_pos.has_value() ? (newline_pos.value() + 2) : num_read] = '\0';
  750. argv[0] = shebang;
  751. int rc = execvp(argv[0], const_cast<char* const*>(argv.data()));
  752. if (rc < 0)
  753. fprintf(stderr, "%s: Invalid interpreter \"%s\": %s\n", argv[0], &shebang[2], strerror(errno));
  754. } else
  755. fprintf(stderr, "%s: Command not found.\n", argv[0]);
  756. } else {
  757. if (S_ISDIR(st.st_mode)) {
  758. fprintf(stderr, "Shell: %s: Is a directory\n", argv[0]);
  759. _exit(126);
  760. }
  761. fprintf(stderr, "execvp(%s): %s\n", argv[0], strerror(saved_errno));
  762. }
  763. _exit(126);
  764. }
  765. VERIFY_NOT_REACHED();
  766. }
  767. void Shell::run_tail(const AST::Command& invoking_command, const AST::NodeWithAction& next_in_chain, int head_exit_code)
  768. {
  769. if (m_error != ShellError::None) {
  770. possibly_print_error();
  771. if (!is_control_flow(m_error))
  772. take_error();
  773. return;
  774. }
  775. auto evaluate = [&] {
  776. if (next_in_chain.node->would_execute()) {
  777. next_in_chain.node->run(*this);
  778. return;
  779. }
  780. auto node = next_in_chain.node;
  781. if (!invoking_command.should_wait)
  782. node = adopt(static_cast<AST::Node&>(*new AST::Background(next_in_chain.node->position(), move(node))));
  783. adopt(static_cast<AST::Node&>(*new AST::Execute(next_in_chain.node->position(), move(node))))->run(*this);
  784. };
  785. switch (next_in_chain.action) {
  786. case AST::NodeWithAction::And:
  787. if (head_exit_code == 0)
  788. evaluate();
  789. break;
  790. case AST::NodeWithAction::Or:
  791. if (head_exit_code != 0)
  792. evaluate();
  793. break;
  794. case AST::NodeWithAction::Sequence:
  795. evaluate();
  796. break;
  797. }
  798. }
  799. void Shell::run_tail(RefPtr<Job> job)
  800. {
  801. if (auto cmd = job->command_ptr()) {
  802. deferred_invoke([=, this](auto&) {
  803. for (auto& next_in_chain : cmd->next_chain) {
  804. run_tail(*cmd, next_in_chain, job->exit_code());
  805. }
  806. });
  807. }
  808. }
  809. NonnullRefPtrVector<Job> Shell::run_commands(Vector<AST::Command>& commands)
  810. {
  811. if (m_error != ShellError::None) {
  812. possibly_print_error();
  813. if (!is_control_flow(m_error))
  814. take_error();
  815. return {};
  816. }
  817. NonnullRefPtrVector<Job> spawned_jobs;
  818. for (auto& command : commands) {
  819. if constexpr (SH_DEBUG) {
  820. dbgln("Command");
  821. for (auto& arg : command.argv)
  822. dbgln("argv: {}", arg);
  823. for (auto& redir : command.redirections) {
  824. if (redir.is_path_redirection()) {
  825. auto path_redir = (const AST::PathRedirection*)&redir;
  826. dbgln("redir path '{}' <-({})-> {}", path_redir->path, (int)path_redir->direction, path_redir->fd);
  827. } else if (redir.is_fd_redirection()) {
  828. auto* fdredir = (const AST::FdRedirection*)&redir;
  829. dbgln("redir fd {} -> {}", fdredir->old_fd, fdredir->new_fd);
  830. } else if (redir.is_close_redirection()) {
  831. auto close_redir = (const AST::CloseRedirection*)&redir;
  832. dbgln("close fd {}", close_redir->fd);
  833. } else {
  834. VERIFY_NOT_REACHED();
  835. }
  836. }
  837. }
  838. auto job = run_command(command);
  839. if (!job)
  840. continue;
  841. spawned_jobs.append(*job);
  842. if (command.should_wait) {
  843. block_on_job(job);
  844. } else {
  845. job->set_running_in_background(true);
  846. if (!command.is_pipe_source && command.should_notify_if_in_background)
  847. job->set_should_announce_exit(true);
  848. }
  849. }
  850. if (m_error != ShellError::None) {
  851. possibly_print_error();
  852. if (!is_control_flow(m_error))
  853. take_error();
  854. }
  855. return spawned_jobs;
  856. }
  857. bool Shell::run_file(const String& filename, bool explicitly_invoked)
  858. {
  859. TemporaryChange script_change { current_script, filename };
  860. TemporaryChange interactive_change { m_is_interactive, false };
  861. TemporaryChange<Optional<SourcePosition>> source_change { m_source_position, SourcePosition { .source_file = filename, .literal_source_text = {}, .position = {} } };
  862. auto file_result = Core::File::open(filename, Core::File::ReadOnly);
  863. if (file_result.is_error()) {
  864. auto error = String::formatted("'{}': {}", escape_token_for_single_quotes(filename), file_result.error());
  865. if (explicitly_invoked)
  866. raise_error(ShellError::OpenFailure, error);
  867. else
  868. dbgln("open() failed for {}", error);
  869. return false;
  870. }
  871. auto file = file_result.value();
  872. auto data = file->read_all();
  873. return run_command(data) == 0;
  874. }
  875. void Shell::restore_ios()
  876. {
  877. if (m_is_subshell)
  878. return;
  879. tcsetattr(0, TCSANOW, &termios);
  880. tcsetpgrp(STDOUT_FILENO, m_pid);
  881. tcsetpgrp(STDIN_FILENO, m_pid);
  882. }
  883. void Shell::block_on_pipeline(RefPtr<AST::Pipeline> pipeline)
  884. {
  885. if (!pipeline)
  886. return;
  887. for (auto& it : jobs) {
  888. if (auto cmd = it.value->command_ptr(); cmd->pipeline == pipeline && cmd->is_pipe_source)
  889. block_on_job(it.value);
  890. }
  891. }
  892. void Shell::block_on_job(RefPtr<Job> job)
  893. {
  894. TemporaryChange<const Job*> current_job { m_current_job, job.ptr() };
  895. if (!job)
  896. return;
  897. if (job->is_suspended() && !job->shell_did_continue())
  898. return; // We cannot wait for a suspended job.
  899. ScopeGuard io_restorer { [&]() {
  900. if (job->exited() && !job->is_running_in_background()) {
  901. restore_ios();
  902. }
  903. } };
  904. bool job_exited { false };
  905. job->on_exit = [&, old_exit = move(job->on_exit)](auto job) {
  906. if (old_exit)
  907. old_exit(job);
  908. job_exited = true;
  909. };
  910. if (job->exited())
  911. return;
  912. while (!job_exited)
  913. Core::EventLoop::current().pump();
  914. // If the job is part of a pipeline, wait for the rest of the members too.
  915. if (auto command = job->command_ptr())
  916. block_on_pipeline(command->pipeline);
  917. }
  918. String Shell::get_history_path()
  919. {
  920. if (auto histfile = getenv("HISTFILE"))
  921. return { histfile };
  922. return String::formatted("{}/.history", home);
  923. }
  924. String Shell::escape_token_for_single_quotes(const String& token)
  925. {
  926. // `foo bar \n '` -> `'foo bar \n '"'"`
  927. StringBuilder builder;
  928. builder.append("'");
  929. auto started_single_quote = true;
  930. for (auto c : token) {
  931. switch (c) {
  932. case '\'':
  933. builder.append("\"'\"");
  934. started_single_quote = false;
  935. continue;
  936. default:
  937. builder.append(c);
  938. if (!started_single_quote) {
  939. started_single_quote = true;
  940. builder.append("'");
  941. }
  942. break;
  943. }
  944. }
  945. if (started_single_quote)
  946. builder.append("'");
  947. return builder.build();
  948. }
  949. String Shell::escape_token_for_double_quotes(const String& token)
  950. {
  951. // `foo bar \n $x 'blah "hello` -> `"foo bar \\n $x 'blah \"hello"`
  952. StringBuilder builder;
  953. builder.append('"');
  954. for (auto c : token) {
  955. switch (c) {
  956. case '\"':
  957. builder.append("\\\"");
  958. continue;
  959. case '\\':
  960. builder.append("\\\\");
  961. continue;
  962. default:
  963. builder.append(c);
  964. break;
  965. }
  966. }
  967. builder.append('"');
  968. return builder.build();
  969. }
  970. bool Shell::is_special(char c)
  971. {
  972. switch (c) {
  973. case '\'':
  974. case '"':
  975. case '$':
  976. case '|':
  977. case '>':
  978. case '<':
  979. case '(':
  980. case ')':
  981. case '{':
  982. case '}':
  983. case '&':
  984. case '\\':
  985. case ' ':
  986. return true;
  987. default:
  988. return false;
  989. }
  990. }
  991. String Shell::escape_token(const String& token)
  992. {
  993. StringBuilder builder;
  994. for (auto c : token) {
  995. if (is_special(c))
  996. builder.append('\\');
  997. builder.append(c);
  998. }
  999. return builder.build();
  1000. }
  1001. String Shell::unescape_token(const String& token)
  1002. {
  1003. StringBuilder builder;
  1004. enum {
  1005. Free,
  1006. Escaped
  1007. } state { Free };
  1008. for (auto c : token) {
  1009. switch (state) {
  1010. case Escaped:
  1011. builder.append(c);
  1012. state = Free;
  1013. break;
  1014. case Free:
  1015. if (c == '\\')
  1016. state = Escaped;
  1017. else
  1018. builder.append(c);
  1019. break;
  1020. }
  1021. }
  1022. if (state == Escaped)
  1023. builder.append('\\');
  1024. return builder.build();
  1025. }
  1026. void Shell::cache_path()
  1027. {
  1028. if (!m_is_interactive)
  1029. return;
  1030. if (!cached_path.is_empty())
  1031. cached_path.clear_with_capacity();
  1032. // Add shell builtins to the cache.
  1033. for (const auto& builtin_name : builtin_names)
  1034. cached_path.append(escape_token(builtin_name));
  1035. // Add functions to the cache.
  1036. for (auto& function : m_functions) {
  1037. auto name = escape_token(function.key);
  1038. if (cached_path.contains_slow(name))
  1039. continue;
  1040. cached_path.append(name);
  1041. }
  1042. // Add aliases to the cache.
  1043. for (const auto& alias : m_aliases) {
  1044. auto name = escape_token(alias.key);
  1045. if (cached_path.contains_slow(name))
  1046. continue;
  1047. cached_path.append(name);
  1048. }
  1049. String path = getenv("PATH");
  1050. if (!path.is_empty()) {
  1051. auto directories = path.split(':');
  1052. for (const auto& directory : directories) {
  1053. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1054. while (programs.has_next()) {
  1055. auto program = programs.next_path();
  1056. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  1057. auto escaped_name = escape_token(program);
  1058. if (cached_path.contains_slow(escaped_name))
  1059. continue;
  1060. if (access(program_path.characters(), X_OK) == 0)
  1061. cached_path.append(escaped_name);
  1062. }
  1063. }
  1064. }
  1065. quick_sort(cached_path);
  1066. }
  1067. void Shell::add_entry_to_cache(const String& entry)
  1068. {
  1069. size_t index = 0;
  1070. auto match = binary_search(
  1071. cached_path.span(),
  1072. entry,
  1073. &index,
  1074. [](auto& name, auto& program) { return strcmp(name.characters(), program.characters()); });
  1075. if (match)
  1076. return;
  1077. while (index < cached_path.size() && strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  1078. index++;
  1079. }
  1080. cached_path.insert(index, entry);
  1081. }
  1082. void Shell::highlight(Line::Editor& editor) const
  1083. {
  1084. auto line = editor.line();
  1085. Parser parser(line, m_is_interactive);
  1086. auto ast = parser.parse();
  1087. if (!ast)
  1088. return;
  1089. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  1090. }
  1091. Vector<Line::CompletionSuggestion> Shell::complete()
  1092. {
  1093. auto line = m_editor->line(m_editor->cursor());
  1094. Parser parser(line, m_is_interactive);
  1095. auto ast = parser.parse();
  1096. if (!ast)
  1097. return {};
  1098. return ast->complete_for_editor(*this, line.length());
  1099. }
  1100. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  1101. {
  1102. auto token = offset ? part.substring_view(0, offset) : "";
  1103. String path;
  1104. ssize_t last_slash = token.length() - 1;
  1105. while (last_slash >= 0 && token[last_slash] != '/')
  1106. --last_slash;
  1107. StringBuilder path_builder;
  1108. auto init_slash_part = token.substring_view(0, last_slash + 1);
  1109. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  1110. // Depending on the base, we will have to prepend cwd.
  1111. if (base.is_empty()) {
  1112. // '' /foo -> absolute
  1113. // '' foo -> relative
  1114. if (!token.starts_with('/'))
  1115. path_builder.append(cwd);
  1116. path_builder.append('/');
  1117. path_builder.append(init_slash_part);
  1118. } else {
  1119. // /foo * -> absolute
  1120. // foo * -> relative
  1121. if (!base.starts_with('/'))
  1122. path_builder.append(cwd);
  1123. path_builder.append('/');
  1124. path_builder.append(base);
  1125. path_builder.append('/');
  1126. path_builder.append(init_slash_part);
  1127. }
  1128. path = path_builder.build();
  1129. token = last_slash_part;
  1130. // the invariant part of the token is actually just the last segment
  1131. // e. in `cd /foo/bar', 'bar' is the invariant
  1132. // since we are not suggesting anything starting with
  1133. // `/foo/', but rather just `bar...'
  1134. auto token_length = escape_token(token).length();
  1135. if (m_editor)
  1136. m_editor->suggest(token_length, last_slash + 1);
  1137. // only suggest dot-files if path starts with a dot
  1138. Core::DirIterator files(path,
  1139. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1140. Vector<Line::CompletionSuggestion> suggestions;
  1141. while (files.has_next()) {
  1142. auto file = files.next_path();
  1143. if (file.starts_with(token)) {
  1144. struct stat program_status;
  1145. String file_path = String::format("%s/%s", path.characters(), file.characters());
  1146. int stat_error = stat(file_path.characters(), &program_status);
  1147. if (!stat_error) {
  1148. if (S_ISDIR(program_status.st_mode)) {
  1149. suggestions.append({ escape_token(file), "/" });
  1150. } else {
  1151. suggestions.append({ escape_token(file), " " });
  1152. }
  1153. suggestions.last().input_offset = token_length;
  1154. }
  1155. }
  1156. }
  1157. return suggestions;
  1158. }
  1159. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  1160. {
  1161. auto match = binary_search(
  1162. cached_path.span(),
  1163. name,
  1164. nullptr,
  1165. [](auto& name, auto& program) { return strncmp(name.characters(), program.characters(), name.length()); });
  1166. if (!match)
  1167. return complete_path("", name, offset);
  1168. String completion = *match;
  1169. auto token_length = escape_token(name).length();
  1170. if (m_editor)
  1171. m_editor->suggest(token_length, 0);
  1172. // Now that we have a program name starting with our token, we look at
  1173. // other program names starting with our token and cut off any mismatching
  1174. // characters.
  1175. Vector<Line::CompletionSuggestion> suggestions;
  1176. int index = match - cached_path.data();
  1177. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  1178. suggestions.append({ cached_path[i], " " });
  1179. suggestions.last().input_offset = token_length;
  1180. }
  1181. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  1182. suggestions.append({ cached_path[i], " " });
  1183. suggestions.last().input_offset = token_length;
  1184. }
  1185. suggestions.append({ cached_path[index], " " });
  1186. suggestions.last().input_offset = token_length;
  1187. return suggestions;
  1188. }
  1189. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  1190. {
  1191. Vector<Line::CompletionSuggestion> suggestions;
  1192. auto pattern = offset ? name.substring_view(0, offset) : "";
  1193. if (m_editor)
  1194. m_editor->suggest(offset);
  1195. // Look at local variables.
  1196. for (auto& frame : m_local_frames) {
  1197. for (auto& variable : frame.local_variables) {
  1198. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1199. suggestions.append(variable.key);
  1200. }
  1201. }
  1202. // Look at the environment.
  1203. for (auto i = 0; environ[i]; ++i) {
  1204. auto entry = StringView { environ[i] };
  1205. if (entry.starts_with(pattern)) {
  1206. auto parts = entry.split_view('=');
  1207. if (parts.is_empty() || parts.first().is_empty())
  1208. continue;
  1209. String name = parts.first();
  1210. if (suggestions.contains_slow(name))
  1211. continue;
  1212. suggestions.append(move(name));
  1213. suggestions.last().input_offset = offset;
  1214. }
  1215. }
  1216. return suggestions;
  1217. }
  1218. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  1219. {
  1220. Vector<Line::CompletionSuggestion> suggestions;
  1221. auto pattern = offset ? name.substring_view(0, offset) : "";
  1222. if (m_editor)
  1223. m_editor->suggest(offset);
  1224. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1225. if (di.has_error())
  1226. return suggestions;
  1227. while (di.has_next()) {
  1228. String name = di.next_path();
  1229. if (name.starts_with(pattern)) {
  1230. suggestions.append(name);
  1231. suggestions.last().input_offset = offset;
  1232. }
  1233. }
  1234. return suggestions;
  1235. }
  1236. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  1237. {
  1238. size_t start = 0;
  1239. while (start < option.length() && option[start] == '-' && start < 2)
  1240. ++start;
  1241. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  1242. if (m_editor)
  1243. m_editor->suggest(offset);
  1244. Vector<Line::CompletionSuggestion> suggestions;
  1245. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1246. // FIXME: Figure out how to do this stuff.
  1247. if (has_builtin(program_name)) {
  1248. // Complete builtins.
  1249. if (program_name == "setopt") {
  1250. bool negate = false;
  1251. if (option_pattern.starts_with("no_")) {
  1252. negate = true;
  1253. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  1254. }
  1255. auto maybe_negate = [&](const StringView& view) {
  1256. static StringBuilder builder;
  1257. builder.clear();
  1258. builder.append("--");
  1259. if (negate)
  1260. builder.append("no_");
  1261. builder.append(view);
  1262. return builder.to_string();
  1263. };
  1264. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  1265. if (StringView { #name }.starts_with(option_pattern)) { \
  1266. suggestions.append(maybe_negate(#name)); \
  1267. suggestions.last().input_offset = offset; \
  1268. }
  1269. ENUMERATE_SHELL_OPTIONS();
  1270. #undef __ENUMERATE_SHELL_OPTION
  1271. return suggestions;
  1272. }
  1273. }
  1274. return suggestions;
  1275. }
  1276. Vector<Line::CompletionSuggestion> Shell::complete_immediate_function_name(const String& name, size_t offset)
  1277. {
  1278. Vector<Line::CompletionSuggestion> suggestions;
  1279. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(fn_name) \
  1280. if (auto name_view = StringView { #fn_name }; name_view.starts_with(name)) { \
  1281. suggestions.append({ name_view, " " }); \
  1282. suggestions.last().input_offset = offset; \
  1283. }
  1284. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS();
  1285. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  1286. if (m_editor)
  1287. m_editor->suggest(offset);
  1288. return suggestions;
  1289. }
  1290. void Shell::bring_cursor_to_beginning_of_a_line() const
  1291. {
  1292. struct winsize ws;
  1293. if (m_editor) {
  1294. ws = m_editor->terminal_size();
  1295. } else {
  1296. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1297. // Very annoying assumptions.
  1298. ws.ws_col = 80;
  1299. ws.ws_row = 25;
  1300. }
  1301. }
  1302. // Black with Cyan background.
  1303. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1304. String eol_mark = getenv("PROMPT_EOL_MARK");
  1305. if (eol_mark.is_null())
  1306. eol_mark = default_mark;
  1307. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1308. if (eol_mark_length >= ws.ws_col) {
  1309. eol_mark = default_mark;
  1310. eol_mark_length = 1;
  1311. }
  1312. fputs(eol_mark.characters(), stderr);
  1313. for (auto i = eol_mark_length; i < ws.ws_col; ++i)
  1314. putc(' ', stderr);
  1315. putc('\r', stderr);
  1316. }
  1317. bool Shell::has_history_event(StringView source)
  1318. {
  1319. struct : public AST::NodeVisitor {
  1320. virtual void visit(const AST::HistoryEvent* node)
  1321. {
  1322. has_history_event = true;
  1323. AST::NodeVisitor::visit(node);
  1324. }
  1325. bool has_history_event { false };
  1326. } visitor;
  1327. auto ast = Parser { source, true }.parse();
  1328. if (!ast)
  1329. return false;
  1330. ast->visit(visitor);
  1331. return visitor.has_history_event;
  1332. }
  1333. bool Shell::read_single_line()
  1334. {
  1335. restore_ios();
  1336. bring_cursor_to_beginning_of_a_line();
  1337. auto line_result = m_editor->get_line(prompt());
  1338. if (line_result.is_error()) {
  1339. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1340. // Pretend the user tried to execute builtin_exit()
  1341. run_command("exit");
  1342. return read_single_line();
  1343. } else {
  1344. Core::EventLoop::current().quit(1);
  1345. return false;
  1346. }
  1347. }
  1348. auto& line = line_result.value();
  1349. if (line.is_empty())
  1350. return true;
  1351. run_command(line);
  1352. if (!has_history_event(line))
  1353. m_editor->add_to_history(line);
  1354. return true;
  1355. }
  1356. void Shell::custom_event(Core::CustomEvent& event)
  1357. {
  1358. if (event.custom_type() == ReadLine) {
  1359. if (read_single_line())
  1360. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1361. return;
  1362. }
  1363. }
  1364. void Shell::notify_child_event()
  1365. {
  1366. Vector<u64> disowned_jobs;
  1367. // Workaround the fact that we can't receive *who* exactly changed state.
  1368. // The child might still be alive (and even running) when this signal is dispatched to us
  1369. // so just...repeat until we find a suitable child.
  1370. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1371. // until the next child event we can actually handle.
  1372. bool found_child = false;
  1373. do {
  1374. // Ignore stray SIGCHLD when there are no jobs.
  1375. if (jobs.is_empty())
  1376. return;
  1377. for (auto& it : jobs) {
  1378. auto job_id = it.key;
  1379. auto& job = *it.value;
  1380. int wstatus = 0;
  1381. dbgln_if(SH_DEBUG, "waitpid({} = {}) = ...", job.pid(), job.cmd());
  1382. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1383. dbgln_if(SH_DEBUG, "... = {} - exited: {}, suspended: {}", child_pid, WIFEXITED(wstatus), WIFSTOPPED(wstatus));
  1384. if (child_pid < 0) {
  1385. if (errno == ECHILD) {
  1386. // The child process went away before we could process its death, just assume it exited all ok.
  1387. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1388. child_pid = job.pid();
  1389. } else {
  1390. VERIFY_NOT_REACHED();
  1391. }
  1392. }
  1393. if (child_pid == 0) {
  1394. // If the child existed, but wasn't dead.
  1395. if (job.is_suspended() && job.shell_did_continue()) {
  1396. // The job was suspended, and we sent it a SIGCONT.
  1397. job.set_is_suspended(false);
  1398. job.set_shell_did_continue(false);
  1399. found_child = true;
  1400. }
  1401. continue;
  1402. }
  1403. if (child_pid == job.pid()) {
  1404. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1405. job.set_signalled(WTERMSIG(wstatus));
  1406. } else if (WIFEXITED(wstatus)) {
  1407. job.set_has_exit(WEXITSTATUS(wstatus));
  1408. } else if (WIFSTOPPED(wstatus)) {
  1409. job.unblock();
  1410. job.set_is_suspended(true);
  1411. }
  1412. found_child = true;
  1413. }
  1414. if (job.should_be_disowned())
  1415. disowned_jobs.append(job_id);
  1416. }
  1417. for (auto job_id : disowned_jobs) {
  1418. jobs.remove(job_id);
  1419. }
  1420. } while (!found_child);
  1421. }
  1422. Shell::Shell()
  1423. : m_default_constructed(true)
  1424. {
  1425. push_frame("main").leak_frame();
  1426. int rc = gethostname(hostname, Shell::HostNameSize);
  1427. if (rc < 0)
  1428. perror("gethostname");
  1429. {
  1430. auto* pw = getpwuid(getuid());
  1431. if (pw) {
  1432. username = pw->pw_name;
  1433. home = pw->pw_dir;
  1434. setenv("HOME", pw->pw_dir, 1);
  1435. }
  1436. endpwent();
  1437. }
  1438. // For simplicity, start at the user's home directory.
  1439. this->cwd = home;
  1440. setenv("PWD", home.characters(), 1);
  1441. // Add the default PATH vars.
  1442. {
  1443. StringBuilder path;
  1444. path.append(getenv("PATH"));
  1445. if (path.length())
  1446. path.append(":");
  1447. path.append("/bin:/usr/bin:/usr/local/bin");
  1448. setenv("PATH", path.to_string().characters(), true);
  1449. }
  1450. cache_path();
  1451. }
  1452. Shell::Shell(Line::Editor& editor, bool attempt_interactive)
  1453. : m_editor(editor)
  1454. {
  1455. uid = getuid();
  1456. tcsetpgrp(0, getpgrp());
  1457. m_pid = getpid();
  1458. push_frame("main").leak_frame();
  1459. int rc = gethostname(hostname, Shell::HostNameSize);
  1460. if (rc < 0)
  1461. perror("gethostname");
  1462. auto istty = isatty(STDIN_FILENO);
  1463. m_is_interactive = attempt_interactive && istty;
  1464. if (istty) {
  1465. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1466. if (rc < 0)
  1467. perror("ttyname_r");
  1468. } else {
  1469. ttyname[0] = 0;
  1470. }
  1471. {
  1472. auto* cwd = getcwd(nullptr, 0);
  1473. this->cwd = cwd;
  1474. setenv("PWD", cwd, 1);
  1475. free(cwd);
  1476. }
  1477. {
  1478. auto* pw = getpwuid(getuid());
  1479. if (pw) {
  1480. username = pw->pw_name;
  1481. home = pw->pw_dir;
  1482. setenv("HOME", pw->pw_dir, 1);
  1483. }
  1484. endpwent();
  1485. }
  1486. directory_stack.append(cwd);
  1487. if (m_is_interactive) {
  1488. m_editor->load_history(get_history_path());
  1489. cache_path();
  1490. }
  1491. m_editor->register_key_input_callback('\n', [](Line::Editor& editor) {
  1492. auto ast = Parser(editor.line()).parse();
  1493. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1494. return true;
  1495. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1496. });
  1497. }
  1498. Shell::~Shell()
  1499. {
  1500. if (m_default_constructed)
  1501. return;
  1502. stop_all_jobs();
  1503. if (!m_is_interactive)
  1504. return;
  1505. m_editor->save_history(get_history_path());
  1506. }
  1507. void Shell::stop_all_jobs()
  1508. {
  1509. if (!jobs.is_empty()) {
  1510. if (m_is_interactive && !m_is_subshell)
  1511. printf("Killing active jobs\n");
  1512. for (auto& entry : jobs) {
  1513. if (entry.value->is_suspended()) {
  1514. dbgln_if(SH_DEBUG, "Job {} is suspended", entry.value->pid());
  1515. kill_job(entry.value, SIGCONT);
  1516. }
  1517. kill_job(entry.value, SIGHUP);
  1518. }
  1519. usleep(10000); // Wait for a bit before killing the job
  1520. for (auto& entry : jobs) {
  1521. dbgln_if(SH_DEBUG, "Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1522. kill_job(entry.value, SIGKILL);
  1523. }
  1524. jobs.clear();
  1525. }
  1526. }
  1527. u64 Shell::find_last_job_id() const
  1528. {
  1529. u64 job_id = 0;
  1530. for (auto& entry : jobs) {
  1531. if (entry.value->job_id() > job_id)
  1532. job_id = entry.value->job_id();
  1533. }
  1534. return job_id;
  1535. }
  1536. const Job* Shell::find_job(u64 id)
  1537. {
  1538. for (auto& entry : jobs) {
  1539. if (entry.value->job_id() == id)
  1540. return entry.value;
  1541. }
  1542. return nullptr;
  1543. }
  1544. void Shell::kill_job(const Job* job, int sig)
  1545. {
  1546. if (!job)
  1547. return;
  1548. if (killpg(job->pgid(), sig) < 0) {
  1549. if (kill(job->pid(), sig) < 0) {
  1550. if (errno != ESRCH)
  1551. perror("kill");
  1552. }
  1553. }
  1554. }
  1555. void Shell::save_to(JsonObject& object)
  1556. {
  1557. Core::Object::save_to(object);
  1558. object.set("working_directory", cwd);
  1559. object.set("username", username);
  1560. object.set("user_home_path", home);
  1561. object.set("user_id", uid);
  1562. object.set("directory_stack_size", directory_stack.size());
  1563. object.set("cd_history_size", cd_history.size());
  1564. // Jobs.
  1565. JsonArray job_objects;
  1566. for (auto& job_entry : jobs) {
  1567. JsonObject job_object;
  1568. job_object.set("pid", job_entry.value->pid());
  1569. job_object.set("pgid", job_entry.value->pgid());
  1570. job_object.set("running_time", job_entry.value->timer().elapsed());
  1571. job_object.set("command", job_entry.value->cmd());
  1572. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1573. job_objects.append(move(job_object));
  1574. }
  1575. object.set("jobs", move(job_objects));
  1576. }
  1577. void Shell::possibly_print_error() const
  1578. {
  1579. switch (m_error) {
  1580. case ShellError::EvaluatedSyntaxError:
  1581. warnln("Shell Syntax Error: {}", m_error_description);
  1582. break;
  1583. case ShellError::InvalidSliceContentsError:
  1584. case ShellError::InvalidGlobError:
  1585. case ShellError::NonExhaustiveMatchRules:
  1586. warnln("Shell: {}", m_error_description);
  1587. break;
  1588. case ShellError::OpenFailure:
  1589. warnln("Shell: Open failed for {}", m_error_description);
  1590. break;
  1591. case ShellError::InternalControlFlowBreak:
  1592. case ShellError::InternalControlFlowContinue:
  1593. return;
  1594. case ShellError::None:
  1595. return;
  1596. }
  1597. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  1598. auto& source_position = m_source_position.value();
  1599. auto do_line = [&](auto line, auto& current_line) {
  1600. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  1601. warnln("{:>3}| {}", line, current_line);
  1602. if (is_in_range) {
  1603. warn("\x1b[31m");
  1604. size_t length_written_so_far = 0;
  1605. if (line == (i64)source_position.position->start_line.line_number) {
  1606. warn(StringView { "{:~>{}}" }, "", 5 + source_position.position->start_line.line_column);
  1607. length_written_so_far += source_position.position->start_line.line_column;
  1608. } else {
  1609. warn(StringView { "{:~>{}}" }, "", 5);
  1610. }
  1611. if (line == (i64)source_position.position->end_line.line_number) {
  1612. warn(StringView { "{:^>{}}" }, "", source_position.position->end_line.line_column - length_written_so_far);
  1613. length_written_so_far += source_position.position->start_line.line_column;
  1614. } else {
  1615. warn(StringView { "{:^>{}}" }, "", current_line.length() - length_written_so_far);
  1616. }
  1617. warnln("\x1b[0m");
  1618. }
  1619. };
  1620. int line = -1;
  1621. String current_line;
  1622. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  1623. if (!source_position.source_file.is_null()) {
  1624. auto file = Core::File::open(source_position.source_file, Core::IODevice::OpenMode::ReadOnly);
  1625. if (file.is_error()) {
  1626. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file.error(), source_position.source_file);
  1627. return;
  1628. }
  1629. while (line < line_to_skip_to) {
  1630. if (file.value()->eof())
  1631. return;
  1632. current_line = file.value()->read_line();
  1633. ++line;
  1634. }
  1635. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1636. do_line(line, current_line);
  1637. if (file.value()->eof())
  1638. current_line = "";
  1639. else
  1640. current_line = file.value()->read_line();
  1641. }
  1642. } else if (!source_position.literal_source_text.is_empty()) {
  1643. GenericLexer lexer { source_position.literal_source_text };
  1644. while (line < line_to_skip_to) {
  1645. if (lexer.is_eof())
  1646. return;
  1647. current_line = lexer.consume_line();
  1648. ++line;
  1649. }
  1650. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1651. do_line(line, current_line);
  1652. if (lexer.is_eof())
  1653. current_line = "";
  1654. else
  1655. current_line = lexer.consume_line();
  1656. }
  1657. }
  1658. }
  1659. warnln();
  1660. }
  1661. void FileDescriptionCollector::collect()
  1662. {
  1663. for (auto fd : m_fds)
  1664. close(fd);
  1665. m_fds.clear();
  1666. }
  1667. FileDescriptionCollector::~FileDescriptionCollector()
  1668. {
  1669. collect();
  1670. }
  1671. void FileDescriptionCollector::add(int fd)
  1672. {
  1673. m_fds.append(fd);
  1674. }
  1675. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  1676. {
  1677. for (auto& rewiring : intended_rewirings) {
  1678. int new_fd = dup(rewiring.new_fd);
  1679. if (new_fd < 0) {
  1680. if (errno != EBADF)
  1681. perror("dup");
  1682. // The fd that will be overwritten isn't open right now,
  1683. // it will be cleaned up by the exec()-side collector
  1684. // and we have nothing to do here, so just ignore this error.
  1685. continue;
  1686. }
  1687. auto flags = fcntl(new_fd, F_GETFL);
  1688. auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC);
  1689. VERIFY(rc == 0);
  1690. m_saves.append({ rewiring.new_fd, new_fd });
  1691. m_collector.add(new_fd);
  1692. }
  1693. }
  1694. SavedFileDescriptors::~SavedFileDescriptors()
  1695. {
  1696. for (auto& save : m_saves) {
  1697. if (dup2(save.saved, save.original) < 0) {
  1698. perror("dup2(~SavedFileDescriptors)");
  1699. continue;
  1700. }
  1701. }
  1702. }
  1703. }