Shell.cpp 61 KB

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