Builtin.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. const char* real_path = lexical_path.string().characters();
  525. struct stat st;
  526. int rc = stat(real_path, &st);
  527. if (rc < 0) {
  528. warnln("stat({}) failed: {}", real_path, strerror(errno));
  529. return 1;
  530. }
  531. if (!S_ISDIR(st.st_mode)) {
  532. warnln("Not a directory: {}", real_path);
  533. return 1;
  534. }
  535. if (should_switch) {
  536. int rc = chdir(real_path);
  537. if (rc < 0) {
  538. warnln("chdir({}) failed: {}", real_path, strerror(errno));
  539. return 1;
  540. }
  541. cwd = lexical_path.string();
  542. }
  543. return 0;
  544. }
  545. int Shell::builtin_pushd(int argc, const char** argv)
  546. {
  547. StringBuilder path_builder;
  548. bool should_switch = true;
  549. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  550. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  551. if (argc == 1) {
  552. if (directory_stack.size() < 2) {
  553. warnln("pushd: no other directory");
  554. return 1;
  555. }
  556. String dir1 = directory_stack.take_first();
  557. String dir2 = directory_stack.take_first();
  558. directory_stack.insert(0, dir2);
  559. directory_stack.insert(1, dir1);
  560. int rc = chdir(dir2.characters());
  561. if (rc < 0) {
  562. warnln("chdir({}) failed: {}", dir2, strerror(errno));
  563. return 1;
  564. }
  565. cwd = dir2;
  566. return 0;
  567. }
  568. // Let's assume the user's typed in 'pushd <dir>'
  569. if (argc == 2) {
  570. directory_stack.append(cwd.characters());
  571. if (argv[1][0] == '/') {
  572. path_builder.append(argv[1]);
  573. } else {
  574. path_builder.appendff("{}/{}", cwd, argv[1]);
  575. }
  576. } else if (argc == 3) {
  577. directory_stack.append(cwd.characters());
  578. for (int i = 1; i < argc; i++) {
  579. const char* arg = argv[i];
  580. if (arg[0] != '-') {
  581. if (arg[0] == '/') {
  582. path_builder.append(arg);
  583. } else
  584. path_builder.appendff("{}/{}", cwd, arg);
  585. }
  586. if (!strcmp(arg, "-n"))
  587. should_switch = false;
  588. }
  589. }
  590. auto real_path = LexicalPath::canonicalized_path(path_builder.to_string());
  591. struct stat st;
  592. int rc = stat(real_path.characters(), &st);
  593. if (rc < 0) {
  594. warnln("stat({}) failed: {}", real_path, strerror(errno));
  595. return 1;
  596. }
  597. if (!S_ISDIR(st.st_mode)) {
  598. warnln("Not a directory: {}", real_path);
  599. return 1;
  600. }
  601. if (should_switch) {
  602. int rc = chdir(real_path.characters());
  603. if (rc < 0) {
  604. warnln("chdir({}) failed: {}", real_path, strerror(errno));
  605. return 1;
  606. }
  607. cwd = real_path;
  608. }
  609. return 0;
  610. }
  611. int Shell::builtin_pwd(int, const char**)
  612. {
  613. print_path(cwd);
  614. fputc('\n', stdout);
  615. return 0;
  616. }
  617. int Shell::builtin_setopt(int argc, const char** argv)
  618. {
  619. if (argc == 1) {
  620. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  621. if (options.name) \
  622. warnln("{}", #name);
  623. ENUMERATE_SHELL_OPTIONS();
  624. #undef __ENUMERATE_SHELL_OPTION
  625. }
  626. Core::ArgsParser parser;
  627. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  628. bool name = false; \
  629. bool not_##name = false; \
  630. parser.add_option(name, "Enable: " description, #name, '\0'); \
  631. parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0');
  632. ENUMERATE_SHELL_OPTIONS();
  633. #undef __ENUMERATE_SHELL_OPTION
  634. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  635. return 1;
  636. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  637. if (name) \
  638. options.name = true; \
  639. if (not_##name) \
  640. options.name = false;
  641. ENUMERATE_SHELL_OPTIONS();
  642. #undef __ENUMERATE_SHELL_OPTION
  643. return 0;
  644. }
  645. int Shell::builtin_shift(int argc, const char** argv)
  646. {
  647. int count = 1;
  648. Core::ArgsParser parser;
  649. parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No);
  650. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  651. return 1;
  652. if (count < 1)
  653. return 0;
  654. auto argv_ = lookup_local_variable("ARGV");
  655. if (!argv_) {
  656. warnln("shift: ARGV is unset");
  657. return 1;
  658. }
  659. if (!argv_->is_list())
  660. argv_ = adopt_ref(*new AST::ListValue({ argv_.release_nonnull() }));
  661. auto& values = static_cast<AST::ListValue*>(argv_.ptr())->values();
  662. if ((size_t)count > values.size()) {
  663. warnln("shift: shift count must not be greater than {}", values.size());
  664. return 1;
  665. }
  666. for (auto i = 0; i < count; ++i)
  667. values.take_first();
  668. return 0;
  669. }
  670. int Shell::builtin_source(int argc, const char** argv)
  671. {
  672. const char* file_to_source = nullptr;
  673. Vector<const char*> args;
  674. Core::ArgsParser parser;
  675. parser.add_positional_argument(file_to_source, "File to read commands from", "path");
  676. parser.add_positional_argument(args, "ARGV for the sourced file", "args", Core::ArgsParser::Required::No);
  677. if (!parser.parse(argc, const_cast<char**>(argv)))
  678. return 1;
  679. Vector<String> string_argv;
  680. for (auto& arg : args)
  681. string_argv.append(arg);
  682. auto previous_argv = lookup_local_variable("ARGV");
  683. ScopeGuard guard { [&] {
  684. if (!args.is_empty())
  685. set_local_variable("ARGV", move(previous_argv));
  686. } };
  687. if (!args.is_empty())
  688. set_local_variable("ARGV", AST::create<AST::ListValue>(move(string_argv)));
  689. if (!run_file(file_to_source, true))
  690. return 126;
  691. return 0;
  692. }
  693. int Shell::builtin_time(int argc, const char** argv)
  694. {
  695. Vector<const char*> args;
  696. Core::ArgsParser parser;
  697. parser.set_stop_on_first_non_option(true);
  698. parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  699. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  700. return 1;
  701. AST::Command command;
  702. for (auto& arg : args)
  703. command.argv.append(arg);
  704. auto commands = expand_aliases({ move(command) });
  705. Core::ElapsedTimer timer;
  706. int exit_code = 1;
  707. timer.start();
  708. for (auto& job : run_commands(commands)) {
  709. block_on_job(job);
  710. exit_code = job.exit_code();
  711. }
  712. warnln("Time: {} ms", timer.elapsed());
  713. return exit_code;
  714. }
  715. int Shell::builtin_umask(int argc, const char** argv)
  716. {
  717. const char* mask_text = nullptr;
  718. Core::ArgsParser parser;
  719. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  720. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  721. return 1;
  722. if (!mask_text) {
  723. mode_t old_mask = umask(0);
  724. printf("%#o\n", old_mask);
  725. umask(old_mask);
  726. return 0;
  727. }
  728. unsigned mask;
  729. int matches = sscanf(mask_text, "%o", &mask);
  730. if (matches == 1) {
  731. umask(mask);
  732. return 0;
  733. }
  734. warnln("umask: Invalid mask '{}'", mask_text);
  735. return 1;
  736. }
  737. int Shell::builtin_wait(int argc, const char** argv)
  738. {
  739. Vector<int> job_ids;
  740. Vector<bool> id_is_pid;
  741. Core::ArgsParser parser;
  742. parser.add_positional_argument(Core::ArgsParser::Arg {
  743. .help_string = "Job IDs or Jobspecs to wait for",
  744. .name = "job-id",
  745. .min_values = 0,
  746. .max_values = INT_MAX,
  747. .accept_value = [&](const String& value) -> bool {
  748. // Check if it's a pid (i.e. literal integer)
  749. if (auto number = value.to_uint(); number.has_value()) {
  750. job_ids.append(number.value());
  751. id_is_pid.append(true);
  752. return true;
  753. }
  754. // Check if it's a jobspec
  755. if (auto id = resolve_job_spec(value); id.has_value()) {
  756. job_ids.append(id.value());
  757. id_is_pid.append(false);
  758. return true;
  759. }
  760. return false;
  761. } });
  762. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  763. return 1;
  764. Vector<NonnullRefPtr<Job>> jobs_to_wait_for;
  765. for (size_t i = 0; i < job_ids.size(); ++i) {
  766. auto id = job_ids[i];
  767. auto is_pid = id_is_pid[i];
  768. auto job = find_job(id, is_pid);
  769. if (!job)
  770. warnln("wait: Job with id/pid {} not found", id);
  771. else
  772. jobs_to_wait_for.append(*job);
  773. }
  774. if (job_ids.is_empty()) {
  775. for (const auto& it : jobs)
  776. jobs_to_wait_for.append(it.value);
  777. }
  778. for (auto& job : jobs_to_wait_for) {
  779. job->set_running_in_background(false);
  780. block_on_job(job);
  781. }
  782. return 0;
  783. }
  784. int Shell::builtin_unset(int argc, const char** argv)
  785. {
  786. Vector<const char*> vars;
  787. Core::ArgsParser parser;
  788. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  789. if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
  790. return 1;
  791. for (auto& value : vars) {
  792. if (lookup_local_variable(value)) {
  793. unset_local_variable(value);
  794. } else {
  795. unsetenv(value);
  796. }
  797. }
  798. return 0;
  799. }
  800. int Shell::builtin_not(int argc, const char** argv)
  801. {
  802. // FIXME: Use ArgsParser when it can collect unrelated -arguments too.
  803. if (argc == 1)
  804. return 1;
  805. AST::Command command;
  806. for (size_t i = 1; i < (size_t)argc; ++i)
  807. command.argv.append(argv[i]);
  808. auto commands = expand_aliases({ move(command) });
  809. int exit_code = 1;
  810. auto found_a_job = false;
  811. for (auto& job : run_commands(commands)) {
  812. found_a_job = true;
  813. block_on_job(job);
  814. exit_code = job.exit_code();
  815. }
  816. // In case it was a function.
  817. if (!found_a_job)
  818. exit_code = last_return_code;
  819. return exit_code == 0 ? 1 : 0;
  820. }
  821. int Shell::builtin_kill(int argc, const char** argv)
  822. {
  823. // Simply translate the arguments and pass them to `kill'
  824. Vector<String> replaced_values;
  825. auto kill_path = find_in_path("kill");
  826. if (kill_path.is_empty()) {
  827. warnln("kill: `kill' not found in PATH");
  828. return 126;
  829. }
  830. replaced_values.append(kill_path);
  831. for (auto i = 1; i < argc; ++i) {
  832. if (auto job_id = resolve_job_spec(argv[i]); job_id.has_value()) {
  833. auto job = find_job(job_id.value());
  834. if (job) {
  835. replaced_values.append(String::number(job->pid()));
  836. } else {
  837. warnln("kill: Job with pid {} not found", job_id.value());
  838. return 1;
  839. }
  840. } else {
  841. replaced_values.append(argv[i]);
  842. }
  843. }
  844. // Now just run `kill'
  845. AST::Command command;
  846. command.argv = move(replaced_values);
  847. command.position = m_source_position.has_value() ? m_source_position->position : Optional<AST::Position> {};
  848. auto exit_code = 1;
  849. if (auto job = run_command(command)) {
  850. block_on_job(job);
  851. exit_code = job->exit_code();
  852. }
  853. return exit_code;
  854. }
  855. bool Shell::run_builtin(const AST::Command& command, const NonnullRefPtrVector<AST::Rewiring>& rewirings, int& retval)
  856. {
  857. if (command.argv.is_empty())
  858. return false;
  859. if (!has_builtin(command.argv.first()))
  860. return false;
  861. Vector<const char*> argv;
  862. for (auto& arg : command.argv)
  863. argv.append(arg.characters());
  864. argv.append(nullptr);
  865. StringView name = command.argv.first();
  866. SavedFileDescriptors fds { rewirings };
  867. for (auto& rewiring : rewirings) {
  868. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  869. if (rc < 0) {
  870. perror("dup2(run)");
  871. return false;
  872. }
  873. }
  874. Core::EventLoop loop;
  875. setup_signals();
  876. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  877. if (name == #builtin) { \
  878. retval = builtin_##builtin(argv.size() - 1, argv.data()); \
  879. if (!has_error(ShellError::None)) \
  880. raise_error(m_error, m_error_description, command.position); \
  881. fflush(stdout); \
  882. fflush(stderr); \
  883. return true; \
  884. }
  885. ENUMERATE_SHELL_BUILTINS();
  886. #undef __ENUMERATE_SHELL_BUILTIN
  887. return false;
  888. }
  889. bool Shell::has_builtin(const StringView& name) const
  890. {
  891. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  892. if (name == #builtin) { \
  893. return true; \
  894. }
  895. ENUMERATE_SHELL_BUILTINS();
  896. #undef __ENUMERATE_SHELL_BUILTIN
  897. return false;
  898. }
  899. }