Builtin.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. /*
  2. * Copyright (c) 2020, The SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Shell.h"
  27. #include <AK/LexicalPath.h>
  28. #include <LibCore/ArgsParser.h>
  29. #include <LibCore/EventLoop.h>
  30. #include <LibCore/File.h>
  31. #include <inttypes.h>
  32. #include <signal.h>
  33. #include <sys/wait.h>
  34. #include <unistd.h>
  35. extern char** environ;
  36. namespace Shell {
  37. int Shell::builtin_alias(int argc, const char** argv)
  38. {
  39. Vector<const char*> arguments;
  40. Core::ArgsParser parser;
  41. parser.add_positional_argument(arguments, "List of name[=values]'s", "name[=value]", Core::ArgsParser::Required::No);
  42. if (!parser.parse(argc, const_cast<char**>(argv), false))
  43. return 1;
  44. if (arguments.is_empty()) {
  45. for (auto& alias : m_aliases)
  46. printf("%s=%s\n", escape_token(alias.key).characters(), escape_token(alias.value).characters());
  47. return 0;
  48. }
  49. bool fail = false;
  50. for (auto& argument : arguments) {
  51. auto parts = String { argument }.split_limit('=', 2, true);
  52. if (parts.size() == 1) {
  53. auto alias = m_aliases.get(parts[0]);
  54. if (alias.has_value()) {
  55. printf("%s=%s\n", escape_token(parts[0]).characters(), escape_token(alias.value()).characters());
  56. } else {
  57. fail = true;
  58. }
  59. } else {
  60. m_aliases.set(parts[0], parts[1]);
  61. add_entry_to_cache(parts[0]);
  62. }
  63. }
  64. return fail ? 1 : 0;
  65. }
  66. int Shell::builtin_bg(int argc, const char** argv)
  67. {
  68. int job_id = -1;
  69. Core::ArgsParser parser;
  70. parser.add_positional_argument(job_id, "Job ID to run in background", "job-id", Core::ArgsParser::Required::No);
  71. if (!parser.parse(argc, const_cast<char**>(argv), false))
  72. return 1;
  73. if (job_id == -1 && !jobs.is_empty())
  74. job_id = find_last_job_id();
  75. auto* job = const_cast<Job*>(find_job(job_id));
  76. if (!job) {
  77. if (job_id == -1) {
  78. fprintf(stderr, "bg: no current job\n");
  79. } else {
  80. fprintf(stderr, "bg: job with id %d not found\n", job_id);
  81. }
  82. return 1;
  83. }
  84. job->set_running_in_background(true);
  85. job->set_is_suspended(false);
  86. dbgln("Resuming {} ({})", job->pid(), job->cmd());
  87. warnln("Resuming job {} - {}", job->job_id(), job->cmd().characters());
  88. // Try using the PGID, but if that fails, just use the PID.
  89. if (killpg(job->pgid(), SIGCONT) < 0) {
  90. if (kill(job->pid(), SIGCONT) < 0) {
  91. perror("kill");
  92. return 1;
  93. }
  94. }
  95. return 0;
  96. }
  97. int Shell::builtin_cd(int argc, const char** argv)
  98. {
  99. const char* arg_path = nullptr;
  100. Core::ArgsParser parser;
  101. parser.add_positional_argument(arg_path, "Path to change to", "path", Core::ArgsParser::Required::No);
  102. if (!parser.parse(argc, const_cast<char**>(argv), false))
  103. return 1;
  104. String new_path;
  105. if (!arg_path) {
  106. new_path = home;
  107. } else {
  108. if (strcmp(arg_path, "-") == 0) {
  109. char* oldpwd = getenv("OLDPWD");
  110. if (oldpwd == nullptr)
  111. return 1;
  112. new_path = oldpwd;
  113. } else if (arg_path[0] == '/') {
  114. new_path = argv[1];
  115. } else {
  116. StringBuilder builder;
  117. builder.append(cwd);
  118. builder.append('/');
  119. builder.append(arg_path);
  120. new_path = builder.to_string();
  121. }
  122. }
  123. auto real_path = Core::File::real_path_for(new_path);
  124. if (real_path.is_empty()) {
  125. fprintf(stderr, "Invalid path '%s'\n", new_path.characters());
  126. return 1;
  127. }
  128. if (cd_history.is_empty() || cd_history.last() != real_path)
  129. cd_history.enqueue(real_path);
  130. const char* path = real_path.characters();
  131. int rc = chdir(path);
  132. if (rc < 0) {
  133. if (errno == ENOTDIR) {
  134. fprintf(stderr, "Not a directory: %s\n", path);
  135. } else {
  136. fprintf(stderr, "chdir(%s) failed: %s\n", path, strerror(errno));
  137. }
  138. return 1;
  139. }
  140. setenv("OLDPWD", cwd.characters(), 1);
  141. cwd = real_path;
  142. setenv("PWD", cwd.characters(), 1);
  143. return 0;
  144. }
  145. int Shell::builtin_cdh(int argc, const char** argv)
  146. {
  147. int index = -1;
  148. Core::ArgsParser parser;
  149. parser.add_positional_argument(index, "Index of the cd history entry (leave out for a list)", "index", Core::ArgsParser::Required::No);
  150. if (!parser.parse(argc, const_cast<char**>(argv), false))
  151. return 1;
  152. if (index == -1) {
  153. if (cd_history.is_empty()) {
  154. fprintf(stderr, "cdh: no history available\n");
  155. return 0;
  156. }
  157. for (ssize_t i = cd_history.size() - 1; i >= 0; --i)
  158. printf("%lu: %s\n", cd_history.size() - i, cd_history.at(i).characters());
  159. return 0;
  160. }
  161. if (index < 1 || (size_t)index > cd_history.size()) {
  162. fprintf(stderr, "cdh: history index out of bounds: %d not in (0, %zu)\n", index, cd_history.size());
  163. return 1;
  164. }
  165. const char* path = cd_history.at(cd_history.size() - index).characters();
  166. const char* cd_args[] = { "cd", path, nullptr };
  167. return Shell::builtin_cd(2, cd_args);
  168. }
  169. int Shell::builtin_dirs(int argc, const char** argv)
  170. {
  171. // The first directory in the stack is ALWAYS the current directory
  172. directory_stack.at(0) = cwd.characters();
  173. bool clear = false;
  174. bool print = false;
  175. bool number_when_printing = false;
  176. char separator = ' ';
  177. Vector<const char*> paths;
  178. Core::ArgsParser parser;
  179. parser.add_option(clear, "Clear the directory stack", "clear", 'c');
  180. parser.add_option(print, "Print directory entries one per line", "print", 'p');
  181. parser.add_option(number_when_printing, "Number the directories in the stack when printing", "number", 'v');
  182. parser.add_positional_argument(paths, "Extra paths to put on the stack", "path", Core::ArgsParser::Required::No);
  183. if (!parser.parse(argc, const_cast<char**>(argv), false))
  184. return 1;
  185. // -v implies -p
  186. print = print || number_when_printing;
  187. if (print) {
  188. if (!paths.is_empty()) {
  189. fprintf(stderr, "dirs: 'print' and 'number' are not allowed when any path is specified");
  190. return 1;
  191. }
  192. separator = '\n';
  193. }
  194. if (clear) {
  195. for (size_t i = 1; i < directory_stack.size(); i++)
  196. directory_stack.remove(i);
  197. }
  198. for (auto& path : paths)
  199. directory_stack.append(path);
  200. if (print || (!clear && paths.is_empty())) {
  201. int index = 0;
  202. for (auto& directory : directory_stack) {
  203. if (number_when_printing)
  204. printf("%d ", index++);
  205. print_path(directory);
  206. fputc(separator, stdout);
  207. }
  208. }
  209. return 0;
  210. }
  211. int Shell::builtin_exit(int argc, const char** argv)
  212. {
  213. int exit_code = 0;
  214. Core::ArgsParser parser;
  215. parser.add_positional_argument(exit_code, "Exit code", "code", Core::ArgsParser::Required::No);
  216. if (!parser.parse(argc, const_cast<char**>(argv)))
  217. return 1;
  218. if (m_is_interactive) {
  219. if (!jobs.is_empty()) {
  220. if (!m_should_ignore_jobs_on_next_exit) {
  221. fprintf(stderr, "Shell: You have %zu active job%s, run 'exit' again to really exit.\n", jobs.size(), jobs.size() > 1 ? "s" : "");
  222. m_should_ignore_jobs_on_next_exit = true;
  223. return 1;
  224. }
  225. }
  226. }
  227. stop_all_jobs();
  228. m_editor->save_history(get_history_path());
  229. if (m_is_interactive)
  230. printf("Good-bye!\n");
  231. exit(exit_code);
  232. return 0;
  233. }
  234. int Shell::builtin_export(int argc, const char** argv)
  235. {
  236. Vector<const char*> vars;
  237. Core::ArgsParser parser;
  238. parser.add_positional_argument(vars, "List of variable[=value]'s", "values", Core::ArgsParser::Required::No);
  239. if (!parser.parse(argc, const_cast<char**>(argv), false))
  240. return 1;
  241. if (vars.is_empty()) {
  242. for (size_t i = 0; environ[i]; ++i)
  243. puts(environ[i]);
  244. return 0;
  245. }
  246. for (auto& value : vars) {
  247. auto parts = String { value }.split_limit('=', 2);
  248. if (parts.size() == 1) {
  249. auto value = lookup_local_variable(parts[0]);
  250. if (value) {
  251. auto values = value->resolve_as_list(*this);
  252. StringBuilder builder;
  253. builder.join(" ", values);
  254. parts.append(builder.to_string());
  255. } else {
  256. // Ignore the export.
  257. continue;
  258. }
  259. }
  260. int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1);
  261. if (setenv_return != 0) {
  262. perror("setenv");
  263. return 1;
  264. }
  265. if (parts[0] == "PATH")
  266. cache_path();
  267. }
  268. return 0;
  269. }
  270. int Shell::builtin_fg(int argc, const char** argv)
  271. {
  272. int job_id = -1;
  273. Core::ArgsParser parser;
  274. parser.add_positional_argument(job_id, "Job ID to bring to foreground", "job-id", Core::ArgsParser::Required::No);
  275. if (!parser.parse(argc, const_cast<char**>(argv), false))
  276. return 1;
  277. if (job_id == -1 && !jobs.is_empty())
  278. job_id = find_last_job_id();
  279. RefPtr<Job> job = find_job(job_id);
  280. if (!job) {
  281. if (job_id == -1) {
  282. fprintf(stderr, "fg: no current job\n");
  283. } else {
  284. fprintf(stderr, "fg: job with id %d not found\n", job_id);
  285. }
  286. return 1;
  287. }
  288. job->set_running_in_background(false);
  289. job->set_is_suspended(false);
  290. dbgln("Resuming {} ({})", job->pid(), job->cmd());
  291. warnln("Resuming job {} - {}", job->job_id(), job->cmd().characters());
  292. tcsetpgrp(STDOUT_FILENO, job->pgid());
  293. tcsetpgrp(STDIN_FILENO, job->pgid());
  294. // Try using the PGID, but if that fails, just use the PID.
  295. if (killpg(job->pgid(), SIGCONT) < 0) {
  296. if (kill(job->pid(), SIGCONT) < 0) {
  297. perror("kill");
  298. return 1;
  299. }
  300. }
  301. block_on_job(job);
  302. if (job->exited())
  303. return job->exit_code();
  304. else
  305. return 0;
  306. }
  307. int Shell::builtin_disown(int argc, const char** argv)
  308. {
  309. Vector<const char*> str_job_ids;
  310. Core::ArgsParser parser;
  311. parser.add_positional_argument(str_job_ids, "Id of the jobs to disown (omit for current job)", "job_ids", Core::ArgsParser::Required::No);
  312. if (!parser.parse(argc, const_cast<char**>(argv), false))
  313. return 1;
  314. Vector<size_t> job_ids;
  315. for (auto& job_id : str_job_ids) {
  316. auto id = StringView(job_id).to_uint();
  317. if (id.has_value())
  318. job_ids.append(id.value());
  319. else
  320. fprintf(stderr, "disown: Invalid job id %s\n", job_id);
  321. }
  322. if (job_ids.is_empty())
  323. job_ids.append(find_last_job_id());
  324. Vector<const Job*> jobs_to_disown;
  325. for (auto id : job_ids) {
  326. auto job = find_job(id);
  327. if (!job)
  328. fprintf(stderr, "disown: job with id %zu not found\n", id);
  329. else
  330. jobs_to_disown.append(job);
  331. }
  332. if (jobs_to_disown.is_empty()) {
  333. if (str_job_ids.is_empty())
  334. fprintf(stderr, "disown: no current job\n");
  335. // An error message has already been printed about the nonexistence of each listed job.
  336. return 1;
  337. }
  338. for (auto job : jobs_to_disown) {
  339. job->deactivate();
  340. if (!job->is_running_in_background())
  341. fprintf(stderr, "disown warning: job %" PRIu64 " is currently not running, 'kill -%d %d' to make it continue\n", job->job_id(), SIGCONT, job->pid());
  342. jobs.remove(job->pid());
  343. }
  344. return 0;
  345. }
  346. int Shell::builtin_history(int, const char**)
  347. {
  348. for (size_t i = 0; i < m_editor->history().size(); ++i) {
  349. printf("%6zu %s\n", i, m_editor->history()[i].characters());
  350. }
  351. return 0;
  352. }
  353. int Shell::builtin_jobs(int argc, const char** argv)
  354. {
  355. bool list = false, show_pid = false;
  356. Core::ArgsParser parser;
  357. parser.add_option(list, "List all information about jobs", "list", 'l');
  358. parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
  359. if (!parser.parse(argc, const_cast<char**>(argv), false))
  360. return 1;
  361. Job::PrintStatusMode mode = Job::PrintStatusMode::Basic;
  362. if (show_pid)
  363. mode = Job::PrintStatusMode::OnlyPID;
  364. if (list)
  365. mode = Job::PrintStatusMode::ListAll;
  366. for (auto& it : jobs) {
  367. if (!it.value->print_status(mode))
  368. return 1;
  369. }
  370. return 0;
  371. }
  372. int Shell::builtin_popd(int argc, const char** argv)
  373. {
  374. if (directory_stack.size() <= 1) {
  375. fprintf(stderr, "Shell: popd: directory stack empty\n");
  376. return 1;
  377. }
  378. bool should_not_switch = false;
  379. String path = directory_stack.take_last();
  380. Core::ArgsParser parser;
  381. parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
  382. if (!parser.parse(argc, const_cast<char**>(argv), false))
  383. return 1;
  384. bool should_switch = !should_not_switch;
  385. // When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory.
  386. if (argc == 1) {
  387. int rc = chdir(path.characters());
  388. if (rc < 0) {
  389. fprintf(stderr, "chdir(%s) failed: %s\n", path.characters(), strerror(errno));
  390. return 1;
  391. }
  392. cwd = path;
  393. return 0;
  394. }
  395. LexicalPath lexical_path(path.characters());
  396. if (!lexical_path.is_valid()) {
  397. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path.characters());
  398. return 1;
  399. }
  400. const char* real_path = lexical_path.string().characters();
  401. struct stat st;
  402. int rc = stat(real_path, &st);
  403. if (rc < 0) {
  404. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  405. return 1;
  406. }
  407. if (!S_ISDIR(st.st_mode)) {
  408. fprintf(stderr, "Not a directory: %s\n", real_path);
  409. return 1;
  410. }
  411. if (should_switch) {
  412. int rc = chdir(real_path);
  413. if (rc < 0) {
  414. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  415. return 1;
  416. }
  417. cwd = lexical_path.string();
  418. }
  419. return 0;
  420. }
  421. int Shell::builtin_pushd(int argc, const char** argv)
  422. {
  423. StringBuilder path_builder;
  424. bool should_switch = true;
  425. // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
  426. // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
  427. if (argc == 1) {
  428. if (directory_stack.size() < 2) {
  429. fprintf(stderr, "pushd: no other directory\n");
  430. return 1;
  431. }
  432. String dir1 = directory_stack.take_first();
  433. String dir2 = directory_stack.take_first();
  434. directory_stack.insert(0, dir2);
  435. directory_stack.insert(1, dir1);
  436. int rc = chdir(dir2.characters());
  437. if (rc < 0) {
  438. fprintf(stderr, "chdir(%s) failed: %s\n", dir2.characters(), strerror(errno));
  439. return 1;
  440. }
  441. cwd = dir2;
  442. return 0;
  443. }
  444. // Let's assume the user's typed in 'pushd <dir>'
  445. if (argc == 2) {
  446. directory_stack.append(cwd.characters());
  447. if (argv[1][0] == '/') {
  448. path_builder.append(argv[1]);
  449. } else {
  450. path_builder.appendf("%s/%s", cwd.characters(), argv[1]);
  451. }
  452. } else if (argc == 3) {
  453. directory_stack.append(cwd.characters());
  454. for (int i = 1; i < argc; i++) {
  455. const char* arg = argv[i];
  456. if (arg[0] != '-') {
  457. if (arg[0] == '/') {
  458. path_builder.append(arg);
  459. } else
  460. path_builder.appendf("%s/%s", cwd.characters(), arg);
  461. }
  462. if (!strcmp(arg, "-n"))
  463. should_switch = false;
  464. }
  465. }
  466. LexicalPath lexical_path(path_builder.to_string());
  467. if (!lexical_path.is_valid()) {
  468. fprintf(stderr, "LexicalPath failed to canonicalize '%s'\n", path_builder.to_string().characters());
  469. return 1;
  470. }
  471. const char* real_path = lexical_path.string().characters();
  472. struct stat st;
  473. int rc = stat(real_path, &st);
  474. if (rc < 0) {
  475. fprintf(stderr, "stat(%s) failed: %s\n", real_path, strerror(errno));
  476. return 1;
  477. }
  478. if (!S_ISDIR(st.st_mode)) {
  479. fprintf(stderr, "Not a directory: %s\n", real_path);
  480. return 1;
  481. }
  482. if (should_switch) {
  483. int rc = chdir(real_path);
  484. if (rc < 0) {
  485. fprintf(stderr, "chdir(%s) failed: %s\n", real_path, strerror(errno));
  486. return 1;
  487. }
  488. cwd = lexical_path.string();
  489. }
  490. return 0;
  491. }
  492. int Shell::builtin_pwd(int, const char**)
  493. {
  494. print_path(cwd);
  495. fputc('\n', stdout);
  496. return 0;
  497. }
  498. int Shell::builtin_setopt(int argc, const char** argv)
  499. {
  500. if (argc == 1) {
  501. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  502. if (options.name) \
  503. fprintf(stderr, #name "\n");
  504. ENUMERATE_SHELL_OPTIONS();
  505. #undef __ENUMERATE_SHELL_OPTION
  506. }
  507. Core::ArgsParser parser;
  508. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  509. bool name = false; \
  510. bool not_##name = false; \
  511. parser.add_option(name, "Enable: " description, #name, '\0'); \
  512. parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0');
  513. ENUMERATE_SHELL_OPTIONS();
  514. #undef __ENUMERATE_SHELL_OPTION
  515. if (!parser.parse(argc, const_cast<char**>(argv), false))
  516. return 1;
  517. #define __ENUMERATE_SHELL_OPTION(name, default_, description) \
  518. if (name) \
  519. options.name = true; \
  520. if (not_##name) \
  521. options.name = false;
  522. ENUMERATE_SHELL_OPTIONS();
  523. #undef __ENUMERATE_SHELL_OPTION
  524. return 0;
  525. }
  526. int Shell::builtin_shift(int argc, const char** argv)
  527. {
  528. int count = 1;
  529. Core::ArgsParser parser;
  530. parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No);
  531. if (!parser.parse(argc, const_cast<char**>(argv), false))
  532. return 1;
  533. if (count < 1)
  534. return 0;
  535. auto argv_ = lookup_local_variable("ARGV");
  536. if (!argv_) {
  537. fprintf(stderr, "shift: ARGV is unset\n");
  538. return 1;
  539. }
  540. if (!argv_->is_list())
  541. argv_ = adopt(*new AST::ListValue({ argv_.release_nonnull() }));
  542. auto& values = static_cast<AST::ListValue*>(argv_.ptr())->values();
  543. if ((size_t)count > values.size()) {
  544. fprintf(stderr, "shift: shift count must not be greater than %zu\n", values.size());
  545. return 1;
  546. }
  547. for (auto i = 0; i < count; ++i)
  548. values.take_first();
  549. return 0;
  550. }
  551. int Shell::builtin_time(int argc, const char** argv)
  552. {
  553. Vector<const char*> args;
  554. Core::ArgsParser parser;
  555. parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
  556. if (!parser.parse(argc, const_cast<char**>(argv), false))
  557. return 1;
  558. AST::Command command;
  559. for (auto& arg : args)
  560. command.argv.append(arg);
  561. auto commands = expand_aliases({ move(command) });
  562. Core::ElapsedTimer timer;
  563. int exit_code = 1;
  564. timer.start();
  565. for (auto& job : run_commands(commands)) {
  566. block_on_job(job);
  567. exit_code = job.exit_code();
  568. }
  569. fprintf(stderr, "Time: %d ms\n", timer.elapsed());
  570. return exit_code;
  571. }
  572. int Shell::builtin_umask(int argc, const char** argv)
  573. {
  574. const char* mask_text = nullptr;
  575. Core::ArgsParser parser;
  576. parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
  577. if (!parser.parse(argc, const_cast<char**>(argv), false))
  578. return 1;
  579. if (!mask_text) {
  580. mode_t old_mask = umask(0);
  581. printf("%#o\n", old_mask);
  582. umask(old_mask);
  583. return 0;
  584. }
  585. unsigned mask;
  586. int matches = sscanf(mask_text, "%o", &mask);
  587. if (matches == 1) {
  588. umask(mask);
  589. return 0;
  590. }
  591. fprintf(stderr, "umask: Invalid mask '%s'\n", mask_text);
  592. return 1;
  593. }
  594. int Shell::builtin_wait(int argc, const char** argv)
  595. {
  596. Vector<const char*> job_ids;
  597. Core::ArgsParser parser;
  598. parser.add_positional_argument(job_ids, "Job IDs to wait for, defaults to all jobs if missing", "jobs", Core::ArgsParser::Required::No);
  599. if (!parser.parse(argc, const_cast<char**>(argv), false))
  600. return 1;
  601. Vector<NonnullRefPtr<Job>> jobs_to_wait_for;
  602. if (job_ids.is_empty()) {
  603. for (auto it : jobs)
  604. jobs_to_wait_for.append(it.value);
  605. } else {
  606. for (String id_s : job_ids) {
  607. auto id_opt = id_s.to_uint();
  608. if (id_opt.has_value()) {
  609. if (auto job = find_job(id_opt.value())) {
  610. jobs_to_wait_for.append(*job);
  611. continue;
  612. }
  613. }
  614. warnln("wait: invalid or nonexistent job id {}", id_s);
  615. return 1;
  616. }
  617. }
  618. for (auto& job : jobs_to_wait_for) {
  619. job->set_running_in_background(false);
  620. block_on_job(job);
  621. }
  622. return 0;
  623. }
  624. int Shell::builtin_unset(int argc, const char** argv)
  625. {
  626. Vector<const char*> vars;
  627. Core::ArgsParser parser;
  628. parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
  629. if (!parser.parse(argc, const_cast<char**>(argv), false))
  630. return 1;
  631. for (auto& value : vars) {
  632. if (lookup_local_variable(value)) {
  633. unset_local_variable(value);
  634. } else {
  635. unsetenv(value);
  636. }
  637. }
  638. return 0;
  639. }
  640. bool Shell::run_builtin(const AST::Command& command, const NonnullRefPtrVector<AST::Rewiring>& rewirings, int& retval)
  641. {
  642. if (command.argv.is_empty())
  643. return false;
  644. if (!has_builtin(command.argv.first()))
  645. return false;
  646. Vector<const char*> argv;
  647. for (auto& arg : command.argv)
  648. argv.append(arg.characters());
  649. argv.append(nullptr);
  650. StringView name = command.argv.first();
  651. SavedFileDescriptors fds { rewirings };
  652. for (auto& rewiring : rewirings) {
  653. int rc = dup2(rewiring.old_fd, rewiring.new_fd);
  654. if (rc < 0) {
  655. perror("dup2(run)");
  656. return false;
  657. }
  658. }
  659. Core::EventLoop loop;
  660. setup_signals();
  661. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  662. if (name == #builtin) { \
  663. retval = builtin_##builtin(argv.size() - 1, argv.data()); \
  664. return true; \
  665. }
  666. ENUMERATE_SHELL_BUILTINS();
  667. #undef __ENUMERATE_SHELL_BUILTIN
  668. return false;
  669. }
  670. bool Shell::has_builtin(const StringView& name) const
  671. {
  672. #define __ENUMERATE_SHELL_BUILTIN(builtin) \
  673. if (name == #builtin) { \
  674. return true; \
  675. }
  676. ENUMERATE_SHELL_BUILTINS();
  677. #undef __ENUMERATE_SHELL_BUILTIN
  678. return false;
  679. }
  680. }