Builtin.cpp 23 KB

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