Shell.cpp 59 KB

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