Builtin.cpp 32 KB

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