Builtin.cpp 64 KB

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