Shell.cpp 61 KB

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