Shell.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  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).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 aliases to the cache.
  1042. for (const auto& alias : m_aliases) {
  1043. auto name = escape_token(alias.key);
  1044. if (cached_path.contains_slow(name))
  1045. continue;
  1046. cached_path.append(name);
  1047. }
  1048. String path = getenv("PATH");
  1049. if (!path.is_empty()) {
  1050. auto directories = path.split(':');
  1051. for (const auto& directory : directories) {
  1052. Core::DirIterator programs(directory.characters(), Core::DirIterator::SkipDots);
  1053. while (programs.has_next()) {
  1054. auto program = programs.next_path();
  1055. String program_path = String::format("%s/%s", directory.characters(), program.characters());
  1056. auto escaped_name = escape_token(program);
  1057. if (cached_path.contains_slow(escaped_name))
  1058. continue;
  1059. if (access(program_path.characters(), X_OK) == 0)
  1060. cached_path.append(escaped_name);
  1061. }
  1062. }
  1063. }
  1064. quick_sort(cached_path);
  1065. }
  1066. void Shell::add_entry_to_cache(const String& entry)
  1067. {
  1068. size_t index = 0;
  1069. auto match = binary_search(
  1070. cached_path.span(),
  1071. entry,
  1072. &index,
  1073. [](auto& name, auto& program) { return strcmp(name.characters(), program.characters()); });
  1074. if (match)
  1075. return;
  1076. while (index < cached_path.size() && strcmp(cached_path[index].characters(), entry.characters()) < 0) {
  1077. index++;
  1078. }
  1079. cached_path.insert(index, entry);
  1080. }
  1081. void Shell::highlight(Line::Editor& editor) const
  1082. {
  1083. auto line = editor.line();
  1084. Parser parser(line);
  1085. auto ast = parser.parse();
  1086. if (!ast)
  1087. return;
  1088. ast->highlight_in_editor(editor, const_cast<Shell&>(*this));
  1089. }
  1090. Vector<Line::CompletionSuggestion> Shell::complete()
  1091. {
  1092. auto line = m_editor->line(m_editor->cursor());
  1093. Parser parser(line);
  1094. auto ast = parser.parse();
  1095. if (!ast)
  1096. return {};
  1097. return ast->complete_for_editor(*this, line.length());
  1098. }
  1099. Vector<Line::CompletionSuggestion> Shell::complete_path(const String& base, const String& part, size_t offset)
  1100. {
  1101. auto token = offset ? part.substring_view(0, offset) : "";
  1102. String path;
  1103. ssize_t last_slash = token.length() - 1;
  1104. while (last_slash >= 0 && token[last_slash] != '/')
  1105. --last_slash;
  1106. StringBuilder path_builder;
  1107. auto init_slash_part = token.substring_view(0, last_slash + 1);
  1108. auto last_slash_part = token.substring_view(last_slash + 1, token.length() - last_slash - 1);
  1109. // Depending on the base, we will have to prepend cwd.
  1110. if (base.is_empty()) {
  1111. // '' /foo -> absolute
  1112. // '' foo -> relative
  1113. if (!token.starts_with('/'))
  1114. path_builder.append(cwd);
  1115. path_builder.append('/');
  1116. path_builder.append(init_slash_part);
  1117. } else {
  1118. // /foo * -> absolute
  1119. // foo * -> relative
  1120. if (!base.starts_with('/'))
  1121. path_builder.append(cwd);
  1122. path_builder.append('/');
  1123. path_builder.append(base);
  1124. path_builder.append('/');
  1125. path_builder.append(init_slash_part);
  1126. }
  1127. path = path_builder.build();
  1128. token = last_slash_part;
  1129. // the invariant part of the token is actually just the last segment
  1130. // e. in `cd /foo/bar', 'bar' is the invariant
  1131. // since we are not suggesting anything starting with
  1132. // `/foo/', but rather just `bar...'
  1133. auto token_length = escape_token(token).length();
  1134. if (m_editor)
  1135. m_editor->suggest(token_length, last_slash + 1);
  1136. // only suggest dot-files if path starts with a dot
  1137. Core::DirIterator files(path,
  1138. token.starts_with('.') ? Core::DirIterator::SkipParentAndBaseDir : Core::DirIterator::SkipDots);
  1139. Vector<Line::CompletionSuggestion> suggestions;
  1140. while (files.has_next()) {
  1141. auto file = files.next_path();
  1142. if (file.starts_with(token)) {
  1143. struct stat program_status;
  1144. String file_path = String::format("%s/%s", path.characters(), file.characters());
  1145. int stat_error = stat(file_path.characters(), &program_status);
  1146. if (!stat_error) {
  1147. if (S_ISDIR(program_status.st_mode)) {
  1148. suggestions.append({ escape_token(file), "/" });
  1149. } else {
  1150. suggestions.append({ escape_token(file), " " });
  1151. }
  1152. suggestions.last().input_offset = token_length;
  1153. }
  1154. }
  1155. }
  1156. return suggestions;
  1157. }
  1158. Vector<Line::CompletionSuggestion> Shell::complete_program_name(const String& name, size_t offset)
  1159. {
  1160. auto match = binary_search(
  1161. cached_path.span(),
  1162. name,
  1163. nullptr,
  1164. [](auto& name, auto& program) { return strncmp(name.characters(), program.characters(), name.length()); });
  1165. if (!match)
  1166. return complete_path("", name, offset);
  1167. String completion = *match;
  1168. auto token_length = escape_token(name).length();
  1169. if (m_editor)
  1170. m_editor->suggest(token_length, 0);
  1171. // Now that we have a program name starting with our token, we look at
  1172. // other program names starting with our token and cut off any mismatching
  1173. // characters.
  1174. Vector<Line::CompletionSuggestion> suggestions;
  1175. int index = match - cached_path.data();
  1176. for (int i = index - 1; i >= 0 && cached_path[i].starts_with(name); --i) {
  1177. suggestions.append({ cached_path[i], " " });
  1178. suggestions.last().input_offset = token_length;
  1179. }
  1180. for (size_t i = index + 1; i < cached_path.size() && cached_path[i].starts_with(name); ++i) {
  1181. suggestions.append({ cached_path[i], " " });
  1182. suggestions.last().input_offset = token_length;
  1183. }
  1184. suggestions.append({ cached_path[index], " " });
  1185. suggestions.last().input_offset = token_length;
  1186. return suggestions;
  1187. }
  1188. Vector<Line::CompletionSuggestion> Shell::complete_variable(const String& name, size_t offset)
  1189. {
  1190. Vector<Line::CompletionSuggestion> suggestions;
  1191. auto pattern = offset ? name.substring_view(0, offset) : "";
  1192. if (m_editor)
  1193. m_editor->suggest(offset);
  1194. // Look at local variables.
  1195. for (auto& frame : m_local_frames) {
  1196. for (auto& variable : frame.local_variables) {
  1197. if (variable.key.starts_with(pattern) && !suggestions.contains_slow(variable.key))
  1198. suggestions.append(variable.key);
  1199. }
  1200. }
  1201. // Look at the environment.
  1202. for (auto i = 0; environ[i]; ++i) {
  1203. auto entry = StringView { environ[i] };
  1204. if (entry.starts_with(pattern)) {
  1205. auto parts = entry.split_view('=');
  1206. if (parts.is_empty() || parts.first().is_empty())
  1207. continue;
  1208. String name = parts.first();
  1209. if (suggestions.contains_slow(name))
  1210. continue;
  1211. suggestions.append(move(name));
  1212. suggestions.last().input_offset = offset;
  1213. }
  1214. }
  1215. return suggestions;
  1216. }
  1217. Vector<Line::CompletionSuggestion> Shell::complete_user(const String& name, size_t offset)
  1218. {
  1219. Vector<Line::CompletionSuggestion> suggestions;
  1220. auto pattern = offset ? name.substring_view(0, offset) : "";
  1221. if (m_editor)
  1222. m_editor->suggest(offset);
  1223. Core::DirIterator di("/home", Core::DirIterator::SkipParentAndBaseDir);
  1224. if (di.has_error())
  1225. return suggestions;
  1226. while (di.has_next()) {
  1227. String name = di.next_path();
  1228. if (name.starts_with(pattern)) {
  1229. suggestions.append(name);
  1230. suggestions.last().input_offset = offset;
  1231. }
  1232. }
  1233. return suggestions;
  1234. }
  1235. Vector<Line::CompletionSuggestion> Shell::complete_option(const String& program_name, const String& option, size_t offset)
  1236. {
  1237. size_t start = 0;
  1238. while (start < option.length() && option[start] == '-' && start < 2)
  1239. ++start;
  1240. auto option_pattern = offset > start ? option.substring_view(start, offset - start) : "";
  1241. if (m_editor)
  1242. m_editor->suggest(offset);
  1243. Vector<Line::CompletionSuggestion> suggestions;
  1244. dbgln("Shell::complete_option({}, {})", program_name, option_pattern);
  1245. // FIXME: Figure out how to do this stuff.
  1246. if (has_builtin(program_name)) {
  1247. // Complete builtins.
  1248. if (program_name == "setopt") {
  1249. bool negate = false;
  1250. if (option_pattern.starts_with("no_")) {
  1251. negate = true;
  1252. option_pattern = option_pattern.substring_view(3, option_pattern.length() - 3);
  1253. }
  1254. auto maybe_negate = [&](const StringView& view) {
  1255. static StringBuilder builder;
  1256. builder.clear();
  1257. builder.append("--");
  1258. if (negate)
  1259. builder.append("no_");
  1260. builder.append(view);
  1261. return builder.to_string();
  1262. };
  1263. #define __ENUMERATE_SHELL_OPTION(name, d_, descr_) \
  1264. if (StringView { #name }.starts_with(option_pattern)) { \
  1265. suggestions.append(maybe_negate(#name)); \
  1266. suggestions.last().input_offset = offset; \
  1267. }
  1268. ENUMERATE_SHELL_OPTIONS();
  1269. #undef __ENUMERATE_SHELL_OPTION
  1270. return suggestions;
  1271. }
  1272. }
  1273. return suggestions;
  1274. }
  1275. void Shell::bring_cursor_to_beginning_of_a_line() const
  1276. {
  1277. struct winsize ws;
  1278. if (m_editor) {
  1279. ws = m_editor->terminal_size();
  1280. } else {
  1281. if (ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) < 0) {
  1282. // Very annoying assumptions.
  1283. ws.ws_col = 80;
  1284. ws.ws_row = 25;
  1285. }
  1286. }
  1287. // Black with Cyan background.
  1288. constexpr auto default_mark = "\e[30;46m%\e[0m";
  1289. String eol_mark = getenv("PROMPT_EOL_MARK");
  1290. if (eol_mark.is_null())
  1291. eol_mark = default_mark;
  1292. size_t eol_mark_length = Line::Editor::actual_rendered_string_metrics(eol_mark).line_metrics.last().total_length();
  1293. if (eol_mark_length >= ws.ws_col) {
  1294. eol_mark = default_mark;
  1295. eol_mark_length = 1;
  1296. }
  1297. fputs(eol_mark.characters(), stderr);
  1298. for (auto i = eol_mark_length; i < ws.ws_col; ++i)
  1299. putc(' ', stderr);
  1300. putc('\r', stderr);
  1301. }
  1302. bool Shell::has_history_event(StringView source)
  1303. {
  1304. struct : public AST::NodeVisitor {
  1305. virtual void visit(const AST::HistoryEvent* node)
  1306. {
  1307. has_history_event = true;
  1308. AST::NodeVisitor::visit(node);
  1309. }
  1310. bool has_history_event { false };
  1311. } visitor;
  1312. Parser { source }.parse()->visit(visitor);
  1313. return visitor.has_history_event;
  1314. }
  1315. bool Shell::read_single_line()
  1316. {
  1317. restore_ios();
  1318. bring_cursor_to_beginning_of_a_line();
  1319. auto line_result = m_editor->get_line(prompt());
  1320. if (line_result.is_error()) {
  1321. if (line_result.error() == Line::Editor::Error::Eof || line_result.error() == Line::Editor::Error::Empty) {
  1322. // Pretend the user tried to execute builtin_exit()
  1323. run_command("exit");
  1324. return read_single_line();
  1325. } else {
  1326. Core::EventLoop::current().quit(1);
  1327. return false;
  1328. }
  1329. }
  1330. auto& line = line_result.value();
  1331. if (line.is_empty())
  1332. return true;
  1333. run_command(line);
  1334. if (!has_history_event(line))
  1335. m_editor->add_to_history(line);
  1336. return true;
  1337. }
  1338. void Shell::custom_event(Core::CustomEvent& event)
  1339. {
  1340. if (event.custom_type() == ReadLine) {
  1341. if (read_single_line())
  1342. Core::EventLoop::current().post_event(*this, make<Core::CustomEvent>(ShellEventType::ReadLine));
  1343. return;
  1344. }
  1345. }
  1346. void Shell::notify_child_event()
  1347. {
  1348. Vector<u64> disowned_jobs;
  1349. // Workaround the fact that we can't receive *who* exactly changed state.
  1350. // The child might still be alive (and even running) when this signal is dispatched to us
  1351. // so just...repeat until we find a suitable child.
  1352. // This, of course, will mean that someone can send us a SIGCHILD and we'd be spinning here
  1353. // until the next child event we can actually handle.
  1354. bool found_child = false;
  1355. do {
  1356. // Ignore stray SIGCHLD when there are no jobs.
  1357. if (jobs.is_empty())
  1358. return;
  1359. for (auto& it : jobs) {
  1360. auto job_id = it.key;
  1361. auto& job = *it.value;
  1362. int wstatus = 0;
  1363. #if SH_DEBUG
  1364. dbgln("waitpid({}) = ...", job.pid());
  1365. #endif
  1366. auto child_pid = waitpid(job.pid(), &wstatus, WNOHANG | WUNTRACED);
  1367. #if SH_DEBUG
  1368. dbgln("... = {} - {}", child_pid, wstatus);
  1369. #endif
  1370. if (child_pid < 0) {
  1371. if (errno == ECHILD) {
  1372. // The child process went away before we could process its death, just assume it exited all ok.
  1373. // FIXME: This should never happen, the child should stay around until we do the waitpid above.
  1374. child_pid = job.pid();
  1375. } else {
  1376. VERIFY_NOT_REACHED();
  1377. }
  1378. }
  1379. if (child_pid == 0) {
  1380. // If the child existed, but wasn't dead.
  1381. continue;
  1382. }
  1383. if (child_pid == job.pid()) {
  1384. if (WIFSIGNALED(wstatus) && !WIFSTOPPED(wstatus)) {
  1385. job.set_signalled(WTERMSIG(wstatus));
  1386. } else if (WIFEXITED(wstatus)) {
  1387. job.set_has_exit(WEXITSTATUS(wstatus));
  1388. } else if (WIFSTOPPED(wstatus)) {
  1389. job.unblock();
  1390. job.set_is_suspended(true);
  1391. }
  1392. found_child = true;
  1393. }
  1394. if (job.should_be_disowned())
  1395. disowned_jobs.append(job_id);
  1396. }
  1397. for (auto job_id : disowned_jobs) {
  1398. jobs.remove(job_id);
  1399. }
  1400. } while (!found_child);
  1401. }
  1402. Shell::Shell()
  1403. : m_default_constructed(true)
  1404. {
  1405. push_frame("main").leak_frame();
  1406. int rc = gethostname(hostname, Shell::HostNameSize);
  1407. if (rc < 0)
  1408. perror("gethostname");
  1409. {
  1410. auto* pw = getpwuid(getuid());
  1411. if (pw) {
  1412. username = pw->pw_name;
  1413. home = pw->pw_dir;
  1414. setenv("HOME", pw->pw_dir, 1);
  1415. }
  1416. endpwent();
  1417. }
  1418. // For simplicity, start at the user's home directory.
  1419. this->cwd = home;
  1420. setenv("PWD", home.characters(), 1);
  1421. // Add the default PATH vars.
  1422. {
  1423. StringBuilder path;
  1424. path.append(getenv("PATH"));
  1425. if (path.length())
  1426. path.append(":");
  1427. path.append("/bin:/usr/bin:/usr/local/bin");
  1428. setenv("PATH", path.to_string().characters(), true);
  1429. }
  1430. cache_path();
  1431. }
  1432. Shell::Shell(Line::Editor& editor, bool attempt_interactive)
  1433. : m_editor(editor)
  1434. {
  1435. uid = getuid();
  1436. tcsetpgrp(0, getpgrp());
  1437. m_pid = getpid();
  1438. push_frame("main").leak_frame();
  1439. int rc = gethostname(hostname, Shell::HostNameSize);
  1440. if (rc < 0)
  1441. perror("gethostname");
  1442. auto istty = isatty(STDIN_FILENO);
  1443. m_is_interactive = attempt_interactive && istty;
  1444. if (istty) {
  1445. rc = ttyname_r(0, ttyname, Shell::TTYNameSize);
  1446. if (rc < 0)
  1447. perror("ttyname_r");
  1448. } else {
  1449. ttyname[0] = 0;
  1450. }
  1451. {
  1452. auto* cwd = getcwd(nullptr, 0);
  1453. this->cwd = cwd;
  1454. setenv("PWD", cwd, 1);
  1455. free(cwd);
  1456. }
  1457. {
  1458. auto* pw = getpwuid(getuid());
  1459. if (pw) {
  1460. username = pw->pw_name;
  1461. home = pw->pw_dir;
  1462. setenv("HOME", pw->pw_dir, 1);
  1463. }
  1464. endpwent();
  1465. }
  1466. directory_stack.append(cwd);
  1467. if (m_is_interactive) {
  1468. m_editor->load_history(get_history_path());
  1469. cache_path();
  1470. }
  1471. m_editor->register_key_input_callback('\n', [](Line::Editor& editor) {
  1472. auto ast = Parser(editor.line()).parse();
  1473. if (ast && ast->is_syntax_error() && ast->syntax_error_node().is_continuable())
  1474. return true;
  1475. return EDITOR_INTERNAL_FUNCTION(finish)(editor);
  1476. });
  1477. }
  1478. Shell::~Shell()
  1479. {
  1480. if (m_default_constructed)
  1481. return;
  1482. stop_all_jobs();
  1483. if (!m_is_interactive)
  1484. return;
  1485. m_editor->save_history(get_history_path());
  1486. }
  1487. void Shell::stop_all_jobs()
  1488. {
  1489. if (!jobs.is_empty()) {
  1490. if (m_is_interactive && !m_is_subshell)
  1491. printf("Killing active jobs\n");
  1492. for (auto& entry : jobs) {
  1493. if (entry.value->is_suspended()) {
  1494. #if SH_DEBUG
  1495. dbgln("Job {} is suspended", entry.value->pid());
  1496. #endif
  1497. kill_job(entry.value, SIGCONT);
  1498. }
  1499. kill_job(entry.value, SIGHUP);
  1500. }
  1501. usleep(10000); // Wait for a bit before killing the job
  1502. for (auto& entry : jobs) {
  1503. #if SH_DEBUG
  1504. dbgln("Actively killing {} ({})", entry.value->pid(), entry.value->cmd());
  1505. #endif
  1506. kill_job(entry.value, SIGKILL);
  1507. }
  1508. jobs.clear();
  1509. }
  1510. }
  1511. u64 Shell::find_last_job_id() const
  1512. {
  1513. u64 job_id = 0;
  1514. for (auto& entry : jobs) {
  1515. if (entry.value->job_id() > job_id)
  1516. job_id = entry.value->job_id();
  1517. }
  1518. return job_id;
  1519. }
  1520. const Job* Shell::find_job(u64 id)
  1521. {
  1522. for (auto& entry : jobs) {
  1523. if (entry.value->job_id() == id)
  1524. return entry.value;
  1525. }
  1526. return nullptr;
  1527. }
  1528. void Shell::kill_job(const Job* job, int sig)
  1529. {
  1530. if (!job)
  1531. return;
  1532. if (killpg(job->pgid(), sig) < 0) {
  1533. if (kill(job->pid(), sig) < 0) {
  1534. if (errno != ESRCH)
  1535. perror("kill");
  1536. }
  1537. }
  1538. }
  1539. void Shell::save_to(JsonObject& object)
  1540. {
  1541. Core::Object::save_to(object);
  1542. object.set("working_directory", cwd);
  1543. object.set("username", username);
  1544. object.set("user_home_path", home);
  1545. object.set("user_id", uid);
  1546. object.set("directory_stack_size", directory_stack.size());
  1547. object.set("cd_history_size", cd_history.size());
  1548. // Jobs.
  1549. JsonArray job_objects;
  1550. for (auto& job_entry : jobs) {
  1551. JsonObject job_object;
  1552. job_object.set("pid", job_entry.value->pid());
  1553. job_object.set("pgid", job_entry.value->pgid());
  1554. job_object.set("running_time", job_entry.value->timer().elapsed());
  1555. job_object.set("command", job_entry.value->cmd());
  1556. job_object.set("is_running_in_background", job_entry.value->is_running_in_background());
  1557. job_objects.append(move(job_object));
  1558. }
  1559. object.set("jobs", move(job_objects));
  1560. }
  1561. void Shell::possibly_print_error() const
  1562. {
  1563. switch (m_error) {
  1564. case ShellError::EvaluatedSyntaxError:
  1565. warnln("Shell Syntax Error: {}", m_error_description);
  1566. break;
  1567. case ShellError::InvalidGlobError:
  1568. case ShellError::NonExhaustiveMatchRules:
  1569. warnln("Shell: {}", m_error_description);
  1570. break;
  1571. case ShellError::OpenFailure:
  1572. warnln("Shell: Open failed for {}", m_error_description);
  1573. break;
  1574. case ShellError::InternalControlFlowBreak:
  1575. case ShellError::InternalControlFlowContinue:
  1576. return;
  1577. case ShellError::None:
  1578. return;
  1579. }
  1580. if (m_source_position.has_value() && m_source_position->position.has_value()) {
  1581. auto& source_position = m_source_position.value();
  1582. auto do_line = [&](auto line, auto& current_line) {
  1583. auto is_in_range = line >= (i64)source_position.position->start_line.line_number && line <= (i64)source_position.position->end_line.line_number;
  1584. warnln("{:>3}| {}", line, current_line);
  1585. if (is_in_range) {
  1586. warn("\x1b[31m");
  1587. size_t length_written_so_far = 0;
  1588. if (line == (i64)source_position.position->start_line.line_number) {
  1589. warn(StringView { "{:~>{}}" }, "", 5 + source_position.position->start_line.line_column);
  1590. length_written_so_far += source_position.position->start_line.line_column;
  1591. } else {
  1592. warn(StringView { "{:~>{}}" }, "", 5);
  1593. }
  1594. if (line == (i64)source_position.position->end_line.line_number) {
  1595. warn(StringView { "{:^>{}}" }, "", source_position.position->end_line.line_column - length_written_so_far);
  1596. length_written_so_far += source_position.position->start_line.line_column;
  1597. } else {
  1598. warn(StringView { "{:^>{}}" }, "", current_line.length() - length_written_so_far);
  1599. }
  1600. warnln("\x1b[0m");
  1601. }
  1602. };
  1603. int line = -1;
  1604. String current_line;
  1605. i64 line_to_skip_to = max(source_position.position->start_line.line_number, 2ul) - 2;
  1606. if (!source_position.source_file.is_null()) {
  1607. auto file = Core::File::open(source_position.source_file, Core::IODevice::OpenMode::ReadOnly);
  1608. if (file.is_error()) {
  1609. warnln("Shell: Internal error while trying to display source information: {} (while reading '{}')", file.error(), source_position.source_file);
  1610. return;
  1611. }
  1612. while (line < line_to_skip_to) {
  1613. if (file.value()->eof())
  1614. return;
  1615. current_line = file.value()->read_line();
  1616. ++line;
  1617. }
  1618. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1619. do_line(line, current_line);
  1620. if (file.value()->eof())
  1621. current_line = "";
  1622. else
  1623. current_line = file.value()->read_line();
  1624. }
  1625. } else if (!source_position.literal_source_text.is_empty()) {
  1626. GenericLexer lexer { source_position.literal_source_text };
  1627. while (line < line_to_skip_to) {
  1628. if (lexer.is_eof())
  1629. return;
  1630. current_line = lexer.consume_line();
  1631. ++line;
  1632. }
  1633. for (; line < (i64)source_position.position->end_line.line_number + 2; ++line) {
  1634. do_line(line, current_line);
  1635. if (lexer.is_eof())
  1636. current_line = "";
  1637. else
  1638. current_line = lexer.consume_line();
  1639. }
  1640. }
  1641. }
  1642. warnln();
  1643. }
  1644. void FileDescriptionCollector::collect()
  1645. {
  1646. for (auto fd : m_fds)
  1647. close(fd);
  1648. m_fds.clear();
  1649. }
  1650. FileDescriptionCollector::~FileDescriptionCollector()
  1651. {
  1652. collect();
  1653. }
  1654. void FileDescriptionCollector::add(int fd)
  1655. {
  1656. m_fds.append(fd);
  1657. }
  1658. SavedFileDescriptors::SavedFileDescriptors(const NonnullRefPtrVector<AST::Rewiring>& intended_rewirings)
  1659. {
  1660. for (auto& rewiring : intended_rewirings) {
  1661. int new_fd = dup(rewiring.new_fd);
  1662. if (new_fd < 0) {
  1663. if (errno != EBADF)
  1664. perror("dup");
  1665. // The fd that will be overwritten isn't open right now,
  1666. // it will be cleaned up by the exec()-side collector
  1667. // and we have nothing to do here, so just ignore this error.
  1668. continue;
  1669. }
  1670. auto flags = fcntl(new_fd, F_GETFL);
  1671. auto rc = fcntl(new_fd, F_SETFL, flags | FD_CLOEXEC);
  1672. VERIFY(rc == 0);
  1673. m_saves.append({ rewiring.new_fd, new_fd });
  1674. m_collector.add(new_fd);
  1675. }
  1676. }
  1677. SavedFileDescriptors::~SavedFileDescriptors()
  1678. {
  1679. for (auto& save : m_saves) {
  1680. if (dup2(save.saved, save.original) < 0) {
  1681. perror("dup2(~SavedFileDescriptors)");
  1682. continue;
  1683. }
  1684. }
  1685. }
  1686. }