Builtin.cpp 23 KB

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