Shell.cpp 59 KB

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