Builtin.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "AST.h"
  7. #include "Shell.h"
  8. #include "Shell/Formatter.h"
  9. #include <AK/LexicalPath.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/Statistics.h>
  12. #include <AK/String.h>
  13. #include <LibCore/ArgsParser.h>
  14. #include <LibCore/EventLoop.h>
  15. #include <LibCore/File.h>
  16. #include <errno.h>
  17. #include <inttypes.h>
  18. #include <limits.h>
  19. #include <signal.h>
  20. #include <sys/wait.h>
  21. #include <unistd.h>
  22. extern char** environ;
  23. namespace Shell {
  24. int Shell::builtin_dump(int argc, const char** argv)
  25. {
  26. if (argc != 2)
  27. return 1;
  28. Parser { argv[1] }.parse()->dump(0);
  29. return 0;
  30. }
  31. int Shell::builtin_alias(int argc, const char** argv)
  32. {
  33. Vector<const char*> arguments;
  34. Core::ArgsParser parser;
  35. parser.add_positional_argument(arguments, "List of name[=values]'s", "name[=value]", Core::ArgsParser::Required::No);
  36. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  37. return 1;
  38. if (arguments.is_empty()) {
  39. for (auto& alias : m_aliases)
  40. printf("%s=%s\n", escape_token(alias.key).characters(), escape_token(alias.value).characters());
  41. return 0;
  42. }
  43. bool fail = false;
  44. for (auto& argument : arguments) {
  45. auto parts = String { argument }.split_limit('=', 2, true);
  46. if (parts.size() == 1) {
  47. auto alias = m_aliases.get(parts[0]);
  48. if (alias.has_value()) {
  49. printf("%s=%s\n", escape_token(parts[0]).characters(), escape_token(alias.value()).characters());
  50. } else {
  51. fail = true;
  52. }
  53. } else {
  54. m_aliases.set(parts[0], parts[1]);
  55. add_entry_to_cache(parts[0]);
  56. }
  57. }
  58. return fail ? 1 : 0;
  59. }
  60. int Shell::builtin_unalias(int argc, const char** argv)
  61. {
  62. bool remove_all { false };
  63. Vector<const char*> arguments;
  64. Core::ArgsParser parser;
  65. parser.set_general_help("Remove alias from the list of aliases");
  66. parser.add_option(remove_all, "Remove all aliases", nullptr, 'a');
  67. parser.add_positional_argument(arguments, "List of aliases to remove", "alias", Core::ArgsParser::Required::No);
  68. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  69. return 1;
  70. if (remove_all) {
  71. m_aliases.clear();
  72. cache_path();
  73. return 0;
  74. }
  75. if (arguments.is_empty()) {
  76. warnln("unalias: not enough arguments");
  77. parser.print_usage(stderr, argv[0]);
  78. return 1;
  79. }
  80. bool failed { false };
  81. for (auto& argument : arguments) {
  82. if (!m_aliases.contains(argument)) {
  83. warnln("unalias: {}: alias not found", argument);
  84. failed = true;
  85. continue;
  86. }
  87. m_aliases.remove(argument);
  88. remove_entry_from_cache(argument);
  89. }
  90. return failed ? 1 : 0;
  91. }
  92. int Shell::builtin_bg(int argc, const char** argv)
  93. {
  94. int job_id = -1;
  95. bool is_pid = false;
  96. Core::ArgsParser parser;
  97. parser.add_positional_argument(Core::ArgsParser::Arg {
  98. .help_string = "Job ID or Jobspec to run in background",
  99. .name = "job-id",
  100. .min_values = 0,
  101. .max_values = 1,
  102. .accept_value = [&](const String& value) -> bool {
  103. // Check if it's a pid (i.e. literal integer)
  104. if (auto number = value.to_uint(); number.has_value()) {
  105. job_id = number.value();
  106. is_pid = true;
  107. return true;
  108. }
  109. // Check if it's a jobspec
  110. if (auto id = resolve_job_spec(value); id.has_value()) {
  111. job_id = id.value();
  112. is_pid = false;
  113. return true;
  114. }
  115. return false;
  116. } });
  117. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  118. return 1;
  119. if (job_id == -1 && !jobs.is_empty())
  120. job_id = find_last_job_id();
  121. auto* job = const_cast<Job*>(find_job(job_id, is_pid));
  122. if (!job) {
  123. if (job_id == -1) {
  124. warnln("bg: No current job");
  125. } else {
  126. warnln("bg: Job with id/pid {} not found", job_id);
  127. }
  128. return 1;
  129. }
  130. job->set_running_in_background(true);
  131. job->set_should_announce_exit(true);
  132. job->set_shell_did_continue(true);
  133. dbgln("Resuming {} ({})", job->pid(), job->cmd());
  134. warnln("Resuming job {} - {}", job->job_id(), job->cmd());
  135. // Try using the PGID, but if that fails, just use the PID.
  136. if (killpg(job->pgid(), SIGCONT) < 0) {
  137. if (kill(job->pid(), SIGCONT) < 0) {
  138. perror("kill");
  139. return 1;
  140. }
  141. }
  142. return 0;
  143. }
  144. int Shell::builtin_type(int argc, const char** argv)
  145. {
  146. Vector<const char*> commands;
  147. bool dont_show_function_source = false;
  148. Core::ArgsParser parser;
  149. parser.set_general_help("Display information about commands.");
  150. parser.add_positional_argument(commands, "Command(s) to list info about", "command");
  151. parser.add_option(dont_show_function_source, "Do not show functions source.", "no-fn-source", 'f');
  152. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  153. return 1;
  154. bool something_not_found = false;
  155. for (auto& command : commands) {
  156. // check if it is an alias
  157. if (auto alias = m_aliases.get(command); alias.has_value()) {
  158. printf("%s is aliased to `%s`\n", escape_token(command).characters(), escape_token(alias.value()).characters());
  159. continue;
  160. }
  161. // check if it is a function
  162. if (auto function = m_functions.get(command); function.has_value()) {
  163. auto fn = function.value();
  164. printf("%s is a function\n", command);
  165. if (!dont_show_function_source) {
  166. StringBuilder builder;
  167. builder.append(fn.name);
  168. builder.append("(");
  169. for (size_t i = 0; i < fn.arguments.size(); i++) {
  170. builder.append(fn.arguments[i]);
  171. if (!(i == fn.arguments.size() - 1))
  172. builder.append(" ");
  173. }
  174. builder.append(") {\n");
  175. if (fn.body) {
  176. auto formatter = Formatter(*fn.body);
  177. builder.append(formatter.format());
  178. printf("%s\n}\n", builder.build().characters());
  179. } else {
  180. printf("%s\n}\n", builder.build().characters());
  181. }
  182. }
  183. continue;
  184. }
  185. // check if its a builtin
  186. if (has_builtin(command)) {
  187. printf("%s is a shell builtin\n", command);
  188. continue;
  189. }
  190. // check if its an executable in PATH
  191. auto fullpath = Core::find_executable_in_path(command);
  192. if (!fullpath.is_empty()) {
  193. printf("%s is %s\n", command, escape_token(fullpath).characters());
  194. continue;
  195. }
  196. something_not_found = true;
  197. printf("type: %s not found\n", command);
  198. }
  199. if (something_not_found)
  200. return 1;
  201. else
  202. return 0;
  203. }
  204. int Shell::builtin_cd(int argc, const char** argv)
  205. {
  206. const char* arg_path = nullptr;
  207. Core::ArgsParser parser;
  208. parser.add_positional_argument(arg_path, "Path to change to", "path", Core::ArgsParser::Required::No);
  209. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  210. return 1;
  211. String new_path;
  212. if (!arg_path) {
  213. new_path = home;
  214. } else {
  215. if (strcmp(arg_path, "-") == 0) {
  216. char* oldpwd = getenv("OLDPWD");
  217. if (oldpwd == nullptr)
  218. return 1;
  219. new_path = oldpwd;
  220. } else {
  221. new_path = arg_path;
  222. }
  223. }
  224. auto real_path = Core::File::real_path_for(new_path);
  225. if (real_path.is_empty()) {
  226. warnln("Invalid path '{}'", new_path);
  227. return 1;
  228. }
  229. if (cd_history.is_empty() || cd_history.last() != real_path)
  230. cd_history.enqueue(real_path);
  231. auto path_relative_to_current_directory = LexicalPath::relative_path(real_path, cwd);
  232. if (path_relative_to_current_directory.is_empty())
  233. path_relative_to_current_directory = real_path;
  234. const char* path = path_relative_to_current_directory.characters();
  235. int rc = chdir(path);
  236. if (rc < 0) {
  237. if (errno == ENOTDIR) {
  238. warnln("Not a directory: {}", path);
  239. } else {
  240. warnln("chdir({}) failed: {}", path, strerror(errno));
  241. }
  242. return 1;
  243. }
  244. setenv("OLDPWD", cwd.characters(), 1);
  245. cwd = move(real_path);
  246. setenv("PWD", cwd.characters(), 1);
  247. return 0;
  248. }
  249. int Shell::builtin_cdh(int argc, const char** argv)
  250. {
  251. int index = -1;
  252. Core::ArgsParser parser;
  253. parser.add_positional_argument(index, "Index of the cd history entry (leave out for a list)", "index", Core::ArgsParser::Required::No);
  254. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  255. return 1;
  256. if (index == -1) {
  257. if (cd_history.is_empty()) {
  258. warnln("cdh: no history available");
  259. return 0;
  260. }
  261. for (ssize_t i = cd_history.size() - 1; i >= 0; --i)
  262. printf("%zu: %s\n", cd_history.size() - i, cd_history.at(i).characters());
  263. return 0;
  264. }
  265. if (index < 1 || (size_t)index > cd_history.size()) {
  266. warnln("cdh: history index out of bounds: {} not in (0, {})", index, cd_history.size());
  267. return 1;
  268. }
  269. const char* path = cd_history.at(cd_history.size() - index).characters();
  270. const char* cd_args[] = { "cd", path, nullptr };
  271. return Shell::builtin_cd(2, cd_args);
  272. }
  273. int Shell::builtin_dirs(int argc, const char** argv)
  274. {
  275. // The first directory in the stack is ALWAYS the current directory
  276. directory_stack.at(0) = cwd.characters();
  277. bool clear = false;
  278. bool print = false;
  279. bool number_when_printing = false;
  280. char separator = ' ';
  281. Vector<const char*> paths;
  282. Core::ArgsParser parser;
  283. parser.add_option(clear, "Clear the directory stack", "clear", 'c');
  284. parser.add_option(print, "Print directory entries one per line", "print", 'p');
  285. parser.add_option(number_when_printing, "Number the directories in the stack when printing", "number", 'v');
  286. parser.add_positional_argument(paths, "Extra paths to put on the stack", "path", Core::ArgsParser::Required::No);
  287. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  288. return 1;
  289. // -v implies -p
  290. print = print || number_when_printing;
  291. if (print) {
  292. if (!paths.is_empty()) {
  293. warnln("dirs: 'print' and 'number' are not allowed when any path is specified");
  294. return 1;
  295. }
  296. separator = '\n';
  297. }
  298. if (clear) {
  299. for (size_t i = 1; i < directory_stack.size(); i++)
  300. directory_stack.remove(i);
  301. }
  302. for (auto& path : paths)
  303. directory_stack.append(path);
  304. if (print || (!clear && paths.is_empty())) {
  305. int index = 0;
  306. for (auto& directory : directory_stack) {
  307. if (number_when_printing)
  308. printf("%d ", index++);
  309. print_path(directory);
  310. fputc(separator, stdout);
  311. }
  312. }
  313. return 0;
  314. }
  315. int Shell::builtin_exec(int argc, const char** argv)
  316. {
  317. if (argc < 2) {
  318. warnln("Shell: No command given to exec");
  319. return 1;
  320. }
  321. Vector<const char*> argv_vector;
  322. argv_vector.append(argv + 1, argc - 1);
  323. argv_vector.append(nullptr);
  324. execute_process(move(argv_vector));
  325. }
  326. int Shell::builtin_exit(int argc, const char** argv)
  327. {
  328. int exit_code = 0;
  329. Core::ArgsParser parser;
  330. parser.add_positional_argument(exit_code, "Exit code", "code", Core::ArgsParser::Required::No);
  331. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  332. return 1;
  333. if (m_is_interactive) {
  334. if (!jobs.is_empty()) {
  335. if (!m_should_ignore_jobs_on_next_exit) {
  336. warnln("Shell: You have {} active job{}, run 'exit' again to really exit.", jobs.size(), jobs.size() > 1 ? "s" : "");
  337. m_should_ignore_jobs_on_next_exit = true;
  338. return 1;
  339. }
  340. }
  341. }
  342. stop_all_jobs();
  343. if (m_is_interactive) {
  344. m_editor->save_history(get_history_path());
  345. printf("Good-bye!\n");
  346. }
  347. exit(exit_code);
  348. }
  349. int Shell::builtin_export(int argc, const char** argv)
  350. {
  351. Vector<const char*> vars;
  352. Core::ArgsParser parser;
  353. parser.add_positional_argument(vars, "List of variable[=value]'s", "values", Core::ArgsParser::Required::No);
  354. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  355. return 1;
  356. if (vars.is_empty()) {
  357. for (size_t i = 0; environ[i]; ++i)
  358. puts(environ[i]);
  359. return 0;
  360. }
  361. for (auto& value : vars) {
  362. auto parts = String { value }.split_limit('=', 2);
  363. if (parts.size() == 1) {
  364. auto value = lookup_local_variable(parts[0]);
  365. if (value) {
  366. auto values = value->resolve_as_list(*this);
  367. StringBuilder builder;
  368. builder.join(" ", values);
  369. parts.append(builder.to_string());
  370. } else {
  371. // Ignore the export.
  372. continue;
  373. }
  374. }
  375. int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1);
  376. if (setenv_return != 0) {
  377. perror("setenv");
  378. return 1;
  379. }
  380. if (parts[0] == "PATH")
  381. cache_path();
  382. }
  383. return 0;
  384. }
  385. int Shell::builtin_glob(int argc, const char** argv)
  386. {
  387. Vector<const char*> globs;
  388. Core::ArgsParser parser;
  389. parser.add_positional_argument(globs, "Globs to resolve", "glob");
  390. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  391. return 1;
  392. for (auto& glob : globs) {
  393. for (auto& expanded : expand_globs(glob, cwd))
  394. outln("{}", expanded);
  395. }
  396. return 0;
  397. }
  398. int Shell::builtin_fg(int argc, const char** argv)
  399. {
  400. int job_id = -1;
  401. bool is_pid = false;
  402. Core::ArgsParser parser;
  403. parser.add_positional_argument(Core::ArgsParser::Arg {
  404. .help_string = "Job ID or Jobspec to bring to foreground",
  405. .name = "job-id",
  406. .min_values = 0,
  407. .max_values = 1,
  408. .accept_value = [&](const String& value) -> bool {
  409. // Check if it's a pid (i.e. literal integer)
  410. if (auto number = value.to_uint(); number.has_value()) {
  411. job_id = number.value();
  412. is_pid = true;
  413. return true;
  414. }
  415. // Check if it's a jobspec
  416. if (auto id = resolve_job_spec(value); id.has_value()) {
  417. job_id = id.value();
  418. is_pid = false;
  419. return true;
  420. }
  421. return false;
  422. } });
  423. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  424. return 1;
  425. if (job_id == -1 && !jobs.is_empty())
  426. job_id = find_last_job_id();
  427. RefPtr<Job> job = find_job(job_id, is_pid);
  428. if (!job) {
  429. if (job_id == -1) {
  430. warnln("fg: No current job");
  431. } else {
  432. warnln("fg: Job with id/pid {} not found", job_id);
  433. }
  434. return 1;
  435. }
  436. job->set_running_in_background(false);
  437. job->set_shell_did_continue(true);
  438. dbgln("Resuming {} ({})", job->pid(), job->cmd());
  439. warnln("Resuming job {} - {}", job->job_id(), job->cmd());
  440. tcsetpgrp(STDOUT_FILENO, job->pgid());
  441. tcsetpgrp(STDIN_FILENO, job->pgid());
  442. // Try using the PGID, but if that fails, just use the PID.
  443. if (killpg(job->pgid(), SIGCONT) < 0) {
  444. if (kill(job->pid(), SIGCONT) < 0) {
  445. perror("kill");
  446. return 1;
  447. }
  448. }
  449. block_on_job(job);
  450. if (job->exited())
  451. return job->exit_code();
  452. else
  453. return 0;
  454. }
  455. int Shell::builtin_disown(int argc, const char** argv)
  456. {
  457. Vector<int> job_ids;
  458. Vector<bool> id_is_pid;
  459. Core::ArgsParser parser;
  460. parser.add_positional_argument(Core::ArgsParser::Arg {
  461. .help_string = "Job IDs or Jobspecs to disown",
  462. .name = "job-id",
  463. .min_values = 0,
  464. .max_values = INT_MAX,
  465. .accept_value = [&](const String& value) -> bool {
  466. // Check if it's a pid (i.e. literal integer)
  467. if (auto number = value.to_uint(); number.has_value()) {
  468. job_ids.append(number.value());
  469. id_is_pid.append(true);
  470. return true;
  471. }
  472. // Check if it's a jobspec
  473. if (auto id = resolve_job_spec(value); id.has_value()) {
  474. job_ids.append(id.value());
  475. id_is_pid.append(false);
  476. return true;
  477. }
  478. return false;
  479. } });
  480. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  481. return 1;
  482. if (job_ids.is_empty()) {
  483. job_ids.append(find_last_job_id());
  484. id_is_pid.append(false);
  485. }
  486. Vector<const Job*> jobs_to_disown;
  487. for (size_t i = 0; i < job_ids.size(); ++i) {
  488. auto id = job_ids[i];
  489. auto is_pid = id_is_pid[i];
  490. auto job = find_job(id, is_pid);
  491. if (!job)
  492. warnln("disown: Job with id/pid {} not found", id);
  493. else
  494. jobs_to_disown.append(job);
  495. }
  496. if (jobs_to_disown.is_empty()) {
  497. if (job_ids.is_empty())
  498. warnln("disown: No current job");
  499. // An error message has already been printed about the nonexistence of each listed job.
  500. return 1;
  501. }
  502. for (auto job : jobs_to_disown) {
  503. job->deactivate();
  504. if (!job->is_running_in_background())
  505. warnln("disown warning: Job {} is currently not running, 'kill -{} {}' to make it continue", job->job_id(), SIGCONT, job->pid());
  506. jobs.remove(job->pid());
  507. }
  508. return 0;
  509. }
  510. int Shell::builtin_history(int, const char**)
  511. {
  512. for (size_t i = 0; i < m_editor->history().size(); ++i) {
  513. printf("%6zu %s\n", i, m_editor->history()[i].entry.characters());
  514. }
  515. return 0;
  516. }
  517. int Shell::builtin_jobs(int argc, const char** argv)
  518. {
  519. bool list = false, show_pid = false;
  520. Core::ArgsParser parser;
  521. parser.add_option(list, "List all information about jobs", "list", 'l');
  522. parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
  523. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  524. return 1;
  525. Job::PrintStatusMode mode = Job::PrintStatusMode::Basic;
  526. if (show_pid)
  527. mode = Job::PrintStatusMode::OnlyPID;
  528. if (list)
  529. mode = Job::PrintStatusMode::ListAll;
  530. for (auto& it : jobs) {
  531. if (!it.value->print_status(mode))
  532. return 1;
  533. }
  534. return 0;
  535. }
  536. int Shell::builtin_popd(int argc, const char** argv)
  537. {
  538. if (directory_stack.size() <= 1) {
  539. warnln("Shell: popd: directory stack empty");
  540. return 1;
  541. }
  542. bool should_not_switch = false;
  543. Core::ArgsParser parser;
  544. parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
  545. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  546. return 1;
  547. auto popped_path = directory_stack.take_last();
  548. if (should_not_switch)
  549. return 0;
  550. auto new_path = LexicalPath::canonicalized_path(popped_path);
  551. if (chdir(new_path.characters()) < 0) {
  552. warnln("chdir({}) failed: {}", new_path, strerror(errno));
  553. return 1;
  554. }
  555. cwd = new_path;
  556. return 0;
  557. }
  558. int Shell::builtin_pushd(int argc, const char** argv)
  559. {
  560. StringBuilder path_builder;
  561. bool should_switch = true;
  562. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  563. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  564. if (argc == 1) {
  565. if (directory_stack.size() < 2) {
  566. warnln("pushd: no other directory");
  567. return 1;
  568. }
  569. String dir1 = directory_stack.take_first();
  570. String dir2 = directory_stack.take_first();
  571. directory_stack.insert(0, dir2);
  572. directory_stack.insert(1, dir1);
  573. int rc = chdir(dir2.characters());
  574. if (rc < 0) {
  575. warnln("chdir({}) failed: {}", dir2, strerror(errno));
  576. return 1;
  577. }
  578. cwd = dir2;
  579. return 0;
  580. }
  581. // Let's assume the user's typed in 'pushd <dir>'
  582. if (argc == 2) {
  583. directory_stack.append(cwd.characters());
  584. if (argv[1][0] == '/') {
  585. path_builder.append(argv[1]);
  586. } else {
  587. path_builder.appendff("{}/{}", cwd, argv[1]);
  588. }
  589. } else if (argc == 3) {
  590. directory_stack.append(cwd.characters());
  591. for (int i = 1; i < argc; i++) {
  592. const char* arg = argv[i];
  593. if (arg[0] != '-') {
  594. if (arg[0] == '/') {
  595. path_builder.append(arg);
  596. } else
  597. path_builder.appendff("{}/{}", cwd, arg);
  598. }
  599. if (!strcmp(arg, "-n"))
  600. should_switch = false;
  601. }
  602. }
  603. auto real_path = LexicalPath::canonicalized_path(path_builder.to_string());
  604. struct stat st;
  605. int rc = stat(real_path.characters(), &st);
  606. if (rc < 0) {
  607. warnln("stat({}) failed: {}", real_path, strerror(errno));
  608. return 1;
  609. }
  610. if (!S_ISDIR(st.st_mode)) {
  611. warnln("Not a directory: {}", real_path);
  612. return 1;
  613. }
  614. if (should_switch) {
  615. int rc = chdir(real_path.characters());
  616. if (rc < 0) {
  617. warnln("chdir({}) failed: {}", real_path, strerror(errno));
  618. return 1;
  619. }
  620. cwd = real_path;
  621. }
  622. return 0;
  623. }
  624. int Shell::builtin_pwd(int, const char**)
  625. {
  626. print_path(cwd);
  627. fputc('\n', stdout);
  628. return 0;
  629. }
  630. int Shell::builtin_setopt(int argc, const char** argv)
  631. {
  632. if (argc == 1) {
  633. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  634. if (options.name) \
  635. warnln("{}", #name);
  636. ENUMERATE_SHELL_OPTIONS();
  637. #undef __ENUMERATE_SHELL_OPTION
  638. }
  639. Core::ArgsParser parser;
  640. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  641. bool name = false; \
  642. bool not_##name = false; \
  643. parser.add_option(name, "Enable: " description, #name, '\0'); \
  644. parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0');
  645. ENUMERATE_SHELL_OPTIONS();
  646. #undef __ENUMERATE_SHELL_OPTION
  647. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  648. return 1;
  649. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  650. if (name) \
  651. options.name = true; \
  652. if (not_##name) \
  653. options.name = false;
  654. ENUMERATE_SHELL_OPTIONS();
  655. #undef __ENUMERATE_SHELL_OPTION
  656. return 0;
  657. }
  658. int Shell::builtin_shift(int argc, const char** argv)
  659. {
  660. int count = 1;
  661. Core::ArgsParser parser;
  662. parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No);
  663. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  664. return 1;
  665. if (count < 1)
  666. return 0;
  667. auto argv_ = lookup_local_variable("ARGV");
  668. if (!argv_) {
  669. warnln("shift: ARGV is unset");
  670. return 1;
  671. }
  672. if (!argv_->is_list())
  673. argv_ = adopt_ref(*new AST::ListValue({ argv_.release_nonnull() }));
  674. auto& values = static_cast<AST::ListValue*>(argv_.ptr())->values();
  675. if ((size_t)count > values.size()) {
  676. warnln("shift: shift count must not be greater than {}", values.size());
  677. return 1;
  678. }
  679. for (auto i = 0; i < count; ++i)
  680. (void)values.take_first();
  681. return 0;
  682. }
  683. int Shell::builtin_source(int argc, const char** argv)
  684. {
  685. const char* file_to_source = nullptr;
  686. Vector<const char*> args;
  687. Core::ArgsParser parser;
  688. parser.add_positional_argument(file_to_source, "File to read commands from", "path");
  689. parser.add_positional_argument(args, "ARGV for the sourced file", "args", Core::ArgsParser::Required::No);
  690. if (!parser.parse(argc, const_cast<char**>(argv)))
  691. return 1;
  692. Vector<String> string_argv;
  693. for (auto& arg : args)
  694. string_argv.append(arg);
  695. auto previous_argv = lookup_local_variable("ARGV");
  696. ScopeGuard guard { [&] {
  697. if (!args.is_empty())
  698. set_local_variable("ARGV", move(previous_argv));
  699. } };
  700. if (!args.is_empty())
  701. set_local_variable("ARGV", AST::make_ref_counted<AST::ListValue>(move(string_argv)));
  702. if (!run_file(file_to_source, true))
  703. return 126;
  704. return 0;
  705. }
  706. int Shell::builtin_time(int argc, const char** argv)
  707. {
  708. Vector<const char*> args;
  709. int number_of_iterations = 1;
  710. Core::ArgsParser parser;
  711. parser.add_option(number_of_iterations, "Number of iterations", "iterations", 'n', "iterations");
  712. parser.set_stop_on_first_non_option(true);
  713. parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  714. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  715. return 1;
  716. if (number_of_iterations < 1)
  717. return 1;
  718. AST::Command command;
  719. for (auto& arg : args)
  720. command.argv.append(arg);
  721. auto commands = expand_aliases({ move(command) });
  722. AK::Statistics iteration_times;
  723. int exit_code = 1;
  724. for (int i = 0; i < number_of_iterations; ++i) {
  725. auto timer = Core::ElapsedTimer::start_new();
  726. for (auto& job : run_commands(commands)) {
  727. block_on_job(job);
  728. exit_code = job.exit_code();
  729. }
  730. iteration_times.add(timer.elapsed());
  731. }
  732. if (number_of_iterations == 1) {
  733. warnln("Time: {} ms", iteration_times.values().first());
  734. } else {
  735. AK::Statistics iteration_times_excluding_first;
  736. for (size_t i = 1; i < iteration_times.size(); i++)
  737. iteration_times_excluding_first.add(iteration_times.values()[i]);
  738. warnln("Timing report:");
  739. warnln("==============");
  740. warnln("Command: {}", String::join(' ', args));
  741. warnln("Average time: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max:{})",
  742. iteration_times.average(), iteration_times.median(),
  743. iteration_times.standard_deviation(),
  744. iteration_times.min(), iteration_times.max());
  745. warnln("Excluding first: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max:{})",
  746. iteration_times_excluding_first.average(), iteration_times_excluding_first.median(),
  747. iteration_times_excluding_first.standard_deviation(),
  748. iteration_times_excluding_first.min(), iteration_times_excluding_first.max());
  749. }
  750. return exit_code;
  751. }
  752. int Shell::builtin_umask(int argc, const char** argv)
  753. {
  754. const char* mask_text = nullptr;
  755. Core::ArgsParser parser;
  756. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  757. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  758. return 1;
  759. if (!mask_text) {
  760. mode_t old_mask = umask(0);
  761. printf("%#o\n", old_mask);
  762. umask(old_mask);
  763. return 0;
  764. }
  765. unsigned mask;
  766. int matches = sscanf(mask_text, "%o", &mask);
  767. if (matches == 1) {
  768. umask(mask);
  769. return 0;
  770. }
  771. warnln("umask: Invalid mask '{}'", mask_text);
  772. return 1;
  773. }
  774. int Shell::builtin_wait(int argc, const char** argv)
  775. {
  776. Vector<int> job_ids;
  777. Vector<bool> id_is_pid;
  778. Core::ArgsParser parser;
  779. parser.add_positional_argument(Core::ArgsParser::Arg {
  780. .help_string = "Job IDs or Jobspecs to wait for",
  781. .name = "job-id",
  782. .min_values = 0,
  783. .max_values = INT_MAX,
  784. .accept_value = [&](const String& value) -> bool {
  785. // Check if it's a pid (i.e. literal integer)
  786. if (auto number = value.to_uint(); number.has_value()) {
  787. job_ids.append(number.value());
  788. id_is_pid.append(true);
  789. return true;
  790. }
  791. // Check if it's a jobspec
  792. if (auto id = resolve_job_spec(value); id.has_value()) {
  793. job_ids.append(id.value());
  794. id_is_pid.append(false);
  795. return true;
  796. }
  797. return false;
  798. } });
  799. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  800. return 1;
  801. Vector<NonnullRefPtr<Job>> jobs_to_wait_for;
  802. for (size_t i = 0; i < job_ids.size(); ++i) {
  803. auto id = job_ids[i];
  804. auto is_pid = id_is_pid[i];
  805. auto job = find_job(id, is_pid);
  806. if (!job)
  807. warnln("wait: Job with id/pid {} not found", id);
  808. else
  809. jobs_to_wait_for.append(*job);
  810. }
  811. if (job_ids.is_empty()) {
  812. for (const auto& it : jobs)
  813. jobs_to_wait_for.append(it.value);
  814. }
  815. for (auto& job : jobs_to_wait_for) {
  816. job->set_running_in_background(false);
  817. block_on_job(job);
  818. }
  819. return 0;
  820. }
  821. int Shell::builtin_unset(int argc, const char** argv)
  822. {
  823. Vector<const char*> vars;
  824. Core::ArgsParser parser;
  825. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  826. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  827. return 1;
  828. for (auto& value : vars) {
  829. if (lookup_local_variable(value)) {
  830. unset_local_variable(value);
  831. } else {
  832. unsetenv(value);
  833. }
  834. }
  835. return 0;
  836. }
  837. int Shell::builtin_not(int argc, const char** argv)
  838. {
  839. // FIXME: Use ArgsParser when it can collect unrelated -arguments too.
  840. if (argc == 1)
  841. return 1;
  842. AST::Command command;
  843. for (size_t i = 1; i < (size_t)argc; ++i)
  844. command.argv.append(argv[i]);
  845. auto commands = expand_aliases({ move(command) });
  846. int exit_code = 1;
  847. auto found_a_job = false;
  848. for (auto& job : run_commands(commands)) {
  849. found_a_job = true;
  850. block_on_job(job);
  851. exit_code = job.exit_code();
  852. }
  853. // In case it was a function.
  854. if (!found_a_job)
  855. exit_code = last_return_code;
  856. return exit_code == 0 ? 1 : 0;
  857. }
  858. int Shell::builtin_kill(int argc, const char** argv)
  859. {
  860. // Simply translate the arguments and pass them to `kill'
  861. Vector<String> replaced_values;
  862. auto kill_path = find_in_path("kill");
  863. if (kill_path.is_empty()) {
  864. warnln("kill: `kill' not found in PATH");
  865. return 126;
  866. }
  867. replaced_values.append(kill_path);
  868. for (auto i = 1; i < argc; ++i) {
  869. if (auto job_id = resolve_job_spec(argv[i]); job_id.has_value()) {
  870. auto job = find_job(job_id.value());
  871. if (job) {
  872. replaced_values.append(String::number(job->pid()));
  873. } else {
  874. warnln("kill: Job with pid {} not found", job_id.value());
  875. return 1;
  876. }
  877. } else {
  878. replaced_values.append(argv[i]);
  879. }
  880. }
  881. // Now just run `kill'
  882. AST::Command command;
  883. command.argv = move(replaced_values);
  884. command.position = m_source_position.has_value() ? m_source_position->position : Optional<AST::Position> {};
  885. auto exit_code = 1;
  886. auto job_result = run_command(command);
  887. if (job_result.is_error()) {
  888. warnln("kill: Failed to run {}: {}", command.argv.first(), job_result.error());
  889. return exit_code;
  890. }
  891. if (auto job = job_result.release_value()) {
  892. block_on_job(job);
  893. exit_code = job->exit_code();
  894. }
  895. return exit_code;
  896. }
  897. bool Shell::run_builtin(const AST::Command& command, const NonnullRefPtrVector<AST::Rewiring>& rewirings, int& retval)
  898. {
  899. if (command.argv.is_empty())
  900. return false;
  901. if (!has_builtin(command.argv.first()))
  902. return false;
  903. Vector<const char*> argv;
  904. for (auto& arg : command.argv)
  905. argv.append(arg.characters());
  906. argv.append(nullptr);
  907. StringView name = command.argv.first();
  908. SavedFileDescriptors fds { rewirings };
  909. for (auto& rewiring : rewirings) {
  910. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  911. if (rc < 0) {
  912. perror("dup2(run)");
  913. return false;
  914. }
  915. }
  916. Core::EventLoop loop;
  917. setup_signals();
  918. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  919. if (name == #builtin) { \
  920. retval = builtin_##builtin(argv.size() - 1, argv.data()); \
  921. if (!has_error(ShellError::None)) \
  922. raise_error(m_error, m_error_description, command.position); \
  923. fflush(stdout); \
  924. fflush(stderr); \
  925. return true; \
  926. }
  927. ENUMERATE_SHELL_BUILTINS();
  928. #undef __ENUMERATE_SHELL_BUILTIN
  929. return false;
  930. }
  931. bool Shell::has_builtin(StringView name) const
  932. {
  933. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  934. if (name == #builtin) { \
  935. return true; \
  936. }
  937. ENUMERATE_SHELL_BUILTINS();
  938. #undef __ENUMERATE_SHELL_BUILTIN
  939. return false;
  940. }
  941. }