Builtin.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "AST.h"
  7. #include "Formatter.h"
  8. #include "PosixParser.h"
  9. #include "Shell.h"
  10. #include <AK/DeprecatedString.h>
  11. #include <AK/LexicalPath.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <AK/Statistics.h>
  14. #include <LibCore/ArgsParser.h>
  15. #include <LibCore/DeprecatedFile.h>
  16. #include <LibCore/EventLoop.h>
  17. #include <LibCore/File.h>
  18. #include <errno.h>
  19. #include <inttypes.h>
  20. #include <limits.h>
  21. #include <signal.h>
  22. #include <sys/wait.h>
  23. #include <unistd.h>
  24. extern char** environ;
  25. namespace Shell {
  26. ErrorOr<int> Shell::builtin_noop(Main::Arguments)
  27. {
  28. return 0;
  29. }
  30. ErrorOr<int> Shell::builtin_dump(Main::Arguments arguments)
  31. {
  32. bool posix = false;
  33. StringView source;
  34. Core::ArgsParser parser;
  35. parser.add_positional_argument(source, "Shell code to parse and dump", "source");
  36. parser.add_option(posix, "Use the POSIX parser", "posix", 'p');
  37. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  38. return 1;
  39. TRY((posix ? Posix::Parser { source }.parse() : Parser { source }.parse())->dump(0));
  40. return 0;
  41. }
  42. enum FollowSymlinks {
  43. Yes,
  44. No
  45. };
  46. static Vector<DeprecatedString> find_matching_executables_in_path(StringView filename, FollowSymlinks follow_symlinks = FollowSymlinks::No)
  47. {
  48. // Edge cases in which there are guaranteed no solutions
  49. if (filename.is_empty() || filename.contains('/'))
  50. return {};
  51. char const* path_str = getenv("PATH");
  52. auto path = DEFAULT_PATH_SV;
  53. if (path_str != nullptr) // maybe && *path_str
  54. path = { path_str, strlen(path_str) };
  55. Vector<DeprecatedString> executables;
  56. auto directories = path.split_view(':');
  57. for (auto directory : directories) {
  58. auto file = DeprecatedString::formatted("{}/{}", directory, filename);
  59. if (follow_symlinks == FollowSymlinks::Yes) {
  60. auto path_or_error = Core::DeprecatedFile::read_link(file);
  61. if (!path_or_error.is_error())
  62. file = path_or_error.release_value();
  63. }
  64. if (access(file.characters(), X_OK) == 0)
  65. executables.append(move(file));
  66. }
  67. return executables;
  68. }
  69. ErrorOr<int> Shell::builtin_where(Main::Arguments arguments)
  70. {
  71. Vector<StringView> values_to_lookup;
  72. bool do_only_path_search { false };
  73. bool do_follow_symlinks { false };
  74. bool do_print_only_type { false };
  75. Core::ArgsParser parser;
  76. parser.add_positional_argument(values_to_lookup, "List of shell builtins, aliases or executables", "arguments");
  77. parser.add_option(do_only_path_search, "Search only for executables in the PATH environment variable", "path-only", 'p');
  78. parser.add_option(do_follow_symlinks, "Follow symlinks and print the symlink free path", "follow-symlink", 's');
  79. parser.add_option(do_print_only_type, "Print the argument type instead of a human readable description", "type", 'w');
  80. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  81. return 1;
  82. auto const lookup_alias = [do_only_path_search, &m_aliases = this->m_aliases](StringView alias) -> Optional<DeprecatedString> {
  83. if (do_only_path_search)
  84. return {};
  85. return m_aliases.get(alias);
  86. };
  87. auto const lookup_builtin = [do_only_path_search](StringView builtin) -> Optional<DeprecatedString> {
  88. if (do_only_path_search)
  89. return {};
  90. for (auto const& _builtin : builtin_names) {
  91. if (_builtin == builtin) {
  92. return builtin;
  93. }
  94. }
  95. return {};
  96. };
  97. bool at_least_one_succeded { false };
  98. for (auto const& argument : values_to_lookup) {
  99. auto const alias = lookup_alias(argument);
  100. if (alias.has_value()) {
  101. if (do_print_only_type)
  102. outln("{}: alias", argument);
  103. else
  104. outln("{}: aliased to {}", argument, alias.value());
  105. at_least_one_succeded = true;
  106. }
  107. auto const builtin = lookup_builtin(argument);
  108. if (builtin.has_value()) {
  109. if (do_print_only_type)
  110. outln("{}: builtin", builtin.value());
  111. else
  112. outln("{}: shell built-in command", builtin.value());
  113. at_least_one_succeded = true;
  114. }
  115. auto const executables = find_matching_executables_in_path(argument, do_follow_symlinks ? FollowSymlinks::Yes : FollowSymlinks::No);
  116. for (auto const& path : executables) {
  117. if (do_print_only_type)
  118. outln("{}: command", argument);
  119. else
  120. outln(path);
  121. at_least_one_succeded = true;
  122. }
  123. if (!at_least_one_succeded)
  124. warnln("{} not found", argument);
  125. }
  126. return at_least_one_succeded ? 0 : 1;
  127. }
  128. ErrorOr<int> Shell::builtin_alias(Main::Arguments arguments)
  129. {
  130. Vector<DeprecatedString> aliases;
  131. Core::ArgsParser parser;
  132. parser.add_positional_argument(aliases, "List of name[=values]'s", "name[=value]", Core::ArgsParser::Required::No);
  133. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  134. return 1;
  135. if (aliases.is_empty()) {
  136. for (auto& alias : m_aliases)
  137. printf("%s=%s\n", escape_token(alias.key).characters(), escape_token(alias.value).characters());
  138. return 0;
  139. }
  140. bool fail = false;
  141. for (auto& argument : aliases) {
  142. auto parts = argument.split_limit('=', 2, SplitBehavior::KeepEmpty);
  143. if (parts.size() == 1) {
  144. auto alias = m_aliases.get(parts[0]);
  145. if (alias.has_value()) {
  146. printf("%s=%s\n", escape_token(parts[0]).characters(), escape_token(alias.value()).characters());
  147. } else {
  148. fail = true;
  149. }
  150. } else {
  151. m_aliases.set(parts[0], parts[1]);
  152. add_entry_to_cache({ RunnablePath::Kind::Alias, parts[0] });
  153. }
  154. }
  155. return fail ? 1 : 0;
  156. }
  157. ErrorOr<int> Shell::builtin_unalias(Main::Arguments arguments)
  158. {
  159. bool remove_all { false };
  160. Vector<DeprecatedString> aliases;
  161. Core::ArgsParser parser;
  162. parser.set_general_help("Remove alias from the list of aliases");
  163. parser.add_option(remove_all, "Remove all aliases", nullptr, 'a');
  164. parser.add_positional_argument(aliases, "List of aliases to remove", "alias", Core::ArgsParser::Required::Yes);
  165. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  166. return 1;
  167. if (remove_all) {
  168. m_aliases.clear();
  169. cache_path();
  170. return 0;
  171. }
  172. bool failed { false };
  173. for (auto& argument : aliases) {
  174. if (!m_aliases.contains(argument)) {
  175. warnln("unalias: {}: alias not found", argument);
  176. failed = true;
  177. continue;
  178. }
  179. m_aliases.remove(argument);
  180. remove_entry_from_cache(argument);
  181. }
  182. return failed ? 1 : 0;
  183. }
  184. ErrorOr<int> Shell::builtin_break(Main::Arguments arguments)
  185. {
  186. if (!m_in_posix_mode) {
  187. raise_error(ShellError::EvaluatedSyntaxError, "break: Invalid use of builtin break in non-POSIX mode");
  188. return 1;
  189. }
  190. unsigned count = 1;
  191. Core::ArgsParser parser;
  192. parser.add_positional_argument(count, "Number of loops to 'break' out of", "count", Core::ArgsParser::Required::No);
  193. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  194. return 1;
  195. if (count != 1) {
  196. raise_error(ShellError::EvaluatedSyntaxError, "break: count must be equal to 1 (NYI)");
  197. return 1;
  198. }
  199. raise_error(ShellError::InternalControlFlowBreak, "POSIX break");
  200. return 0;
  201. }
  202. ErrorOr<int> Shell::builtin_continue(Main::Arguments arguments)
  203. {
  204. if (!m_in_posix_mode) {
  205. raise_error(ShellError::EvaluatedSyntaxError, "break: Invalid use of builtin continue in non-POSIX mode");
  206. return 1;
  207. }
  208. unsigned count = 1;
  209. Core::ArgsParser parser;
  210. parser.add_positional_argument(count, "Number of loops to 'continue' out of", "count", Core::ArgsParser::Required::No);
  211. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  212. return 1;
  213. if (count != 0) {
  214. raise_error(ShellError::EvaluatedSyntaxError, "continue: count must be equal to 1 (NYI)");
  215. return 1;
  216. }
  217. raise_error(ShellError::InternalControlFlowContinue, "POSIX continue");
  218. return 0;
  219. }
  220. ErrorOr<int> Shell::builtin_bg(Main::Arguments arguments)
  221. {
  222. int job_id = -1;
  223. bool is_pid = false;
  224. Core::ArgsParser parser;
  225. parser.add_positional_argument(Core::ArgsParser::Arg {
  226. .help_string = "Job ID or Jobspec to run in background",
  227. .name = "job-id",
  228. .min_values = 0,
  229. .max_values = 1,
  230. .accept_value = [&](StringView value) -> bool {
  231. // Check if it's a pid (i.e. literal integer)
  232. if (auto number = value.to_uint(); number.has_value()) {
  233. job_id = number.value();
  234. is_pid = true;
  235. return true;
  236. }
  237. // Check if it's a jobspec
  238. if (auto id = resolve_job_spec(value); id.has_value()) {
  239. job_id = id.value();
  240. is_pid = false;
  241. return true;
  242. }
  243. return false;
  244. } });
  245. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  246. return 1;
  247. if (job_id == -1 && !jobs.is_empty())
  248. job_id = find_last_job_id();
  249. auto* job = const_cast<Job*>(find_job(job_id, is_pid));
  250. if (!job) {
  251. if (job_id == -1) {
  252. warnln("bg: No current job");
  253. } else {
  254. warnln("bg: Job with id/pid {} not found", job_id);
  255. }
  256. return 1;
  257. }
  258. job->set_running_in_background(true);
  259. job->set_should_announce_exit(true);
  260. job->set_shell_did_continue(true);
  261. dbgln("Resuming {} ({})", job->pid(), job->cmd());
  262. warnln("Resuming job {} - {}", job->job_id(), job->cmd());
  263. // Try using the PGID, but if that fails, just use the PID.
  264. if (killpg(job->pgid(), SIGCONT) < 0) {
  265. if (kill(job->pid(), SIGCONT) < 0) {
  266. perror("kill");
  267. return 1;
  268. }
  269. }
  270. return 0;
  271. }
  272. ErrorOr<int> Shell::builtin_type(Main::Arguments arguments)
  273. {
  274. Vector<DeprecatedString> commands;
  275. bool dont_show_function_source = false;
  276. Core::ArgsParser parser;
  277. parser.set_general_help("Display information about commands.");
  278. parser.add_positional_argument(commands, "Command(s) to list info about", "command");
  279. parser.add_option(dont_show_function_source, "Do not show functions source.", "no-fn-source", 'f');
  280. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  281. return 1;
  282. bool something_not_found = false;
  283. for (auto& command : commands) {
  284. // check if it is an alias
  285. if (auto alias = m_aliases.get(command); alias.has_value()) {
  286. printf("%s is aliased to `%s`\n", escape_token(command).characters(), escape_token(alias.value()).characters());
  287. continue;
  288. }
  289. // check if it is a function
  290. if (auto function = m_functions.get(command); function.has_value()) {
  291. auto fn = function.value();
  292. printf("%s is a function\n", command.characters());
  293. if (!dont_show_function_source) {
  294. StringBuilder builder;
  295. builder.append(fn.name);
  296. builder.append('(');
  297. for (size_t i = 0; i < fn.arguments.size(); i++) {
  298. builder.append(fn.arguments[i]);
  299. if (!(i == fn.arguments.size() - 1))
  300. builder.append(' ');
  301. }
  302. builder.append(") {\n"sv);
  303. if (fn.body) {
  304. auto formatter = Formatter(*fn.body);
  305. builder.append(formatter.format());
  306. printf("%s\n}\n", builder.to_deprecated_string().characters());
  307. } else {
  308. printf("%s\n}\n", builder.to_deprecated_string().characters());
  309. }
  310. }
  311. continue;
  312. }
  313. // check if its a builtin
  314. if (has_builtin(command)) {
  315. printf("%s is a shell builtin\n", command.characters());
  316. continue;
  317. }
  318. // check if its an executable in PATH
  319. auto fullpath = Core::DeprecatedFile::resolve_executable_from_environment(command);
  320. if (fullpath.has_value()) {
  321. printf("%s is %s\n", command.characters(), escape_token(fullpath.release_value()).characters());
  322. continue;
  323. }
  324. something_not_found = true;
  325. printf("type: %s not found\n", command.characters());
  326. }
  327. if (something_not_found)
  328. return 1;
  329. else
  330. return 0;
  331. }
  332. ErrorOr<int> Shell::builtin_cd(Main::Arguments arguments)
  333. {
  334. StringView arg_path;
  335. Core::ArgsParser parser;
  336. parser.add_positional_argument(arg_path, "Path to change to", "path", Core::ArgsParser::Required::No);
  337. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  338. return 1;
  339. DeprecatedString new_path;
  340. if (arg_path.is_empty()) {
  341. new_path = home;
  342. } else {
  343. if (arg_path == "-"sv) {
  344. char* oldpwd = getenv("OLDPWD");
  345. if (oldpwd == nullptr)
  346. return 1;
  347. new_path = oldpwd;
  348. } else {
  349. new_path = arg_path;
  350. }
  351. }
  352. auto real_path = Core::DeprecatedFile::real_path_for(new_path);
  353. if (real_path.is_empty()) {
  354. warnln("Invalid path '{}'", new_path);
  355. return 1;
  356. }
  357. if (cd_history.is_empty() || cd_history.last() != real_path)
  358. cd_history.enqueue(real_path);
  359. auto path_relative_to_current_directory = LexicalPath::relative_path(real_path, cwd);
  360. if (path_relative_to_current_directory.is_empty())
  361. path_relative_to_current_directory = real_path;
  362. char const* path = path_relative_to_current_directory.characters();
  363. int rc = chdir(path);
  364. if (rc < 0) {
  365. if (errno == ENOTDIR) {
  366. warnln("Not a directory: {}", path);
  367. } else {
  368. warnln("chdir({}) failed: {}", path, strerror(errno));
  369. }
  370. return 1;
  371. }
  372. setenv("OLDPWD", cwd.characters(), 1);
  373. cwd = move(real_path);
  374. setenv("PWD", cwd.characters(), 1);
  375. return 0;
  376. }
  377. ErrorOr<int> Shell::builtin_cdh(Main::Arguments arguments)
  378. {
  379. int index = -1;
  380. Core::ArgsParser parser;
  381. parser.add_positional_argument(index, "Index of the cd history entry (leave out for a list)", "index", Core::ArgsParser::Required::No);
  382. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  383. return 1;
  384. if (index == -1) {
  385. if (cd_history.is_empty()) {
  386. warnln("cdh: no history available");
  387. return 0;
  388. }
  389. for (ssize_t i = cd_history.size() - 1; i >= 0; --i)
  390. printf("%zu: %s\n", cd_history.size() - i, cd_history.at(i).characters());
  391. return 0;
  392. }
  393. if (index < 1 || (size_t)index > cd_history.size()) {
  394. warnln("cdh: history index out of bounds: {} not in (0, {})", index, cd_history.size());
  395. return 1;
  396. }
  397. StringView path = cd_history.at(cd_history.size() - index);
  398. StringView cd_args[] = { "cd"sv, path };
  399. return Shell::builtin_cd({ .argc = 0, .argv = 0, .strings = cd_args });
  400. }
  401. ErrorOr<int> Shell::builtin_dirs(Main::Arguments arguments)
  402. {
  403. // The first directory in the stack is ALWAYS the current directory
  404. directory_stack.at(0) = cwd.characters();
  405. bool clear = false;
  406. bool print = false;
  407. bool number_when_printing = false;
  408. char separator = ' ';
  409. Vector<DeprecatedString> paths;
  410. Core::ArgsParser parser;
  411. parser.add_option(clear, "Clear the directory stack", "clear", 'c');
  412. parser.add_option(print, "Print directory entries one per line", "print", 'p');
  413. parser.add_option(number_when_printing, "Number the directories in the stack when printing", "number", 'v');
  414. parser.add_positional_argument(paths, "Extra paths to put on the stack", "path", Core::ArgsParser::Required::No);
  415. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  416. return 1;
  417. // -v implies -p
  418. print = print || number_when_printing;
  419. if (print) {
  420. if (!paths.is_empty()) {
  421. warnln("dirs: 'print' and 'number' are not allowed when any path is specified");
  422. return 1;
  423. }
  424. separator = '\n';
  425. }
  426. if (clear) {
  427. for (size_t i = 1; i < directory_stack.size(); i++)
  428. directory_stack.remove(i);
  429. }
  430. for (auto& path : paths)
  431. directory_stack.append(path);
  432. if (print || (!clear && paths.is_empty())) {
  433. int index = 0;
  434. for (auto& directory : directory_stack) {
  435. if (number_when_printing)
  436. printf("%d ", index++);
  437. print_path(directory);
  438. fputc(separator, stdout);
  439. }
  440. }
  441. return 0;
  442. }
  443. ErrorOr<int> Shell::builtin_exec(Main::Arguments arguments)
  444. {
  445. if (arguments.strings.size() < 2) {
  446. warnln("Shell: No command given to exec");
  447. return 1;
  448. }
  449. TRY(execute_process(arguments.strings.slice(1)));
  450. // NOTE: Won't get here.
  451. return 0;
  452. }
  453. ErrorOr<int> Shell::builtin_exit(Main::Arguments arguments)
  454. {
  455. int exit_code = 0;
  456. Core::ArgsParser parser;
  457. parser.add_positional_argument(exit_code, "Exit code", "code", Core::ArgsParser::Required::No);
  458. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  459. return 1;
  460. if (m_is_interactive) {
  461. if (!jobs.is_empty()) {
  462. if (!m_should_ignore_jobs_on_next_exit) {
  463. warnln("Shell: You have {} active job{}, run 'exit' again to really exit.", jobs.size(), jobs.size() > 1 ? "s" : "");
  464. m_should_ignore_jobs_on_next_exit = true;
  465. return 1;
  466. }
  467. }
  468. }
  469. stop_all_jobs();
  470. if (m_is_interactive) {
  471. m_editor->save_history(get_history_path());
  472. printf("Good-bye!\n");
  473. }
  474. exit(exit_code);
  475. }
  476. ErrorOr<int> Shell::builtin_export(Main::Arguments arguments)
  477. {
  478. Vector<DeprecatedString> vars;
  479. Core::ArgsParser parser;
  480. parser.add_positional_argument(vars, "List of variable[=value]'s", "values", Core::ArgsParser::Required::No);
  481. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  482. return 1;
  483. if (vars.is_empty()) {
  484. for (size_t i = 0; environ[i]; ++i)
  485. puts(environ[i]);
  486. return 0;
  487. }
  488. for (auto& value : vars) {
  489. auto parts = value.split_limit('=', 2);
  490. if (parts.is_empty()) {
  491. warnln("Shell: Invalid export spec '{}', expected `variable=value' or `variable'", value);
  492. return 1;
  493. }
  494. if (parts.size() == 1) {
  495. auto value = TRY(lookup_local_variable(parts[0]));
  496. if (value) {
  497. auto values = TRY(const_cast<AST::Value&>(*value).resolve_as_list(*this));
  498. StringBuilder builder;
  499. builder.join(' ', values);
  500. parts.append(builder.to_deprecated_string());
  501. } else {
  502. // Ignore the export.
  503. continue;
  504. }
  505. }
  506. int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1);
  507. if (setenv_return != 0) {
  508. perror("setenv");
  509. return 1;
  510. }
  511. if (parts[0] == "PATH")
  512. cache_path();
  513. }
  514. return 0;
  515. }
  516. ErrorOr<int> Shell::builtin_glob(Main::Arguments arguments)
  517. {
  518. Vector<DeprecatedString> globs;
  519. Core::ArgsParser parser;
  520. parser.add_positional_argument(globs, "Globs to resolve", "glob");
  521. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  522. return 1;
  523. for (auto& glob : globs) {
  524. for (auto& expanded : expand_globs(glob, cwd))
  525. outln("{}", expanded);
  526. }
  527. return 0;
  528. }
  529. ErrorOr<int> Shell::builtin_fg(Main::Arguments arguments)
  530. {
  531. int job_id = -1;
  532. bool is_pid = false;
  533. Core::ArgsParser parser;
  534. parser.add_positional_argument(Core::ArgsParser::Arg {
  535. .help_string = "Job ID or Jobspec to bring to foreground",
  536. .name = "job-id",
  537. .min_values = 0,
  538. .max_values = 1,
  539. .accept_value = [&](StringView value) -> bool {
  540. // Check if it's a pid (i.e. literal integer)
  541. if (auto number = value.to_uint(); number.has_value()) {
  542. job_id = number.value();
  543. is_pid = true;
  544. return true;
  545. }
  546. // Check if it's a jobspec
  547. if (auto id = resolve_job_spec(value); id.has_value()) {
  548. job_id = id.value();
  549. is_pid = false;
  550. return true;
  551. }
  552. return false;
  553. } });
  554. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  555. return 1;
  556. if (job_id == -1 && !jobs.is_empty())
  557. job_id = find_last_job_id();
  558. RefPtr<Job> job = find_job(job_id, is_pid);
  559. if (!job) {
  560. if (job_id == -1) {
  561. warnln("fg: No current job");
  562. } else {
  563. warnln("fg: Job with id/pid {} not found", job_id);
  564. }
  565. return 1;
  566. }
  567. job->set_running_in_background(false);
  568. job->set_shell_did_continue(true);
  569. dbgln("Resuming {} ({})", job->pid(), job->cmd());
  570. warnln("Resuming job {} - {}", job->job_id(), job->cmd());
  571. tcsetpgrp(STDOUT_FILENO, job->pgid());
  572. tcsetpgrp(STDIN_FILENO, job->pgid());
  573. // Try using the PGID, but if that fails, just use the PID.
  574. if (killpg(job->pgid(), SIGCONT) < 0) {
  575. if (kill(job->pid(), SIGCONT) < 0) {
  576. perror("kill");
  577. return 1;
  578. }
  579. }
  580. block_on_job(job);
  581. if (job->exited())
  582. return job->exit_code();
  583. else
  584. return 0;
  585. }
  586. ErrorOr<int> Shell::builtin_disown(Main::Arguments arguments)
  587. {
  588. Vector<int> job_ids;
  589. Vector<bool> id_is_pid;
  590. Core::ArgsParser parser;
  591. parser.add_positional_argument(Core::ArgsParser::Arg {
  592. .help_string = "Job IDs or Jobspecs to disown",
  593. .name = "job-id",
  594. .min_values = 0,
  595. .max_values = INT_MAX,
  596. .accept_value = [&](StringView value) -> bool {
  597. // Check if it's a pid (i.e. literal integer)
  598. if (auto number = value.to_uint(); number.has_value()) {
  599. job_ids.append(number.value());
  600. id_is_pid.append(true);
  601. return true;
  602. }
  603. // Check if it's a jobspec
  604. if (auto id = resolve_job_spec(value); id.has_value()) {
  605. job_ids.append(id.value());
  606. id_is_pid.append(false);
  607. return true;
  608. }
  609. return false;
  610. } });
  611. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  612. return 1;
  613. if (job_ids.is_empty()) {
  614. job_ids.append(find_last_job_id());
  615. id_is_pid.append(false);
  616. }
  617. Vector<Job const*> jobs_to_disown;
  618. for (size_t i = 0; i < job_ids.size(); ++i) {
  619. auto id = job_ids[i];
  620. auto is_pid = id_is_pid[i];
  621. auto job = find_job(id, is_pid);
  622. if (!job)
  623. warnln("disown: Job with id/pid {} not found", id);
  624. else
  625. jobs_to_disown.append(job);
  626. }
  627. if (jobs_to_disown.is_empty()) {
  628. if (job_ids.is_empty())
  629. warnln("disown: No current job");
  630. // An error message has already been printed about the nonexistence of each listed job.
  631. return 1;
  632. }
  633. for (auto job : jobs_to_disown) {
  634. job->deactivate();
  635. if (!job->is_running_in_background())
  636. warnln("disown warning: Job {} is currently not running, 'kill -{} {}' to make it continue", job->job_id(), SIGCONT, job->pid());
  637. jobs.remove(job->pid());
  638. }
  639. return 0;
  640. }
  641. ErrorOr<int> Shell::builtin_history(Main::Arguments)
  642. {
  643. for (size_t i = 0; i < m_editor->history().size(); ++i) {
  644. printf("%6zu %s\n", i + 1, m_editor->history()[i].entry.characters());
  645. }
  646. return 0;
  647. }
  648. ErrorOr<int> Shell::builtin_jobs(Main::Arguments arguments)
  649. {
  650. bool list = false, show_pid = false;
  651. Core::ArgsParser parser;
  652. parser.add_option(list, "List all information about jobs", "list", 'l');
  653. parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
  654. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  655. return 1;
  656. Job::PrintStatusMode mode = Job::PrintStatusMode::Basic;
  657. if (show_pid)
  658. mode = Job::PrintStatusMode::OnlyPID;
  659. if (list)
  660. mode = Job::PrintStatusMode::ListAll;
  661. for (auto& it : jobs) {
  662. if (!it.value->print_status(mode))
  663. return 1;
  664. }
  665. return 0;
  666. }
  667. ErrorOr<int> Shell::builtin_popd(Main::Arguments arguments)
  668. {
  669. if (directory_stack.size() <= 1) {
  670. warnln("Shell: popd: directory stack empty");
  671. return 1;
  672. }
  673. bool should_not_switch = false;
  674. Core::ArgsParser parser;
  675. parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
  676. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  677. return 1;
  678. auto popped_path = directory_stack.take_last();
  679. if (should_not_switch)
  680. return 0;
  681. auto new_path = LexicalPath::canonicalized_path(popped_path);
  682. if (chdir(new_path.characters()) < 0) {
  683. warnln("chdir({}) failed: {}", new_path, strerror(errno));
  684. return 1;
  685. }
  686. cwd = new_path;
  687. return 0;
  688. }
  689. ErrorOr<int> Shell::builtin_pushd(Main::Arguments arguments)
  690. {
  691. StringBuilder path_builder;
  692. bool should_switch = true;
  693. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  694. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  695. if (arguments.strings.size() == 1) {
  696. if (directory_stack.size() < 2) {
  697. warnln("pushd: no other directory");
  698. return 1;
  699. }
  700. DeprecatedString dir1 = directory_stack.take_first();
  701. DeprecatedString dir2 = directory_stack.take_first();
  702. directory_stack.insert(0, dir2);
  703. directory_stack.insert(1, dir1);
  704. int rc = chdir(dir2.characters());
  705. if (rc < 0) {
  706. warnln("chdir({}) failed: {}", dir2, strerror(errno));
  707. return 1;
  708. }
  709. cwd = dir2;
  710. return 0;
  711. }
  712. // Let's assume the user's typed in 'pushd <dir>'
  713. if (arguments.strings.size() == 2) {
  714. directory_stack.append(cwd.characters());
  715. if (arguments.strings[1].starts_with('/')) {
  716. path_builder.append(arguments.strings[1]);
  717. } else {
  718. path_builder.appendff("{}/{}", cwd, arguments.strings[1]);
  719. }
  720. } else if (arguments.strings.size() == 3) {
  721. directory_stack.append(cwd.characters());
  722. for (size_t i = 1; i < arguments.strings.size(); i++) {
  723. auto arg = arguments.strings[i];
  724. if (arg.starts_with('-')) {
  725. if (arg.starts_with('/')) {
  726. path_builder.append(arg);
  727. } else {
  728. path_builder.appendff("{}/{}", cwd, arg);
  729. }
  730. }
  731. if (arg == "-n"sv)
  732. should_switch = false;
  733. }
  734. }
  735. auto real_path = LexicalPath::canonicalized_path(path_builder.to_deprecated_string());
  736. struct stat st;
  737. int rc = stat(real_path.characters(), &st);
  738. if (rc < 0) {
  739. warnln("stat({}) failed: {}", real_path, strerror(errno));
  740. return 1;
  741. }
  742. if (!S_ISDIR(st.st_mode)) {
  743. warnln("Not a directory: {}", real_path);
  744. return 1;
  745. }
  746. if (should_switch) {
  747. int rc = chdir(real_path.characters());
  748. if (rc < 0) {
  749. warnln("chdir({}) failed: {}", real_path, strerror(errno));
  750. return 1;
  751. }
  752. cwd = real_path;
  753. }
  754. return 0;
  755. }
  756. ErrorOr<int> Shell::builtin_pwd(Main::Arguments)
  757. {
  758. print_path(cwd);
  759. fputc('\n', stdout);
  760. return 0;
  761. }
  762. ErrorOr<int> Shell::builtin_setopt(Main::Arguments arguments)
  763. {
  764. if (arguments.strings.size() == 1) {
  765. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  766. if (options.name) \
  767. warnln("{}", #name);
  768. ENUMERATE_SHELL_OPTIONS();
  769. #undef __ENUMERATE_SHELL_OPTION
  770. }
  771. Core::ArgsParser parser;
  772. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  773. bool name = false; \
  774. bool not_##name = false; \
  775. parser.add_option(name, "Enable: " description, #name, '\0'); \
  776. parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0');
  777. ENUMERATE_SHELL_OPTIONS();
  778. #undef __ENUMERATE_SHELL_OPTION
  779. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  780. return 1;
  781. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  782. if (name) \
  783. options.name = true; \
  784. if (not_##name) \
  785. options.name = false;
  786. ENUMERATE_SHELL_OPTIONS();
  787. #undef __ENUMERATE_SHELL_OPTION
  788. return 0;
  789. }
  790. ErrorOr<int> Shell::builtin_shift(Main::Arguments arguments)
  791. {
  792. int count = 1;
  793. Core::ArgsParser parser;
  794. parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No);
  795. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  796. return 1;
  797. if (count < 1)
  798. return 0;
  799. auto argv_ = TRY(lookup_local_variable("ARGV"sv));
  800. if (!argv_) {
  801. warnln("shift: ARGV is unset");
  802. return 1;
  803. }
  804. if (!argv_->is_list())
  805. argv_ = adopt_ref(*new AST::ListValue({ const_cast<AST::Value&>(*argv_) }));
  806. auto& values = const_cast<AST::ListValue*>(static_cast<AST::ListValue const*>(argv_.ptr()))->values();
  807. if ((size_t)count > values.size()) {
  808. warnln("shift: shift count must not be greater than {}", values.size());
  809. return 1;
  810. }
  811. for (auto i = 0; i < count; ++i)
  812. (void)values.take_first();
  813. return 0;
  814. }
  815. ErrorOr<int> Shell::builtin_source(Main::Arguments arguments)
  816. {
  817. StringView file_to_source;
  818. Vector<StringView> args;
  819. Core::ArgsParser parser;
  820. parser.add_positional_argument(file_to_source, "File to read commands from", "path");
  821. parser.add_positional_argument(args, "ARGV for the sourced file", "args", Core::ArgsParser::Required::No);
  822. if (!parser.parse(arguments))
  823. return 1;
  824. auto previous_argv = TRY(lookup_local_variable("ARGV"sv));
  825. ScopeGuard guard { [&] {
  826. if (!args.is_empty())
  827. set_local_variable("ARGV", const_cast<AST::Value&>(*previous_argv));
  828. } };
  829. if (!args.is_empty()) {
  830. Vector<String> arguments;
  831. arguments.ensure_capacity(args.size());
  832. for (auto& arg : args)
  833. arguments.append(TRY(String::from_utf8(arg)));
  834. set_local_variable("ARGV", AST::make_ref_counted<AST::ListValue>(move(arguments)));
  835. }
  836. if (!run_file(file_to_source, true))
  837. return 126;
  838. return 0;
  839. }
  840. ErrorOr<int> Shell::builtin_time(Main::Arguments arguments)
  841. {
  842. Vector<StringView> args;
  843. int number_of_iterations = 1;
  844. Core::ArgsParser parser;
  845. parser.add_option(number_of_iterations, "Number of iterations", "iterations", 'n', "iterations");
  846. parser.set_stop_on_first_non_option(true);
  847. parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  848. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  849. return 1;
  850. if (number_of_iterations < 1)
  851. return 1;
  852. AST::Command command;
  853. TRY(command.argv.try_ensure_capacity(args.size()));
  854. for (auto& arg : args)
  855. command.argv.append(TRY(String::from_utf8(arg)));
  856. auto commands = TRY(expand_aliases({ move(command) }));
  857. AK::Statistics iteration_times;
  858. int exit_code = 1;
  859. for (int i = 0; i < number_of_iterations; ++i) {
  860. auto timer = Core::ElapsedTimer::start_new();
  861. for (auto& job : run_commands(commands)) {
  862. block_on_job(job);
  863. exit_code = job->exit_code();
  864. }
  865. iteration_times.add(static_cast<float>(timer.elapsed()));
  866. }
  867. if (number_of_iterations == 1) {
  868. warnln("Time: {} ms", iteration_times.values().first());
  869. } else {
  870. AK::Statistics iteration_times_excluding_first;
  871. for (size_t i = 1; i < iteration_times.size(); i++)
  872. iteration_times_excluding_first.add(iteration_times.values()[i]);
  873. warnln("Timing report: {} ms", iteration_times.sum());
  874. warnln("==============");
  875. warnln("Command: {}", DeprecatedString::join(' ', arguments.strings));
  876. warnln("Average time: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max:{})",
  877. iteration_times.average(), iteration_times.median(),
  878. iteration_times.standard_deviation(),
  879. iteration_times.min(), iteration_times.max());
  880. warnln("Excluding first: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max:{})",
  881. iteration_times_excluding_first.average(), iteration_times_excluding_first.median(),
  882. iteration_times_excluding_first.standard_deviation(),
  883. iteration_times_excluding_first.min(), iteration_times_excluding_first.max());
  884. }
  885. return exit_code;
  886. }
  887. ErrorOr<int> Shell::builtin_umask(Main::Arguments arguments)
  888. {
  889. StringView mask_text;
  890. Core::ArgsParser parser;
  891. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  892. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  893. return 1;
  894. if (mask_text.is_empty()) {
  895. mode_t old_mask = umask(0);
  896. printf("%#o\n", old_mask);
  897. umask(old_mask);
  898. return 0;
  899. }
  900. unsigned mask = 0;
  901. auto matches = true;
  902. // FIXME: There's currently no way to parse an StringView as an octal integer,
  903. // when that becomes available, replace this code.
  904. for (auto byte : mask_text.bytes()) {
  905. if (isspace(byte))
  906. continue;
  907. if (!is_ascii_octal_digit(byte)) {
  908. matches = false;
  909. break;
  910. }
  911. mask = (mask << 3) + (byte - '0');
  912. }
  913. if (matches) {
  914. umask(mask);
  915. return 0;
  916. }
  917. warnln("umask: Invalid mask '{}'", mask_text);
  918. return 1;
  919. }
  920. ErrorOr<int> Shell::builtin_wait(Main::Arguments arguments)
  921. {
  922. Vector<int> job_ids;
  923. Vector<bool> id_is_pid;
  924. Core::ArgsParser parser;
  925. parser.add_positional_argument(Core::ArgsParser::Arg {
  926. .help_string = "Job IDs or Jobspecs to wait for",
  927. .name = "job-id",
  928. .min_values = 0,
  929. .max_values = INT_MAX,
  930. .accept_value = [&](StringView value) -> bool {
  931. // Check if it's a pid (i.e. literal integer)
  932. if (auto number = value.to_uint(); number.has_value()) {
  933. job_ids.append(number.value());
  934. id_is_pid.append(true);
  935. return true;
  936. }
  937. // Check if it's a jobspec
  938. if (auto id = resolve_job_spec(value); id.has_value()) {
  939. job_ids.append(id.value());
  940. id_is_pid.append(false);
  941. return true;
  942. }
  943. return false;
  944. } });
  945. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  946. return 1;
  947. Vector<NonnullRefPtr<Job>> jobs_to_wait_for;
  948. for (size_t i = 0; i < job_ids.size(); ++i) {
  949. auto id = job_ids[i];
  950. auto is_pid = id_is_pid[i];
  951. auto job = find_job(id, is_pid);
  952. if (!job)
  953. warnln("wait: Job with id/pid {} not found", id);
  954. else
  955. jobs_to_wait_for.append(*job);
  956. }
  957. if (job_ids.is_empty()) {
  958. for (auto const& it : jobs)
  959. jobs_to_wait_for.append(it.value);
  960. }
  961. for (auto& job : jobs_to_wait_for) {
  962. job->set_running_in_background(false);
  963. block_on_job(job);
  964. }
  965. return 0;
  966. }
  967. ErrorOr<int> Shell::builtin_unset(Main::Arguments arguments)
  968. {
  969. Vector<DeprecatedString> vars;
  970. bool unset_only_variables = false; // POSIX only.
  971. Core::ArgsParser parser;
  972. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  973. if (m_in_posix_mode)
  974. parser.add_option(unset_only_variables, "Unset only variables", "variables", 'v');
  975. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
  976. return 1;
  977. bool did_touch_path = false;
  978. for (auto& value : vars) {
  979. if (!did_touch_path && value == "PATH"sv)
  980. did_touch_path = true;
  981. if (TRY(lookup_local_variable(value)) != nullptr) {
  982. unset_local_variable(value);
  983. } else if (!unset_only_variables) {
  984. unsetenv(value.characters());
  985. }
  986. }
  987. if (did_touch_path)
  988. cache_path();
  989. return 0;
  990. }
  991. ErrorOr<int> Shell::builtin_not(Main::Arguments arguments)
  992. {
  993. Vector<StringView> args;
  994. Core::ArgsParser parser;
  995. parser.set_stop_on_first_non_option(true);
  996. parser.add_positional_argument(args, "Command to run followed by its arguments", "string");
  997. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
  998. return 1;
  999. AST::Command command;
  1000. TRY(command.argv.try_ensure_capacity(args.size()));
  1001. for (auto& arg : args)
  1002. command.argv.unchecked_append(TRY(String::from_utf8(arg)));
  1003. auto commands = TRY(expand_aliases({ move(command) }));
  1004. int exit_code = 1;
  1005. auto found_a_job = false;
  1006. for (auto& job : run_commands(commands)) {
  1007. found_a_job = true;
  1008. block_on_job(job);
  1009. exit_code = job->exit_code();
  1010. }
  1011. // In case it was a function.
  1012. if (!found_a_job)
  1013. exit_code = last_return_code.value_or(0);
  1014. return exit_code == 0 ? 1 : 0;
  1015. }
  1016. ErrorOr<int> Shell::builtin_kill(Main::Arguments arguments)
  1017. {
  1018. // Simply translate the arguments and pass them to `kill'
  1019. Vector<String> replaced_values;
  1020. auto kill_path = Core::DeprecatedFile::resolve_executable_from_environment("kill"sv);
  1021. if (!kill_path.has_value()) {
  1022. warnln("kill: `kill' not found in PATH");
  1023. return 126;
  1024. }
  1025. replaced_values.append(TRY(String::from_deprecated_string(kill_path.release_value())));
  1026. for (size_t i = 1; i < arguments.strings.size(); ++i) {
  1027. if (auto job_id = resolve_job_spec(arguments.strings[i]); job_id.has_value()) {
  1028. auto job = find_job(job_id.value());
  1029. if (job) {
  1030. replaced_values.append(TRY(String::number(job->pid())));
  1031. } else {
  1032. warnln("kill: Job with pid {} not found", job_id.value());
  1033. return 1;
  1034. }
  1035. } else {
  1036. replaced_values.append(TRY(String::from_utf8(arguments.strings[i])));
  1037. }
  1038. }
  1039. // Now just run `kill'
  1040. AST::Command command;
  1041. command.argv = move(replaced_values);
  1042. command.position = m_source_position.has_value() ? m_source_position->position : Optional<AST::Position> {};
  1043. auto exit_code = 1;
  1044. auto job_result = run_command(command);
  1045. if (job_result.is_error()) {
  1046. warnln("kill: Failed to run {}: {}", command.argv.first(), job_result.error());
  1047. return exit_code;
  1048. }
  1049. if (auto job = job_result.release_value()) {
  1050. block_on_job(job);
  1051. exit_code = job->exit_code();
  1052. }
  1053. return exit_code;
  1054. }
  1055. ErrorOr<bool> Shell::run_builtin(const AST::Command& command, Vector<NonnullRefPtr<AST::Rewiring>> const& rewirings, int& retval)
  1056. {
  1057. if (command.argv.is_empty())
  1058. return false;
  1059. if (!has_builtin(command.argv.first()))
  1060. return false;
  1061. Vector<StringView> arguments;
  1062. TRY(arguments.try_ensure_capacity(command.argv.size()));
  1063. for (auto& arg : command.argv)
  1064. arguments.unchecked_append(arg);
  1065. Main::Arguments arguments_object {
  1066. .argc = 0,
  1067. .argv = nullptr,
  1068. .strings = arguments
  1069. };
  1070. StringView name = command.argv.first();
  1071. SavedFileDescriptors fds { rewirings };
  1072. for (auto& rewiring : rewirings) {
  1073. int rc = dup2(rewiring->old_fd, rewiring->new_fd);
  1074. if (rc < 0) {
  1075. perror("dup2(run)");
  1076. return false;
  1077. }
  1078. }
  1079. Core::EventLoop loop;
  1080. setup_signals();
  1081. if (name == ":"sv)
  1082. name = "noop"sv;
  1083. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  1084. if (name == #builtin) { \
  1085. retval = TRY(builtin_##builtin(arguments_object)); \
  1086. if (!has_error(ShellError::None)) \
  1087. raise_error(m_error, m_error_description, command.position); \
  1088. fflush(stdout); \
  1089. fflush(stderr); \
  1090. return true; \
  1091. }
  1092. ENUMERATE_SHELL_BUILTINS();
  1093. #undef __ENUMERATE_SHELL_BUILTIN
  1094. return false;
  1095. }
  1096. ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
  1097. {
  1098. // argsparser_parse
  1099. // --add-option variable [--type (bool | string | i32 | u32 | double | size)] --help-string "" --long-name "" --short-name "" [--value-name "" <if not --type bool>] --list
  1100. // --add-positional-argument variable [--type (bool | string | i32 | u32 | double | size)] ([--min n] [--max n] | [--required]) --help-string "" --value-name ""
  1101. // [--general-help ""]
  1102. // [--stop-on-first-non-option]
  1103. // --
  1104. // $args_to_parse
  1105. Core::ArgsParser parser;
  1106. Core::ArgsParser user_parser;
  1107. Vector<StringView> descriptors;
  1108. Variant<Core::ArgsParser::Option, Core::ArgsParser::Arg, Empty> current;
  1109. DeprecatedString help_string_storage;
  1110. DeprecatedString long_name_storage;
  1111. DeprecatedString value_name_storage;
  1112. DeprecatedString name_storage;
  1113. DeprecatedString current_variable;
  1114. // if max > 1 or min < 1, or explicit `--list`.
  1115. bool treat_arg_as_list = false;
  1116. enum class Type {
  1117. Bool,
  1118. String,
  1119. I32,
  1120. U32,
  1121. Double,
  1122. Size,
  1123. };
  1124. auto type = Type::String;
  1125. auto try_convert = [](StringView value, Type type) -> ErrorOr<Optional<RefPtr<AST::Value>>> {
  1126. switch (type) {
  1127. case Type::Bool:
  1128. return AST::make_ref_counted<AST::StringValue>(TRY("true"_string));
  1129. case Type::String:
  1130. return AST::make_ref_counted<AST::StringValue>(TRY(String::from_utf8(value)));
  1131. case Type::I32:
  1132. if (auto number = value.to_int(); number.has_value())
  1133. return AST::make_ref_counted<AST::StringValue>(TRY(String::number(*number)));
  1134. warnln("Invalid value for type i32: {}", value);
  1135. return OptionalNone {};
  1136. case Type::U32:
  1137. case Type::Size:
  1138. if (auto number = value.to_uint(); number.has_value())
  1139. return AST::make_ref_counted<AST::StringValue>(TRY(String::number(*number)));
  1140. warnln("Invalid value for type u32|size: {}", value);
  1141. return OptionalNone {};
  1142. case Type::Double: {
  1143. DeprecatedString string = value;
  1144. char* endptr = nullptr;
  1145. auto number = strtod(string.characters(), &endptr);
  1146. if (endptr != string.characters() + string.length()) {
  1147. warnln("Invalid value for type double: {}", value);
  1148. return OptionalNone {};
  1149. }
  1150. return AST::make_ref_counted<AST::StringValue>(TRY(String::number(number)));
  1151. }
  1152. default:
  1153. VERIFY_NOT_REACHED();
  1154. }
  1155. };
  1156. auto enlist = [&](auto name, auto value) -> ErrorOr<NonnullRefPtr<AST::Value>> {
  1157. auto variable = TRY(lookup_local_variable(name));
  1158. if (variable) {
  1159. auto list = TRY(const_cast<AST::Value&>(*variable).resolve_as_list(*this));
  1160. auto new_value = TRY(value->resolve_as_string(*this));
  1161. list.append(move(new_value));
  1162. return try_make_ref_counted<AST::ListValue>(move(list));
  1163. }
  1164. return *value;
  1165. };
  1166. // FIXME: We cannot return ErrorOr<T> from Core::ArgsParser::Option::accept_value(), fix the MUST's here whenever that function is ErrorOr-aware.
  1167. auto commit = [&] {
  1168. return current.visit(
  1169. [&](Core::ArgsParser::Option& option) {
  1170. if (!option.long_name && !option.short_name) {
  1171. warnln("Defined option must have at least one of --long-name or --short-name");
  1172. return false;
  1173. }
  1174. option.accept_value = [&, current_variable, treat_arg_as_list, type](StringView value) {
  1175. auto result = MUST(try_convert(value, type));
  1176. if (result.has_value()) {
  1177. auto value = result.release_value();
  1178. if (treat_arg_as_list)
  1179. value = MUST(enlist(current_variable, move(value)));
  1180. this->set_local_variable(current_variable, move(value), true);
  1181. return true;
  1182. }
  1183. return false;
  1184. };
  1185. user_parser.add_option(move(option));
  1186. type = Type::String;
  1187. treat_arg_as_list = false;
  1188. return true;
  1189. },
  1190. [&](Core::ArgsParser::Arg& arg) {
  1191. if (!arg.name) {
  1192. warnln("Defined positional argument must have a name");
  1193. return false;
  1194. }
  1195. arg.accept_value = [&, current_variable, treat_arg_as_list, type](StringView value) {
  1196. auto result = MUST(try_convert(value, type));
  1197. if (result.has_value()) {
  1198. auto value = result.release_value();
  1199. if (treat_arg_as_list)
  1200. value = MUST(enlist(current_variable, move(value)));
  1201. this->set_local_variable(current_variable, move(value), true);
  1202. return true;
  1203. }
  1204. return false;
  1205. };
  1206. user_parser.add_positional_argument(move(arg));
  1207. type = Type::String;
  1208. treat_arg_as_list = false;
  1209. return true;
  1210. },
  1211. [&](Empty) {
  1212. return true;
  1213. });
  1214. };
  1215. parser.add_option(Core::ArgsParser::Option {
  1216. .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
  1217. .help_string = "Stop processing descriptors after a non-argument parameter is seen",
  1218. .long_name = "stop-on-first-non-option",
  1219. .accept_value = [&](auto) {
  1220. user_parser.set_stop_on_first_non_option(true);
  1221. return true;
  1222. },
  1223. });
  1224. parser.add_option(Core::ArgsParser::Option {
  1225. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1226. .help_string = "Set the general help string for the parser",
  1227. .long_name = "general-help",
  1228. .value_name = "string",
  1229. .accept_value = [&](StringView value) {
  1230. VERIFY(strlen(value.characters_without_null_termination()) == value.length());
  1231. user_parser.set_general_help(value.characters_without_null_termination());
  1232. return true;
  1233. },
  1234. });
  1235. parser.add_option(Core::ArgsParser::Option {
  1236. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1237. .help_string = "Start describing an option",
  1238. .long_name = "add-option",
  1239. .value_name = "variable-name",
  1240. .accept_value = [&](auto name) {
  1241. if (!commit())
  1242. return false;
  1243. current = Core::ArgsParser::Option {};
  1244. current_variable = name;
  1245. if (current_variable.is_empty() || !all_of(current_variable, [](auto ch) { return ch == '_' || isalnum(ch); })) {
  1246. warnln("Option variable name must be a valid identifier");
  1247. return false;
  1248. }
  1249. return true;
  1250. },
  1251. });
  1252. parser.add_option(Core::ArgsParser::Option {
  1253. .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
  1254. .help_string = "Accept multiple of the current option being given",
  1255. .long_name = "list",
  1256. .accept_value = [&](auto) {
  1257. if (!current.has<Core::ArgsParser::Option>()) {
  1258. warnln("Must be defining an option to use --list");
  1259. return false;
  1260. }
  1261. treat_arg_as_list = true;
  1262. return true;
  1263. },
  1264. });
  1265. parser.add_option(Core::ArgsParser::Option {
  1266. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1267. .help_string = "Define the type of the option or argument being described",
  1268. .long_name = "type",
  1269. .value_name = "type",
  1270. .accept_value = [&](StringView ty) {
  1271. if (current.has<Empty>()) {
  1272. warnln("Must be defining an argument or option to use --type");
  1273. return false;
  1274. }
  1275. if (ty == "bool") {
  1276. if (auto option = current.get_pointer<Core::ArgsParser::Option>()) {
  1277. if (option->value_name != nullptr) {
  1278. warnln("Type 'bool' does not apply to options with a value (value name is set to {})", option->value_name);
  1279. return false;
  1280. }
  1281. }
  1282. type = Type::Bool;
  1283. } else if (ty == "string") {
  1284. type = Type::String;
  1285. } else if (ty == "i32") {
  1286. type = Type::I32;
  1287. } else if (ty == "u32") {
  1288. type = Type::U32;
  1289. } else if (ty == "double") {
  1290. type = Type::Double;
  1291. } else if (ty == "size") {
  1292. type = Type::Size;
  1293. } else {
  1294. warnln("Invalid type '{}', expected one of bool | string | i32 | u32 | double | size", ty);
  1295. return false;
  1296. }
  1297. if (type == Type::Bool) {
  1298. set_local_variable(
  1299. current_variable,
  1300. make_ref_counted<AST::StringValue>(MUST("false"_string)),
  1301. true);
  1302. }
  1303. return true;
  1304. },
  1305. });
  1306. parser.add_option(Core::ArgsParser::Option {
  1307. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1308. .help_string = "Set the help string of the option or argument being defined",
  1309. .long_name = "help-string",
  1310. .value_name = "string",
  1311. .accept_value = [&](StringView value) {
  1312. return current.visit(
  1313. [](Empty) {
  1314. warnln("Must be defining an option or argument to use --help-string");
  1315. return false;
  1316. },
  1317. [&](auto& option) {
  1318. help_string_storage = value;
  1319. option.help_string = help_string_storage.characters();
  1320. return true;
  1321. });
  1322. },
  1323. });
  1324. parser.add_option(Core::ArgsParser::Option {
  1325. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1326. .help_string = "Set the long name of the option being defined",
  1327. .long_name = "long-name",
  1328. .value_name = "name",
  1329. .accept_value = [&](StringView value) {
  1330. auto option = current.get_pointer<Core::ArgsParser::Option>();
  1331. if (!option) {
  1332. warnln("Must be defining an option to use --long-name");
  1333. return false;
  1334. }
  1335. if (option->long_name) {
  1336. warnln("Repeated application of --long-name is not allowed, current option has long name set to \"{}\"", option->long_name);
  1337. return false;
  1338. }
  1339. long_name_storage = value;
  1340. option->long_name = long_name_storage.characters();
  1341. return true;
  1342. },
  1343. });
  1344. parser.add_option(Core::ArgsParser::Option {
  1345. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1346. .help_string = "Set the short name of the option being defined",
  1347. .long_name = "short-name",
  1348. .value_name = "char",
  1349. .accept_value = [&](StringView value) {
  1350. auto option = current.get_pointer<Core::ArgsParser::Option>();
  1351. if (!option) {
  1352. warnln("Must be defining an option to use --short-name");
  1353. return false;
  1354. }
  1355. if (value.length() != 1) {
  1356. warnln("Option short name ('{}') must be exactly one character long", value);
  1357. return false;
  1358. }
  1359. if (option->short_name) {
  1360. warnln("Repeated application of --short-name is not allowed, current option has short name set to '{}'", option->short_name);
  1361. return false;
  1362. }
  1363. option->short_name = value[0];
  1364. return true;
  1365. },
  1366. });
  1367. parser.add_option(Core::ArgsParser::Option {
  1368. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1369. .help_string = "Set the value name of the option being defined",
  1370. .long_name = "value-name",
  1371. .value_name = "string",
  1372. .accept_value = [&](StringView value) {
  1373. return current.visit(
  1374. [](Empty) {
  1375. warnln("Must be defining an option or a positional argument to use --value-name");
  1376. return false;
  1377. },
  1378. [&](Core::ArgsParser::Option& option) {
  1379. if (option.value_name) {
  1380. warnln("Repeated application of --value-name is not allowed, current option has value name set to \"{}\"", option.value_name);
  1381. return false;
  1382. }
  1383. if (type == Type::Bool) {
  1384. warnln("Options of type bool cannot have a value name");
  1385. return false;
  1386. }
  1387. value_name_storage = value;
  1388. option.value_name = value_name_storage.characters();
  1389. return true;
  1390. },
  1391. [&](Core::ArgsParser::Arg& arg) {
  1392. if (arg.name) {
  1393. warnln("Repeated application of --value-name is not allowed, current argument has value name set to \"{}\"", arg.name);
  1394. return false;
  1395. }
  1396. name_storage = value;
  1397. arg.name = name_storage.characters();
  1398. return true;
  1399. });
  1400. },
  1401. });
  1402. parser.add_option(Core::ArgsParser::Option {
  1403. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1404. .help_string = "Start describing a positional argument",
  1405. .long_name = "add-positional-argument",
  1406. .value_name = "variable",
  1407. .accept_value = [&](auto value) {
  1408. if (!commit())
  1409. return false;
  1410. current = Core::ArgsParser::Arg {};
  1411. current_variable = value;
  1412. if (current_variable.is_empty() || !all_of(current_variable, [](auto ch) { return ch == '_' || isalnum(ch); })) {
  1413. warnln("Argument variable name must be a valid identifier");
  1414. return false;
  1415. }
  1416. return true;
  1417. },
  1418. });
  1419. parser.add_option(Core::ArgsParser::Option {
  1420. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1421. .help_string = "Set the minimum required number of positional descriptors for the argument being described",
  1422. .long_name = "min",
  1423. .value_name = "n",
  1424. .accept_value = [&](StringView value) {
  1425. auto arg = current.get_pointer<Core::ArgsParser::Arg>();
  1426. if (!arg) {
  1427. warnln("Must be describing a positional argument to use --min");
  1428. return false;
  1429. }
  1430. auto number = value.to_uint();
  1431. if (!number.has_value()) {
  1432. warnln("Invalid value for --min: '{}', expected a non-negative number", value);
  1433. return false;
  1434. }
  1435. if (static_cast<unsigned>(arg->max_values) < *number) {
  1436. warnln("Invalid value for --min: {}, min must not be larger than max ({})", *number, arg->max_values);
  1437. return false;
  1438. }
  1439. arg->min_values = *number;
  1440. treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
  1441. return true;
  1442. },
  1443. });
  1444. parser.add_option(Core::ArgsParser::Option {
  1445. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  1446. .help_string = "Set the maximum required number of positional descriptors for the argument being described",
  1447. .long_name = "max",
  1448. .value_name = "n",
  1449. .accept_value = [&](StringView value) {
  1450. auto arg = current.get_pointer<Core::ArgsParser::Arg>();
  1451. if (!arg) {
  1452. warnln("Must be describing a positional argument to use --max");
  1453. return false;
  1454. }
  1455. auto number = value.to_uint();
  1456. if (!number.has_value()) {
  1457. warnln("Invalid value for --max: '{}', expected a non-negative number", value);
  1458. return false;
  1459. }
  1460. if (static_cast<unsigned>(arg->min_values) > *number) {
  1461. warnln("Invalid value for --max: {}, max must not be smaller than min ({})", *number, arg->min_values);
  1462. return false;
  1463. }
  1464. arg->max_values = *number;
  1465. treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
  1466. return true;
  1467. },
  1468. });
  1469. parser.add_option(Core::ArgsParser::Option {
  1470. .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
  1471. .help_string = "Mark the positional argument being described as required (shorthand for --min 1)",
  1472. .long_name = "required",
  1473. .accept_value = [&](auto) {
  1474. auto arg = current.get_pointer<Core::ArgsParser::Arg>();
  1475. if (!arg) {
  1476. warnln("Must be describing a positional argument to use --required");
  1477. return false;
  1478. }
  1479. arg->min_values = 1;
  1480. if (arg->max_values < arg->min_values)
  1481. arg->max_values = 1;
  1482. treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
  1483. return true;
  1484. },
  1485. });
  1486. parser.add_positional_argument(descriptors, "Arguments to parse via the described ArgsParser configuration", "arg", Core::ArgsParser::Required::No);
  1487. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
  1488. return 2;
  1489. if (!commit())
  1490. return 2;
  1491. if (!user_parser.parse(descriptors, Core::ArgsParser::FailureBehavior::Ignore))
  1492. return 1;
  1493. return 0;
  1494. }
  1495. ErrorOr<int> Shell::builtin_read(Main::Arguments arguments)
  1496. {
  1497. if (!m_in_posix_mode) {
  1498. raise_error(ShellError::EvaluatedSyntaxError, "read: POSIX builtin used in non-POSIX mode");
  1499. return 1;
  1500. }
  1501. bool no_escape = false;
  1502. Vector<DeprecatedString> variables;
  1503. Core::ArgsParser parser;
  1504. parser.add_option(no_escape, "Do not interpret backslash escapes", "no-escape", 'r');
  1505. parser.add_positional_argument(variables, "Variables to read into", "variable", Core::ArgsParser::Required::Yes);
  1506. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
  1507. return 1;
  1508. auto split_by_any_of = " \t\n"_short_string;
  1509. if (auto const* value_from_env = getenv("IFS"); value_from_env)
  1510. split_by_any_of = TRY(String::from_utf8({ value_from_env, strlen(value_from_env) }));
  1511. else if (auto split_by_variable = TRY(lookup_local_variable("IFS"sv)); split_by_variable)
  1512. split_by_any_of = TRY(const_cast<AST::Value&>(*split_by_variable).resolve_as_string(*this));
  1513. auto file = TRY(Core::File::standard_input());
  1514. auto buffered_stream = TRY(Core::BufferedFile::create(move(file)));
  1515. StringBuilder builder;
  1516. ByteBuffer buffer;
  1517. enum class LineState {
  1518. Done,
  1519. EscapedNewline,
  1520. };
  1521. auto read_line = [&]() -> ErrorOr<LineState> {
  1522. if (m_is_interactive && isatty(STDIN_FILENO)) {
  1523. // Show prompt
  1524. warn("read: ");
  1525. }
  1526. size_t attempted_line_size = 32;
  1527. for (;;) {
  1528. auto result = buffered_stream->read_line(TRY(buffer.get_bytes_for_writing(attempted_line_size)));
  1529. if (result.is_error() && result.error().is_errno() && result.error().code() == EMSGSIZE) {
  1530. attempted_line_size *= 2;
  1531. continue;
  1532. }
  1533. auto used_bytes = TRY(move(result));
  1534. if (!no_escape && used_bytes.ends_with("\\\n"sv)) {
  1535. builder.append(used_bytes.substring_view(0, used_bytes.length() - 2));
  1536. return LineState::EscapedNewline;
  1537. }
  1538. if (used_bytes.ends_with("\n"sv))
  1539. used_bytes = used_bytes.substring_view(0, used_bytes.length() - 1);
  1540. builder.append(used_bytes);
  1541. return LineState::Done;
  1542. }
  1543. };
  1544. LineState state;
  1545. do {
  1546. state = TRY(read_line());
  1547. } while (state == LineState::EscapedNewline);
  1548. auto line = builder.string_view();
  1549. if (variables.size() == 1) {
  1550. set_local_variable(variables[0], make_ref_counted<AST::StringValue>(TRY(String::from_utf8(line))));
  1551. return 0;
  1552. }
  1553. auto fields = line.split_view_if(is_any_of(split_by_any_of), SplitBehavior::KeepEmpty);
  1554. for (size_t i = 0; i < variables.size(); ++i) {
  1555. auto& variable = variables[i];
  1556. StringView variable_value;
  1557. if (i >= fields.size())
  1558. variable_value = ""sv;
  1559. else if (i == variables.size() - 1)
  1560. variable_value = line.substring_view_starting_from_substring(fields[i]);
  1561. else
  1562. variable_value = fields[i];
  1563. set_local_variable(variable, make_ref_counted<AST::StringValue>(TRY(String::from_utf8(variable_value))));
  1564. }
  1565. return 0;
  1566. }
  1567. ErrorOr<int> Shell::builtin_run_with_env(Main::Arguments arguments)
  1568. {
  1569. Vector<DeprecatedString> environment_variables;
  1570. Vector<StringView> command_and_arguments;
  1571. Core::ArgsParser parser;
  1572. parser.add_option(environment_variables, "Environment variables to set", "env", 'e', "NAME=VALUE");
  1573. parser.add_positional_argument(command_and_arguments, "Command and arguments to run", "command", Core::ArgsParser::Required::Yes);
  1574. parser.set_stop_on_first_non_option(true);
  1575. if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
  1576. return 1;
  1577. if (command_and_arguments.is_empty()) {
  1578. warnln("run_with_env: No command to run");
  1579. return 1;
  1580. }
  1581. AST::Command command;
  1582. TRY(command.argv.try_ensure_capacity(command_and_arguments.size()));
  1583. for (auto& arg : command_and_arguments)
  1584. command.argv.append(TRY(String::from_utf8(arg)));
  1585. auto commands = TRY(expand_aliases({ move(command) }));
  1586. HashMap<DeprecatedString, Optional<DeprecatedString>> old_environment_entries;
  1587. for (auto& variable : environment_variables) {
  1588. auto parts = variable.split_limit('=', 2, SplitBehavior::KeepEmpty);
  1589. if (parts.size() != 2) {
  1590. warnln("run_with_env: Invalid environment variable: '{}'", variable);
  1591. return 1;
  1592. }
  1593. DeprecatedString name = parts[0];
  1594. old_environment_entries.set(name, getenv(name.characters()) ?: Optional<DeprecatedString> {});
  1595. DeprecatedString value = parts[1];
  1596. setenv(name.characters(), value.characters(), 1);
  1597. }
  1598. int exit_code = 0;
  1599. for (auto& job : run_commands(commands)) {
  1600. block_on_job(job);
  1601. exit_code = job->exit_code();
  1602. }
  1603. for (auto& entry : old_environment_entries) {
  1604. if (entry.value.has_value())
  1605. setenv(entry.key.characters(), entry.value->characters(), 1);
  1606. else
  1607. unsetenv(entry.key.characters());
  1608. }
  1609. return exit_code;
  1610. }
  1611. bool Shell::has_builtin(StringView name) const
  1612. {
  1613. if (name == ":"sv)
  1614. return true;
  1615. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  1616. if (name == #builtin) { \
  1617. return true; \
  1618. }
  1619. ENUMERATE_SHELL_BUILTINS();
  1620. #undef __ENUMERATE_SHELL_BUILTIN
  1621. return false;
  1622. }
  1623. }