Coverage Report

Created: 2025-08-28 06:26

/src/serenity/Userland/Libraries/LibShell/Builtin.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2020-2023, the SerenityOS developers.
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#include "AST.h"
8
#include "Formatter.h"
9
#include "PosixParser.h"
10
#include "Shell.h"
11
#include <AK/ByteString.h>
12
#include <AK/LexicalPath.h>
13
#include <AK/ScopeGuard.h>
14
#include <AK/Statistics.h>
15
#include <LibCore/ArgsParser.h>
16
#include <LibCore/Environment.h>
17
#include <LibCore/EventLoop.h>
18
#include <LibCore/File.h>
19
#include <LibCore/System.h>
20
#include <LibFileSystem/FileSystem.h>
21
#include <errno.h>
22
#include <inttypes.h>
23
#include <limits.h>
24
#include <signal.h>
25
#include <sys/wait.h>
26
#include <unistd.h>
27
28
extern char** environ;
29
30
namespace Shell {
31
32
ErrorOr<int> Shell::builtin_noop(Main::Arguments)
33
0
{
34
0
    return 0;
35
0
}
36
37
ErrorOr<int> Shell::builtin_dump(Main::Arguments arguments)
38
0
{
39
0
    bool posix = false;
40
0
    StringView source;
41
42
0
    Core::ArgsParser parser;
43
0
    parser.add_positional_argument(source, "Shell code to parse and dump", "source");
44
0
    parser.add_option(posix, "Use the POSIX parser", "posix", 'p');
45
46
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
47
0
        return 1;
48
49
0
    TRY((posix ? Posix::Parser { source }.parse() : Parser { source }.parse())->dump(0));
50
0
    return 0;
51
0
}
52
53
enum FollowSymlinks {
54
    Yes,
55
    No
56
};
57
58
static Vector<ByteString> find_matching_executables_in_path(StringView filename, FollowSymlinks follow_symlinks = FollowSymlinks::No, Optional<StringView> force_path = {})
59
0
{
60
    // Edge cases in which there are guaranteed no solutions
61
0
    if (filename.is_empty() || filename.contains('/'))
62
0
        return {};
63
64
0
    char const* path_str = getenv("PATH");
65
0
    auto path = force_path.value_or(DEFAULT_PATH_SV);
66
0
    if (path_str != nullptr && !force_path.has_value())
67
0
        path = { path_str, strlen(path_str) };
68
69
0
    Vector<ByteString> executables;
70
0
    auto directories = path.split_view(':');
71
0
    for (auto directory : directories) {
72
0
        auto file = ByteString::formatted("{}/{}", directory, filename);
73
74
0
        if (follow_symlinks == FollowSymlinks::Yes) {
75
0
            auto path_or_error = FileSystem::read_link(file);
76
0
            if (!path_or_error.is_error())
77
0
                file = path_or_error.release_value();
78
0
        }
79
0
        if (!Core::System::access(file, X_OK).is_error())
80
0
            executables.append(move(file));
81
0
    }
82
83
0
    return executables;
84
0
}
85
86
ErrorOr<int> Shell::builtin_where(Main::Arguments arguments)
87
0
{
88
0
    Vector<StringView> values_to_look_up;
89
0
    bool do_only_path_search { false };
90
0
    bool do_follow_symlinks { false };
91
0
    bool do_print_only_type { false };
92
93
0
    Core::ArgsParser parser;
94
0
    parser.add_positional_argument(values_to_look_up, "List of shell builtins, aliases or executables", "arguments");
95
0
    parser.add_option(do_only_path_search, "Search only for executables in the PATH environment variable", "path-only", 'p');
96
0
    parser.add_option(do_follow_symlinks, "Follow symlinks and print the symlink free path", "follow-symlink", 's');
97
0
    parser.add_option(do_print_only_type, "Print the argument type instead of a human readable description", "type", 'w');
98
99
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
100
0
        return 1;
101
102
0
    auto const look_up_alias = [do_only_path_search, &m_aliases = this->m_aliases](StringView alias) -> Optional<ByteString> {
103
0
        if (do_only_path_search)
104
0
            return {};
105
0
        return m_aliases.get(alias).copy();
106
0
    };
107
108
0
    auto const look_up_builtin = [do_only_path_search](StringView builtin) -> Optional<ByteString> {
109
0
        if (do_only_path_search)
110
0
            return {};
111
0
        for (auto const& _builtin : builtin_names) {
112
0
            if (_builtin == builtin) {
113
0
                return builtin;
114
0
            }
115
0
        }
116
0
        return {};
117
0
    };
118
119
0
    bool at_least_one_succeded { false };
120
0
    for (auto const& argument : values_to_look_up) {
121
0
        auto const alias = look_up_alias(argument);
122
0
        if (alias.has_value()) {
123
0
            if (do_print_only_type)
124
0
                outln("{}: alias", argument);
125
0
            else
126
0
                outln("{}: aliased to {}", argument, alias.value());
127
0
            at_least_one_succeded = true;
128
0
        }
129
130
0
        auto const builtin = look_up_builtin(argument);
131
0
        if (builtin.has_value()) {
132
0
            if (do_print_only_type)
133
0
                outln("{}: builtin", builtin.value());
134
0
            else
135
0
                outln("{}: shell built-in command", builtin.value());
136
0
            at_least_one_succeded = true;
137
0
        }
138
139
0
        auto const executables = find_matching_executables_in_path(argument, do_follow_symlinks ? FollowSymlinks::Yes : FollowSymlinks::No);
140
0
        for (auto const& path : executables) {
141
0
            if (do_print_only_type)
142
0
                outln("{}: command", argument);
143
0
            else
144
0
                outln(path);
145
0
            at_least_one_succeded = true;
146
0
        }
147
0
        if (!at_least_one_succeded)
148
0
            warnln("{} not found", argument);
149
0
    }
150
0
    return at_least_one_succeded ? 0 : 1;
151
0
}
152
153
ErrorOr<int> Shell::builtin_reset(Main::Arguments)
154
0
{
155
0
    destroy();
156
0
    initialize(m_is_interactive);
157
158
    // NOTE: As the last step before returning, clear (flush) the shell text entirely.
159
0
    fprintf(stderr, "\033[3J\033[H\033[2J");
160
0
    fflush(stderr);
161
0
    return 0;
162
0
}
163
164
ErrorOr<int> Shell::builtin_alias(Main::Arguments arguments)
165
0
{
166
0
    Vector<ByteString> aliases;
167
168
0
    Core::ArgsParser parser;
169
0
    parser.add_positional_argument(aliases, "List of name[=values]'s", "name[=value]", Core::ArgsParser::Required::No);
170
171
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
172
0
        return 1;
173
174
0
    if (aliases.is_empty()) {
175
0
        for (auto& alias : m_aliases)
176
0
            printf("%s=%s\n", escape_token(alias.key).characters(), escape_token(alias.value).characters());
177
0
        return 0;
178
0
    }
179
180
0
    bool fail = false;
181
0
    for (auto& argument : aliases) {
182
0
        auto parts = argument.split_limit('=', 2, SplitBehavior::KeepEmpty);
183
0
        if (parts.size() == 1) {
184
0
            auto alias = m_aliases.get(parts[0]);
185
0
            if (alias.has_value()) {
186
0
                printf("%s=%s\n", escape_token(parts[0]).characters(), escape_token(alias.value()).characters());
187
0
            } else {
188
0
                fail = true;
189
0
            }
190
0
        } else {
191
0
            m_aliases.set(parts[0], parts[1]);
192
0
            add_entry_to_cache({ RunnablePath::Kind::Alias, parts[0] });
193
0
        }
194
0
    }
195
196
0
    return fail ? 1 : 0;
197
0
}
198
199
ErrorOr<int> Shell::builtin_unalias(Main::Arguments arguments)
200
0
{
201
0
    bool remove_all { false };
202
0
    Vector<ByteString> aliases;
203
204
0
    Core::ArgsParser parser;
205
0
    parser.set_general_help("Remove alias from the list of aliases");
206
0
    parser.add_option(remove_all, "Remove all aliases", nullptr, 'a');
207
0
    parser.add_positional_argument(aliases, "List of aliases to remove", "alias", Core::ArgsParser::Required::Yes);
208
209
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
210
0
        return 1;
211
212
0
    if (remove_all) {
213
0
        m_aliases.clear();
214
0
        cache_path();
215
0
        return 0;
216
0
    }
217
218
0
    bool failed { false };
219
0
    for (auto& argument : aliases) {
220
0
        if (!m_aliases.contains(argument)) {
221
0
            warnln("unalias: {}: alias not found", argument);
222
0
            failed = true;
223
0
            continue;
224
0
        }
225
0
        m_aliases.remove(argument);
226
0
        remove_entry_from_cache(argument);
227
0
    }
228
229
0
    return failed ? 1 : 0;
230
0
}
231
232
ErrorOr<int> Shell::builtin_break(Main::Arguments arguments)
233
0
{
234
0
    unsigned count = 1;
235
236
0
    Core::ArgsParser parser;
237
0
    parser.add_positional_argument(count, "Number of loops to 'break' out of", "count", Core::ArgsParser::Required::No);
238
239
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
240
0
        return 1;
241
242
0
    if (count != 1) {
243
0
        raise_error(ShellError::EvaluatedSyntaxError, "break: count must be equal to 1 (NYI)");
244
0
        return 1;
245
0
    }
246
247
0
    raise_error(ShellError::InternalControlFlowBreak, "POSIX break");
248
249
0
    return 0;
250
0
}
251
252
ErrorOr<int> Shell::builtin_continue(Main::Arguments arguments)
253
0
{
254
0
    unsigned count = 1;
255
256
0
    Core::ArgsParser parser;
257
0
    parser.add_positional_argument(count, "Number of loops to 'continue' out of", "count", Core::ArgsParser::Required::No);
258
259
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
260
0
        return 1;
261
262
0
    if (count != 1) {
263
0
        raise_error(ShellError::EvaluatedSyntaxError, "continue: count must be equal to 1 (NYI)");
264
0
        return 1;
265
0
    }
266
267
0
    raise_error(ShellError::InternalControlFlowContinue, "POSIX continue");
268
269
0
    return 0;
270
0
}
271
272
ErrorOr<int> Shell::builtin_return(Main::Arguments arguments)
273
0
{
274
0
    int return_code = last_return_code.value_or(0);
275
276
0
    Core::ArgsParser parser;
277
0
    parser.add_positional_argument(return_code, "Return code to return to the parent shell", "return-code", Core::ArgsParser::Required::No);
278
0
    parser.set_general_help("Return from a function or source file");
279
280
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
281
0
        return 1;
282
283
0
    last_return_code = return_code & 0xff;
284
0
    raise_error(ShellError::InternalControlFlowReturn, "POSIX return");
285
286
0
    return 0;
287
0
}
288
289
ErrorOr<int> Shell::builtin_bg(Main::Arguments arguments)
290
0
{
291
0
    int job_id = -1;
292
0
    bool is_pid = false;
293
294
0
    Core::ArgsParser parser;
295
0
    parser.add_positional_argument(Core::ArgsParser::Arg {
296
0
        .help_string = "Job ID or Jobspec to run in background",
297
0
        .name = "job-id",
298
0
        .min_values = 0,
299
0
        .max_values = 1,
300
0
        .accept_value = [&](StringView value) -> bool {
301
            // Check if it's a pid (i.e. literal integer)
302
0
            if (auto number = value.to_number<unsigned>(); number.has_value()) {
303
0
                job_id = number.value();
304
0
                is_pid = true;
305
0
                return true;
306
0
            }
307
308
            // Check if it's a jobspec
309
0
            if (auto id = resolve_job_spec(value); id.has_value()) {
310
0
                job_id = id.value();
311
0
                is_pid = false;
312
0
                return true;
313
0
            }
314
315
0
            return false;
316
0
        } });
317
318
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
319
0
        return 1;
320
321
0
    if (job_id == -1 && !jobs.is_empty())
322
0
        job_id = find_last_job_id();
323
324
0
    auto* job = const_cast<Job*>(find_job(job_id, is_pid));
325
326
0
    if (!job) {
327
0
        if (job_id == -1) {
328
0
            warnln("bg: No current job");
329
0
        } else {
330
0
            warnln("bg: Job with id/pid {} not found", job_id);
331
0
        }
332
0
        return 1;
333
0
    }
334
335
0
    job->set_running_in_background(true);
336
0
    job->set_should_announce_exit(true);
337
0
    job->set_shell_did_continue(true);
338
339
0
    dbgln("Resuming {} ({})", job->pid(), job->cmd());
340
0
    warnln("Resuming job {} - {}", job->job_id(), job->cmd());
341
342
    // Try using the PGID, but if that fails, just use the PID.
343
0
    if (killpg(job->pgid(), SIGCONT) < 0) {
344
0
        if (kill(job->pid(), SIGCONT) < 0) {
345
0
            perror("kill");
346
0
            return 1;
347
0
        }
348
0
    }
349
350
0
    return 0;
351
0
}
352
353
ErrorOr<String> Shell::serialize_function_definition(ShellFunction const& fn) const
354
0
{
355
0
    StringBuilder builder;
356
0
    builder.append(fn.name);
357
0
    builder.append('(');
358
0
    for (size_t i = 0; i < fn.arguments.size(); i++) {
359
0
        builder.append(fn.arguments[i]);
360
0
        if (i != fn.arguments.size() - 1)
361
0
            builder.append(' ');
362
0
    }
363
0
    builder.append(") {\n"sv);
364
0
    if (fn.body) {
365
0
        auto formatter = Formatter(*fn.body);
366
0
        builder.append(formatter.format());
367
0
    }
368
0
    builder.append("\n}"sv);
369
370
0
    return builder.to_string();
371
0
}
372
373
ErrorOr<int> Shell::builtin_type(Main::Arguments arguments)
374
0
{
375
0
    Vector<ByteString> commands;
376
0
    bool dont_show_function_source = false;
377
378
0
    Core::ArgsParser parser;
379
0
    parser.set_general_help("Display information about commands.");
380
0
    parser.add_positional_argument(commands, "Command(s) to list info about", "command");
381
0
    parser.add_option(dont_show_function_source, "Do not show functions source.", "no-fn-source", 'f');
382
383
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
384
0
        return 1;
385
386
0
    bool something_not_found = false;
387
388
0
    for (auto& command : commands) {
389
        // check if it is an alias
390
0
        if (auto alias = m_aliases.get(command); alias.has_value()) {
391
0
            printf("%s is aliased to `%s`\n", escape_token(command).characters(), escape_token(alias.value()).characters());
392
0
            continue;
393
0
        }
394
395
        // check if it is a function
396
0
        if (auto function = m_functions.get(command); function.has_value()) {
397
0
            auto fn = function.value();
398
0
            printf("%s is a function\n", command.characters());
399
0
            if (!dont_show_function_source) {
400
0
                auto source = TRY(serialize_function_definition(fn));
401
0
                outln("{}", source);
402
0
            }
403
0
            continue;
404
0
        }
405
406
        // check if its a builtin
407
0
        if (has_builtin(command)) {
408
0
            printf("%s is a shell builtin\n", command.characters());
409
0
            continue;
410
0
        }
411
412
        // check if its an executable in PATH
413
0
        auto fullpath = Core::System::resolve_executable_from_environment(command);
414
0
        if (!fullpath.is_error()) {
415
0
            printf("%s is %s\n", command.characters(), escape_token(fullpath.release_value()).characters());
416
0
            continue;
417
0
        }
418
0
        something_not_found = true;
419
0
        printf("type: %s not found\n", command.characters());
420
0
    }
421
422
0
    if (something_not_found)
423
0
        return 1;
424
0
    else
425
0
        return 0;
426
0
}
427
428
ErrorOr<int> Shell::builtin_cd(Main::Arguments arguments)
429
0
{
430
0
    StringView arg_path;
431
432
0
    Core::ArgsParser parser;
433
0
    parser.add_positional_argument(arg_path, "Path to change to", "path", Core::ArgsParser::Required::No);
434
435
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
436
0
        return 1;
437
438
0
    ByteString new_path;
439
440
0
    if (arg_path.is_empty()) {
441
0
        new_path = home;
442
0
    } else {
443
0
        if (arg_path == "-"sv) {
444
0
            char* oldpwd = getenv("OLDPWD");
445
0
            if (oldpwd == nullptr)
446
0
                return 1;
447
0
            new_path = oldpwd;
448
0
        } else {
449
0
            new_path = arg_path;
450
0
        }
451
0
    }
452
453
0
    auto real_path_or_error = FileSystem::real_path(new_path);
454
0
    if (real_path_or_error.is_error()) {
455
0
        warnln("Invalid path '{}'", new_path);
456
0
        return 1;
457
0
    }
458
0
    auto real_path = real_path_or_error.release_value();
459
460
0
    if (cd_history.is_empty() || cd_history.last() != real_path)
461
0
        cd_history.enqueue(real_path);
462
463
0
    auto path_relative_to_current_directory = LexicalPath::relative_path(real_path, cwd);
464
0
    if (path_relative_to_current_directory.is_empty())
465
0
        path_relative_to_current_directory = real_path;
466
0
    char const* path = path_relative_to_current_directory.characters();
467
468
0
    int rc = chdir(path);
469
0
    if (rc < 0) {
470
0
        if (errno == ENOTDIR) {
471
0
            warnln("Not a directory: {}", path);
472
0
        } else {
473
0
            warnln("chdir({}) failed: {}", path, strerror(errno));
474
0
        }
475
0
        return 1;
476
0
    }
477
0
    setenv("OLDPWD", cwd.characters(), 1);
478
0
    cwd = move(real_path);
479
0
    setenv("PWD", cwd.characters(), 1);
480
0
    return 0;
481
0
}
482
483
ErrorOr<int> Shell::builtin_cdh(Main::Arguments arguments)
484
0
{
485
0
    int index = -1;
486
487
0
    Core::ArgsParser parser;
488
0
    parser.add_positional_argument(index, "Index of the cd history entry (leave out for a list)", "index", Core::ArgsParser::Required::No);
489
490
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
491
0
        return 1;
492
493
0
    if (index == -1) {
494
0
        if (cd_history.is_empty()) {
495
0
            warnln("cdh: no history available");
496
0
            return 0;
497
0
        }
498
499
0
        for (ssize_t i = cd_history.size() - 1; i >= 0; --i)
500
0
            printf("%zu: %s\n", cd_history.size() - i, cd_history.at(i).characters());
501
0
        return 0;
502
0
    }
503
504
0
    if (index < 1 || (size_t)index > cd_history.size()) {
505
0
        warnln("cdh: history index out of bounds: {} not in (0, {})", index, cd_history.size());
506
0
        return 1;
507
0
    }
508
509
0
    StringView path = cd_history.at(cd_history.size() - index);
510
0
    StringView cd_args[] = { "cd"sv, path };
511
0
    return Shell::builtin_cd({ .argc = 0, .argv = 0, .strings = cd_args });
512
0
}
513
514
ErrorOr<int> Shell::builtin_command(Main::Arguments arguments)
515
0
{
516
0
    bool describe = false;
517
0
    bool describe_verbosely = false;
518
0
    bool search_in_default_path = false;
519
0
    Vector<StringView> commands_or_args;
520
521
0
    Core::ArgsParser parser;
522
0
    parser.add_option(search_in_default_path, "default-path", "Use a default value for PATH", 'p');
523
0
    parser.add_option(describe, "describe", "Describe the file that would be executed", 'v');
524
0
    parser.add_option(describe_verbosely, "describe-verbosely", "Describe the file that would be executed more verbosely", 'V');
525
0
    parser.add_positional_argument(commands_or_args, "Arguments or command names to search for", "arg");
526
0
    parser.set_stop_on_first_non_option(true);
527
528
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
529
0
        return 1;
530
531
0
    auto const look_up_builtin = [](StringView builtin) -> Optional<ByteString> {
532
0
        for (auto const& _builtin : builtin_names) {
533
0
            if (_builtin == builtin) {
534
0
                return builtin;
535
0
            }
536
0
        }
537
0
        return {};
538
0
    };
539
540
0
    describe |= describe_verbosely;
541
0
    if (!describe) {
542
0
        AST::Command command;
543
0
        TRY(command.argv.try_ensure_capacity(commands_or_args.size()));
544
0
        for (auto& arg : commands_or_args)
545
0
            command.argv.append(TRY(String::from_utf8(arg)));
546
547
0
        auto commands = TRY(expand_aliases({ move(command) }));
548
549
0
        int exit_code = 1;
550
0
        for (auto& job : run_commands(commands)) {
551
0
            block_on_job(job);
552
0
            exit_code = job->exit_code();
553
0
        }
554
555
0
        return exit_code;
556
0
    }
557
558
0
    bool any_failed = false;
559
0
    for (auto const& argument : commands_or_args) {
560
0
        auto alias = m_aliases.get(argument);
561
0
        if (alias.has_value()) {
562
0
            if (describe_verbosely)
563
0
                outln("{}: aliased to {}", argument, alias.value());
564
0
            else
565
0
                outln("{}", alias.value());
566
0
            continue;
567
0
        }
568
569
0
        auto const builtin = look_up_builtin(argument);
570
0
        if (builtin.has_value()) {
571
0
            if (describe_verbosely)
572
0
                outln("{}: shell built-in command", builtin.value());
573
0
            else
574
0
                outln("{}", builtin.value());
575
0
            continue;
576
0
        }
577
578
0
        auto const executables = find_matching_executables_in_path(argument, FollowSymlinks::No, search_in_default_path ? DEFAULT_PATH_SV : Optional<StringView>());
579
0
        if (!executables.is_empty()) {
580
0
            outln("{}", executables.first());
581
0
            continue;
582
0
        }
583
584
0
        if (describe_verbosely)
585
0
            warnln("{} not found", argument);
586
0
        any_failed = true;
587
0
    }
588
589
0
    return any_failed ? 1 : 0;
590
0
}
591
592
ErrorOr<int> Shell::builtin_dirs(Main::Arguments arguments)
593
0
{
594
    // The first directory in the stack is ALWAYS the current directory
595
0
    directory_stack.at(0) = cwd.characters();
596
597
0
    bool clear = false;
598
0
    bool print = false;
599
0
    bool number_when_printing = false;
600
0
    char separator = ' ';
601
602
0
    Vector<ByteString> paths;
603
604
0
    Core::ArgsParser parser;
605
0
    parser.add_option(clear, "Clear the directory stack", "clear", 'c');
606
0
    parser.add_option(print, "Print directory entries one per line", "print", 'p');
607
0
    parser.add_option(number_when_printing, "Number the directories in the stack when printing", "number", 'v');
608
0
    parser.add_positional_argument(paths, "Extra paths to put on the stack", "path", Core::ArgsParser::Required::No);
609
610
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
611
0
        return 1;
612
613
    // -v implies -p
614
0
    print = print || number_when_printing;
615
616
0
    if (print) {
617
0
        if (!paths.is_empty()) {
618
0
            warnln("dirs: 'print' and 'number' are not allowed when any path is specified");
619
0
            return 1;
620
0
        }
621
0
        separator = '\n';
622
0
    }
623
624
0
    if (clear) {
625
0
        for (size_t i = 1; i < directory_stack.size(); i++)
626
0
            directory_stack.remove(i);
627
0
    }
628
629
0
    for (auto& path : paths)
630
0
        directory_stack.append(path);
631
632
0
    if (print || (!clear && paths.is_empty())) {
633
0
        int index = 0;
634
0
        for (auto& directory : directory_stack) {
635
0
            if (number_when_printing)
636
0
                printf("%d ", index++);
637
0
            print_path(directory);
638
0
            fputc(separator, stdout);
639
0
        }
640
0
    }
641
642
0
    return 0;
643
0
}
644
645
ErrorOr<int> Shell::builtin_eval(Main::Arguments arguments)
646
0
{
647
0
    if (!m_in_posix_mode) {
648
0
        warnln("eval: This shell is not in POSIX mode");
649
0
        return 1;
650
0
    }
651
652
0
    StringBuilder joined_arguments;
653
0
    for (size_t i = 1; i < arguments.strings.size(); ++i) {
654
0
        if (i != 1)
655
0
            joined_arguments.append(' ');
656
0
        joined_arguments.append(arguments.strings[i]);
657
0
    }
658
659
0
    auto result = Posix::Parser { TRY(joined_arguments.to_string()) }.parse();
660
0
    if (!result)
661
0
        return 1;
662
663
0
    auto value = TRY(result->run(*this));
664
0
    if (value && value->is_job())
665
0
        block_on_job(static_cast<AST::JobValue*>(value.ptr())->job());
666
667
0
    return last_return_code.value_or(0);
668
0
}
669
670
ErrorOr<int> Shell::builtin_exec(Main::Arguments arguments)
671
0
{
672
0
    if (arguments.strings.size() < 2) {
673
0
        warnln("Shell: No command given to exec");
674
0
        return 1;
675
0
    }
676
677
0
    TRY(execute_process(arguments.strings.slice(1)));
678
    // NOTE: Won't get here.
679
0
    return 0;
680
0
}
681
682
ErrorOr<int> Shell::builtin_exit(Main::Arguments arguments)
683
0
{
684
0
    int exit_code = 0;
685
0
    Core::ArgsParser parser;
686
0
    parser.add_positional_argument(exit_code, "Exit code", "code", Core::ArgsParser::Required::No);
687
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
688
0
        return 1;
689
690
0
    if (m_is_interactive) {
691
0
        if (!jobs.is_empty()) {
692
0
            if (!m_should_ignore_jobs_on_next_exit) {
693
0
                warnln("Shell: You have {} active job{}, run 'exit' again to really exit.", jobs.size(), jobs.size() > 1 ? "s" : "");
694
0
                m_should_ignore_jobs_on_next_exit = true;
695
0
                return 1;
696
0
            }
697
0
        }
698
0
    }
699
0
    stop_all_jobs();
700
0
    if (m_is_interactive) {
701
0
        m_editor->save_history(get_history_path());
702
0
        printf("Good-bye!\n");
703
0
    }
704
0
    exit(exit_code);
705
0
}
706
707
ErrorOr<int> Shell::builtin_export(Main::Arguments arguments)
708
0
{
709
0
    Vector<ByteString> vars;
710
711
0
    Core::ArgsParser parser;
712
0
    parser.add_positional_argument(vars, "List of variable[=value]'s", "values", Core::ArgsParser::Required::No);
713
714
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
715
0
        return 1;
716
717
0
    if (vars.is_empty()) {
718
0
        for (auto entry : Core::Environment::entries())
719
0
            outln("{}", entry.full_entry);
720
0
        return 0;
721
0
    }
722
723
0
    for (auto& value : vars) {
724
0
        auto parts = value.split_limit('=', 2);
725
0
        if (parts.is_empty()) {
726
0
            warnln("Shell: Invalid export spec '{}', expected `variable=value' or `variable'", value);
727
0
            return 1;
728
0
        }
729
730
0
        if (parts.size() == 1) {
731
0
            auto value = TRY(look_up_local_variable(parts[0]));
732
0
            if (value) {
733
0
                auto values = TRY(const_cast<AST::Value&>(*value).resolve_as_list(*this));
734
0
                StringBuilder builder;
735
0
                builder.join(' ', values);
736
0
                parts.append(builder.to_byte_string());
737
0
            } else {
738
                // Ignore the export.
739
0
                continue;
740
0
            }
741
0
        }
742
743
0
        int setenv_return = setenv(parts[0].characters(), parts[1].characters(), 1);
744
745
0
        if (setenv_return != 0) {
746
0
            perror("setenv");
747
0
            return 1;
748
0
        }
749
750
0
        if (parts[0] == "PATH")
751
0
            cache_path();
752
0
    }
753
754
0
    return 0;
755
0
}
756
757
ErrorOr<int> Shell::builtin_glob(Main::Arguments arguments)
758
0
{
759
0
    Vector<ByteString> globs;
760
0
    Core::ArgsParser parser;
761
0
    parser.add_positional_argument(globs, "Globs to resolve", "glob");
762
763
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
764
0
        return 1;
765
766
0
    for (auto& glob : globs) {
767
0
        for (auto& expanded : TRY(expand_globs(glob, cwd)))
768
0
            outln("{}", expanded);
769
0
    }
770
771
0
    return 0;
772
0
}
773
774
ErrorOr<int> Shell::builtin_fg(Main::Arguments arguments)
775
0
{
776
0
    int job_id = -1;
777
0
    bool is_pid = false;
778
779
0
    Core::ArgsParser parser;
780
0
    parser.add_positional_argument(Core::ArgsParser::Arg {
781
0
        .help_string = "Job ID or Jobspec to bring to foreground",
782
0
        .name = "job-id",
783
0
        .min_values = 0,
784
0
        .max_values = 1,
785
0
        .accept_value = [&](StringView value) -> bool {
786
            // Check if it's a pid (i.e. literal integer)
787
0
            if (auto number = value.to_number<unsigned>(); number.has_value()) {
788
0
                job_id = number.value();
789
0
                is_pid = true;
790
0
                return true;
791
0
            }
792
793
            // Check if it's a jobspec
794
0
            if (auto id = resolve_job_spec(value); id.has_value()) {
795
0
                job_id = id.value();
796
0
                is_pid = false;
797
0
                return true;
798
0
            }
799
800
0
            return false;
801
0
        } });
802
803
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
804
0
        return 1;
805
806
0
    if (job_id == -1 && !jobs.is_empty())
807
0
        job_id = find_last_job_id();
808
809
0
    RefPtr<Job> job = find_job(job_id, is_pid);
810
811
0
    if (!job) {
812
0
        if (job_id == -1) {
813
0
            warnln("fg: No current job");
814
0
        } else {
815
0
            warnln("fg: Job with id/pid {} not found", job_id);
816
0
        }
817
0
        return 1;
818
0
    }
819
820
0
    job->set_running_in_background(false);
821
0
    job->set_shell_did_continue(true);
822
823
0
    dbgln("Resuming {} ({})", job->pid(), job->cmd());
824
0
    warnln("Resuming job {} - {}", job->job_id(), job->cmd());
825
826
0
    tcsetpgrp(STDOUT_FILENO, job->pgid());
827
0
    tcsetpgrp(STDIN_FILENO, job->pgid());
828
829
    // Try using the PGID, but if that fails, just use the PID.
830
0
    if (killpg(job->pgid(), SIGCONT) < 0) {
831
0
        if (kill(job->pid(), SIGCONT) < 0) {
832
0
            perror("kill");
833
0
            return 1;
834
0
        }
835
0
    }
836
837
0
    block_on_job(job);
838
839
0
    if (job->exited())
840
0
        return job->exit_code();
841
0
    else
842
0
        return 0;
843
0
}
844
845
ErrorOr<int> Shell::builtin_disown(Main::Arguments arguments)
846
0
{
847
0
    Vector<int> job_ids;
848
0
    Vector<bool> id_is_pid;
849
850
0
    Core::ArgsParser parser;
851
0
    parser.add_positional_argument(Core::ArgsParser::Arg {
852
0
        .help_string = "Job IDs or Jobspecs to disown",
853
0
        .name = "job-id",
854
0
        .min_values = 0,
855
0
        .max_values = INT_MAX,
856
0
        .accept_value = [&](StringView value) -> bool {
857
            // Check if it's a pid (i.e. literal integer)
858
0
            if (auto number = value.to_number<unsigned>(); number.has_value()) {
859
0
                job_ids.append(number.value());
860
0
                id_is_pid.append(true);
861
0
                return true;
862
0
            }
863
864
            // Check if it's a jobspec
865
0
            if (auto id = resolve_job_spec(value); id.has_value()) {
866
0
                job_ids.append(id.value());
867
0
                id_is_pid.append(false);
868
0
                return true;
869
0
            }
870
871
0
            return false;
872
0
        } });
873
874
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
875
0
        return 1;
876
877
0
    if (job_ids.is_empty()) {
878
0
        job_ids.append(find_last_job_id());
879
0
        id_is_pid.append(false);
880
0
    }
881
882
0
    Vector<Job const*> jobs_to_disown;
883
884
0
    for (size_t i = 0; i < job_ids.size(); ++i) {
885
0
        auto id = job_ids[i];
886
0
        auto is_pid = id_is_pid[i];
887
0
        auto job = find_job(id, is_pid);
888
0
        if (!job)
889
0
            warnln("disown: Job with id/pid {} not found", id);
890
0
        else
891
0
            jobs_to_disown.append(job);
892
0
    }
893
894
0
    if (jobs_to_disown.is_empty()) {
895
0
        if (job_ids.is_empty())
896
0
            warnln("disown: No current job");
897
        // An error message has already been printed about the nonexistence of each listed job.
898
0
        return 1;
899
0
    }
900
901
0
    for (auto job : jobs_to_disown) {
902
0
        job->deactivate();
903
904
0
        if (!job->is_running_in_background())
905
0
            warnln("disown warning: Job {} is currently not running, 'kill -{} {}' to make it continue", job->job_id(), SIGCONT, job->pid());
906
907
0
        jobs.remove(job->pid());
908
0
    }
909
910
0
    return 0;
911
0
}
912
913
ErrorOr<int> Shell::builtin_history(Main::Arguments)
914
0
{
915
0
    for (size_t i = 0; i < m_editor->history().size(); ++i) {
916
0
        printf("%6zu  %s\n", i + 1, m_editor->history()[i].entry.characters());
917
0
    }
918
0
    return 0;
919
0
}
920
921
ErrorOr<int> Shell::builtin_jobs(Main::Arguments arguments)
922
0
{
923
0
    bool list = false, show_pid = false;
924
925
0
    Core::ArgsParser parser;
926
0
    parser.add_option(list, "List all information about jobs", "list", 'l');
927
0
    parser.add_option(show_pid, "Display the PID of the jobs", "pid", 'p');
928
929
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
930
0
        return 1;
931
932
0
    Job::PrintStatusMode mode = Job::PrintStatusMode::Basic;
933
934
0
    if (show_pid)
935
0
        mode = Job::PrintStatusMode::OnlyPID;
936
937
0
    if (list)
938
0
        mode = Job::PrintStatusMode::ListAll;
939
940
0
    for (auto& it : jobs) {
941
0
        if (!it.value->print_status(mode))
942
0
            return 1;
943
0
    }
944
945
0
    return 0;
946
0
}
947
948
ErrorOr<int> Shell::builtin_popd(Main::Arguments arguments)
949
0
{
950
0
    if (directory_stack.size() <= 1) {
951
0
        warnln("Shell: popd: directory stack empty");
952
0
        return 1;
953
0
    }
954
955
0
    bool should_not_switch = false;
956
0
    Core::ArgsParser parser;
957
0
    parser.add_option(should_not_switch, "Do not switch dirs", "no-switch", 'n');
958
959
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
960
0
        return 1;
961
962
0
    auto popped_path = directory_stack.take_last();
963
964
0
    if (should_not_switch)
965
0
        return 0;
966
967
0
    auto new_path = LexicalPath::canonicalized_path(popped_path);
968
0
    if (chdir(new_path.characters()) < 0) {
969
0
        warnln("chdir({}) failed: {}", new_path, strerror(errno));
970
0
        return 1;
971
0
    }
972
0
    cwd = new_path;
973
0
    return 0;
974
0
}
975
976
ErrorOr<int> Shell::builtin_pushd(Main::Arguments arguments)
977
0
{
978
0
    StringBuilder path_builder;
979
0
    bool should_switch = true;
980
981
    // From the BASH reference manual: https://www.gnu.org/software/bash/manual/html_node/Directory-Stack-Builtins.html
982
    // With no arguments, pushd exchanges the top two directories and makes the new top the current directory.
983
0
    if (arguments.strings.size() == 1) {
984
0
        if (directory_stack.size() < 2) {
985
0
            warnln("pushd: no other directory");
986
0
            return 1;
987
0
        }
988
989
0
        ByteString dir1 = directory_stack.take_first();
990
0
        ByteString dir2 = directory_stack.take_first();
991
0
        directory_stack.insert(0, dir2);
992
0
        directory_stack.insert(1, dir1);
993
994
0
        int rc = chdir(dir2.characters());
995
0
        if (rc < 0) {
996
0
            warnln("chdir({}) failed: {}", dir2, strerror(errno));
997
0
            return 1;
998
0
        }
999
1000
0
        cwd = dir2;
1001
1002
0
        return 0;
1003
0
    }
1004
1005
    // Let's assume the user's typed in 'pushd <dir>'
1006
0
    if (arguments.strings.size() == 2) {
1007
0
        directory_stack.append(cwd.characters());
1008
0
        if (arguments.strings[1].starts_with('/')) {
1009
0
            path_builder.append(arguments.strings[1]);
1010
0
        } else {
1011
0
            path_builder.appendff("{}/{}", cwd, arguments.strings[1]);
1012
0
        }
1013
0
    } else if (arguments.strings.size() == 3) {
1014
0
        directory_stack.append(cwd.characters());
1015
0
        for (size_t i = 1; i < arguments.strings.size(); i++) {
1016
0
            auto arg = arguments.strings[i];
1017
1018
0
            if (arg.starts_with('-')) {
1019
0
                if (arg.starts_with('/')) {
1020
0
                    path_builder.append(arg);
1021
0
                } else {
1022
0
                    path_builder.appendff("{}/{}", cwd, arg);
1023
0
                }
1024
0
            }
1025
1026
0
            if (arg == "-n"sv)
1027
0
                should_switch = false;
1028
0
        }
1029
0
    }
1030
1031
0
    auto real_path = LexicalPath::canonicalized_path(path_builder.to_byte_string());
1032
1033
0
    struct stat st;
1034
0
    int rc = stat(real_path.characters(), &st);
1035
0
    if (rc < 0) {
1036
0
        warnln("stat({}) failed: {}", real_path, strerror(errno));
1037
0
        return 1;
1038
0
    }
1039
1040
0
    if (!S_ISDIR(st.st_mode)) {
1041
0
        warnln("Not a directory: {}", real_path);
1042
0
        return 1;
1043
0
    }
1044
1045
0
    if (should_switch) {
1046
0
        int rc = chdir(real_path.characters());
1047
0
        if (rc < 0) {
1048
0
            warnln("chdir({}) failed: {}", real_path, strerror(errno));
1049
0
            return 1;
1050
0
        }
1051
1052
0
        cwd = real_path;
1053
0
    }
1054
1055
0
    return 0;
1056
0
}
1057
1058
ErrorOr<int> Shell::builtin_pwd(Main::Arguments)
1059
0
{
1060
0
    print_path(cwd);
1061
0
    fputc('\n', stdout);
1062
0
    return 0;
1063
0
}
1064
1065
ErrorOr<int> Shell::builtin_setopt(Main::Arguments arguments)
1066
0
{
1067
0
    if (arguments.strings.size() == 1) {
1068
0
#define __ENUMERATE_SHELL_OPTION(name, default_, description) \
1069
0
    if (options.name)                                         \
1070
0
        warnln("{}", #name);
1071
1072
0
        ENUMERATE_SHELL_OPTIONS();
1073
1074
0
#undef __ENUMERATE_SHELL_OPTION
1075
0
    }
1076
1077
0
    Core::ArgsParser parser;
1078
0
#define __ENUMERATE_SHELL_OPTION(name, default_, description)     \
1079
0
    bool name = false;                                            \
1080
0
    bool not_##name = false;                                      \
1081
0
    parser.add_option(name, "Enable: " description, #name, '\0'); \
1082
0
    parser.add_option(not_##name, "Disable: " description, "no_" #name, '\0');
1083
1084
0
    ENUMERATE_SHELL_OPTIONS();
1085
1086
0
#undef __ENUMERATE_SHELL_OPTION
1087
1088
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
1089
0
        return 1;
1090
1091
0
#define __ENUMERATE_SHELL_OPTION(name, default_, description) \
1092
0
    if (name)                                                 \
1093
0
        options.name = true;                                  \
1094
0
    if (not_##name)                                           \
1095
0
        options.name = false;
1096
1097
0
    ENUMERATE_SHELL_OPTIONS();
1098
1099
0
#undef __ENUMERATE_SHELL_OPTION
1100
1101
0
    return 0;
1102
0
}
1103
1104
ErrorOr<int> Shell::builtin_shift(Main::Arguments arguments)
1105
0
{
1106
0
    int count = 1;
1107
1108
0
    Core::ArgsParser parser;
1109
0
    parser.add_positional_argument(count, "Shift count", "count", Core::ArgsParser::Required::No);
1110
1111
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
1112
0
        return 1;
1113
1114
0
    if (count < 1)
1115
0
        return 0;
1116
1117
0
    auto argv_ = TRY(look_up_local_variable("ARGV"sv));
1118
0
    if (!argv_) {
1119
0
        warnln("shift: ARGV is unset");
1120
0
        return 1;
1121
0
    }
1122
1123
0
    if (!argv_->is_list())
1124
0
        argv_ = adopt_ref(*new AST::ListValue({ const_cast<AST::Value&>(*argv_) }));
1125
1126
0
    auto& values = const_cast<AST::ListValue*>(static_cast<AST::ListValue const*>(argv_.ptr()))->values();
1127
0
    if ((size_t)count > values.size()) {
1128
0
        warnln("shift: shift count must not be greater than {}", values.size());
1129
0
        return 1;
1130
0
    }
1131
1132
0
    for (auto i = 0; i < count; ++i)
1133
0
        (void)values.take_first();
1134
1135
0
    return 0;
1136
0
}
1137
1138
ErrorOr<int> Shell::builtin_source(Main::Arguments arguments)
1139
0
{
1140
0
    StringView file_to_source;
1141
0
    Vector<StringView> args;
1142
1143
0
    Core::ArgsParser parser;
1144
0
    parser.add_positional_argument(file_to_source, "File to read commands from", "path");
1145
0
    parser.add_positional_argument(args, "ARGV for the sourced file", "args", Core::ArgsParser::Required::No);
1146
1147
0
    if (!parser.parse(arguments))
1148
0
        return 1;
1149
1150
0
    auto previous_argv = TRY(look_up_local_variable("ARGV"sv));
1151
0
    ScopeGuard guard { [&] {
1152
0
        if (!args.is_empty())
1153
0
            set_local_variable("ARGV", const_cast<AST::Value&>(*previous_argv));
1154
0
    } };
1155
1156
0
    if (!args.is_empty()) {
1157
0
        Vector<String> arguments;
1158
0
        arguments.ensure_capacity(args.size());
1159
0
        for (auto& arg : args)
1160
0
            arguments.append(TRY(String::from_utf8(arg)));
1161
1162
0
        set_local_variable("ARGV", AST::make_ref_counted<AST::ListValue>(move(arguments)));
1163
0
    }
1164
1165
0
    if (!run_file(file_to_source, true))
1166
0
        return 126;
1167
1168
0
    return 0;
1169
0
}
1170
1171
ErrorOr<int> Shell::builtin_time(Main::Arguments arguments)
1172
0
{
1173
0
    Vector<StringView> args;
1174
1175
0
    int number_of_iterations = 1;
1176
1177
0
    Core::ArgsParser parser;
1178
0
    parser.add_option(number_of_iterations, "Number of iterations", "iterations", 'n', "iterations");
1179
0
    parser.set_stop_on_first_non_option(true);
1180
0
    parser.add_positional_argument(args, "Command to execute with arguments", "command", Core::ArgsParser::Required::Yes);
1181
1182
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
1183
0
        return 1;
1184
1185
0
    if (number_of_iterations < 1)
1186
0
        return 1;
1187
1188
0
    AST::Command command;
1189
0
    TRY(command.argv.try_ensure_capacity(args.size()));
1190
0
    for (auto& arg : args)
1191
0
        command.argv.append(TRY(String::from_utf8(arg)));
1192
1193
0
    auto commands = TRY(expand_aliases({ move(command) }));
1194
1195
0
    AK::Statistics iteration_times;
1196
1197
0
    int exit_code = 1;
1198
0
    for (int i = 0; i < number_of_iterations; ++i) {
1199
0
        auto timer = Core::ElapsedTimer::start_new();
1200
0
        for (auto& job : run_commands(commands)) {
1201
0
            block_on_job(job);
1202
0
            exit_code = job->exit_code();
1203
0
        }
1204
0
        iteration_times.add(static_cast<float>(timer.elapsed()));
1205
0
    }
1206
1207
0
    warnln();
1208
1209
0
    if (number_of_iterations == 1) {
1210
0
        warnln("Time: {} ms", iteration_times.values().first());
1211
0
    } else {
1212
0
        AK::Statistics iteration_times_excluding_first;
1213
0
        for (size_t i = 1; i < iteration_times.size(); i++)
1214
0
            iteration_times_excluding_first.add(iteration_times.values()[i]);
1215
1216
0
        warnln("Timing report: {} ms", iteration_times.sum());
1217
0
        warnln("==============");
1218
0
        warnln("Command:         {}", ByteString::join(' ', arguments.strings));
1219
0
        warnln("Average time:    {:.2} ms (median: {}, stddev: {:.2}, min: {}, max: {})",
1220
0
            iteration_times.average(), iteration_times.median(),
1221
0
            iteration_times.standard_deviation(),
1222
0
            iteration_times.min(), iteration_times.max());
1223
0
        warnln("Excluding first: {:.2} ms (median: {}, stddev: {:.2}, min: {}, max: {})",
1224
0
            iteration_times_excluding_first.average(), iteration_times_excluding_first.median(),
1225
0
            iteration_times_excluding_first.standard_deviation(),
1226
0
            iteration_times_excluding_first.min(), iteration_times_excluding_first.max());
1227
0
    }
1228
1229
0
    return exit_code;
1230
0
}
1231
1232
ErrorOr<int> Shell::builtin_umask(Main::Arguments arguments)
1233
0
{
1234
0
    StringView mask_text;
1235
0
    bool symbolic_output = false;
1236
1237
0
    Core::ArgsParser parser;
1238
1239
0
    parser.add_option(symbolic_output, "Produce symbolic output", "symbolic", 'S');
1240
0
    parser.add_positional_argument(mask_text, "New mask (omit to get current mask)", "octal-mask", Core::ArgsParser::Required::No);
1241
1242
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
1243
0
        return 1;
1244
1245
0
    auto parse_symbolic_digit = [](int digit) -> ErrorOr<String> {
1246
0
        StringBuilder builder;
1247
1248
0
        if ((digit & 4) == 0)
1249
0
            TRY(builder.try_append('r'));
1250
0
        if ((digit & 2) == 0)
1251
0
            TRY(builder.try_append('w'));
1252
0
        if ((digit & 1) == 0)
1253
0
            TRY(builder.try_append('x'));
1254
0
        if (builder.is_empty())
1255
0
            TRY(builder.try_append('-'));
1256
1257
0
        return builder.to_string();
1258
0
    };
1259
1260
0
    if (mask_text.is_empty()) {
1261
0
        mode_t old_mask = umask(0);
1262
1263
0
        if (symbolic_output) {
1264
0
            StringBuilder builder;
1265
1266
0
            TRY(builder.try_append("u="sv));
1267
0
            TRY(builder.try_append(TRY(parse_symbolic_digit(old_mask >> 6 & 7)).bytes()));
1268
1269
0
            TRY(builder.try_append(",g="sv));
1270
0
            TRY(builder.try_append(TRY(parse_symbolic_digit(old_mask >> 3 & 7)).bytes()));
1271
1272
0
            TRY(builder.try_append(",o="sv));
1273
0
            TRY(builder.try_append(TRY(parse_symbolic_digit(old_mask >> 0 & 7)).bytes()));
1274
1275
0
            outln("{}", builder.string_view());
1276
0
        } else {
1277
0
            outln("{:#o}", old_mask);
1278
0
        }
1279
1280
0
        umask(old_mask);
1281
0
        return 0;
1282
0
    }
1283
1284
0
    unsigned mask = 0;
1285
0
    auto matches = true;
1286
1287
    // FIXME: There's currently no way to parse an StringView as an octal integer,
1288
    //        when that becomes available, replace this code.
1289
0
    for (auto byte : mask_text.bytes()) {
1290
0
        if (isspace(byte))
1291
0
            continue;
1292
0
        if (!is_ascii_octal_digit(byte)) {
1293
0
            matches = false;
1294
0
            break;
1295
0
        }
1296
1297
0
        mask = (mask << 3) + (byte - '0');
1298
0
    }
1299
0
    if (matches) {
1300
0
        umask(mask);
1301
0
        return 0;
1302
0
    }
1303
1304
0
    warnln("umask: Invalid mask '{}'", mask_text);
1305
0
    return 1;
1306
0
}
1307
1308
ErrorOr<int> Shell::builtin_wait(Main::Arguments arguments)
1309
0
{
1310
0
    Vector<int> job_ids;
1311
0
    Vector<bool> id_is_pid;
1312
1313
0
    Core::ArgsParser parser;
1314
0
    parser.add_positional_argument(Core::ArgsParser::Arg {
1315
0
        .help_string = "Job IDs or Jobspecs to wait for",
1316
0
        .name = "job-id",
1317
0
        .min_values = 0,
1318
0
        .max_values = INT_MAX,
1319
0
        .accept_value = [&](StringView value) -> bool {
1320
            // Check if it's a pid (i.e. literal integer)
1321
0
            if (auto number = value.to_number<unsigned>(); number.has_value()) {
1322
0
                job_ids.append(number.value());
1323
0
                id_is_pid.append(true);
1324
0
                return true;
1325
0
            }
1326
1327
            // Check if it's a jobspec
1328
0
            if (auto id = resolve_job_spec(value); id.has_value()) {
1329
0
                job_ids.append(id.value());
1330
0
                id_is_pid.append(false);
1331
0
                return true;
1332
0
            }
1333
1334
0
            return false;
1335
0
        } });
1336
1337
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
1338
0
        return 1;
1339
1340
0
    Vector<NonnullRefPtr<Job>> jobs_to_wait_for;
1341
1342
0
    for (size_t i = 0; i < job_ids.size(); ++i) {
1343
0
        auto id = job_ids[i];
1344
0
        auto is_pid = id_is_pid[i];
1345
0
        auto job = find_job(id, is_pid);
1346
0
        if (!job)
1347
0
            warnln("wait: Job with id/pid {} not found", id);
1348
0
        else
1349
0
            jobs_to_wait_for.append(*job);
1350
0
    }
1351
1352
0
    if (job_ids.is_empty()) {
1353
0
        for (auto const& it : jobs)
1354
0
            jobs_to_wait_for.append(it.value);
1355
0
    }
1356
1357
0
    for (auto& job : jobs_to_wait_for) {
1358
0
        job->set_running_in_background(false);
1359
0
        block_on_job(job);
1360
0
    }
1361
1362
0
    return 0;
1363
0
}
1364
1365
ErrorOr<int> Shell::builtin_unset(Main::Arguments arguments)
1366
0
{
1367
0
    Vector<ByteString> vars;
1368
0
    bool unset_only_variables = false; // POSIX only.
1369
1370
0
    Core::ArgsParser parser;
1371
0
    parser.add_positional_argument(vars, "List of variables", "variables", Core::ArgsParser::Required::Yes);
1372
0
    if (m_in_posix_mode)
1373
0
        parser.add_option(unset_only_variables, "Unset only variables", "variables", 'v');
1374
1375
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
1376
0
        return 1;
1377
1378
0
    bool did_touch_path = false;
1379
0
    for (auto& value : vars) {
1380
0
        if (!did_touch_path && value == "PATH"sv)
1381
0
            did_touch_path = true;
1382
1383
0
        if (TRY(look_up_local_variable(value)) != nullptr) {
1384
0
            unset_local_variable(value);
1385
0
        } else if (!unset_only_variables) {
1386
0
            unsetenv(value.characters());
1387
0
        }
1388
0
    }
1389
1390
0
    if (did_touch_path)
1391
0
        cache_path();
1392
1393
0
    return 0;
1394
0
}
1395
1396
ErrorOr<int> Shell::builtin_set(Main::Arguments arguments)
1397
0
{
1398
0
    if (arguments.strings.size() == 1) {
1399
0
        HashMap<String, String> vars;
1400
1401
0
        StringBuilder builder;
1402
0
        for (auto& frame : m_local_frames) {
1403
0
            for (auto& var : frame->local_variables) {
1404
0
                builder.join(" "sv, TRY(var.value->resolve_as_list(*this)));
1405
0
                vars.set(TRY(String::from_byte_string(var.key)), TRY(builder.to_string()));
1406
0
                builder.clear();
1407
0
            }
1408
0
        }
1409
1410
0
        struct Variable {
1411
0
            StringView name;
1412
0
            String value;
1413
0
        };
1414
1415
0
        Vector<Variable> variables;
1416
0
        variables.ensure_capacity(vars.size());
1417
1418
0
        for (auto& var : vars)
1419
0
            variables.unchecked_append({ var.key, var.value });
1420
1421
0
        Vector<String> functions;
1422
0
        functions.ensure_capacity(m_functions.size());
1423
0
        for (auto& function : m_functions)
1424
0
            functions.unchecked_append(TRY(serialize_function_definition(function.value)));
1425
1426
0
        quick_sort(variables, [](auto& a, auto& b) { return a.name < b.name; });
1427
0
        quick_sort(functions, [](auto& a, auto& b) { return a < b; });
1428
1429
0
        for (auto& var : variables)
1430
0
            outln("{}={}", var.name, escape_token(var.value));
1431
1432
0
        for (auto& fn : functions)
1433
0
            outln("{}", fn);
1434
1435
0
        return 0;
1436
0
    }
1437
1438
0
    Vector<StringView> argv_to_set;
1439
1440
0
    Core::ArgsParser parser;
1441
0
    parser.set_stop_on_first_non_option(true);
1442
0
    parser.add_positional_argument(argv_to_set, "List of arguments", "arg", Core::ArgsParser::Required::No);
1443
1444
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::PrintUsage))
1445
0
        return 1;
1446
1447
0
    if (!argv_to_set.is_empty() || arguments.strings.last() == "--"sv) {
1448
0
        Vector<String> argv;
1449
0
        argv.ensure_capacity(argv_to_set.size());
1450
0
        for (auto& arg : argv_to_set)
1451
0
            argv.unchecked_append(TRY(String::from_utf8(arg)));
1452
0
        set_local_variable("ARGV", AST::make_ref_counted<AST::ListValue>(move(argv)));
1453
0
    }
1454
1455
0
    return 0;
1456
0
}
1457
1458
ErrorOr<int> Shell::builtin_not(Main::Arguments arguments)
1459
0
{
1460
0
    Vector<StringView> args;
1461
1462
0
    Core::ArgsParser parser;
1463
0
    parser.set_stop_on_first_non_option(true);
1464
0
    parser.add_positional_argument(args, "Command to run followed by its arguments", "string");
1465
1466
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
1467
0
        return 1;
1468
1469
0
    AST::Command command;
1470
0
    TRY(command.argv.try_ensure_capacity(args.size()));
1471
0
    for (auto& arg : args)
1472
0
        command.argv.unchecked_append(TRY(String::from_utf8(arg)));
1473
1474
0
    auto commands = TRY(expand_aliases({ move(command) }));
1475
0
    int exit_code = 1;
1476
0
    auto found_a_job = false;
1477
0
    for (auto& job : run_commands(commands)) {
1478
0
        found_a_job = true;
1479
0
        block_on_job(job);
1480
0
        exit_code = job->exit_code();
1481
0
    }
1482
    // In case it was a function.
1483
0
    if (!found_a_job)
1484
0
        exit_code = last_return_code.value_or(0);
1485
0
    return exit_code == 0 ? 1 : 0;
1486
0
}
1487
1488
ErrorOr<int> Shell::builtin_kill(Main::Arguments arguments)
1489
0
{
1490
    // Simply translate the arguments and pass them to `kill'
1491
0
    Vector<String> replaced_values;
1492
0
    auto kill_path_or_error = Core::System::resolve_executable_from_environment("kill"sv);
1493
0
    if (kill_path_or_error.is_error()) {
1494
0
        warnln("kill: `kill' not found in PATH");
1495
0
        return 126;
1496
0
    }
1497
1498
0
    replaced_values.append(kill_path_or_error.release_value());
1499
0
    for (size_t i = 1; i < arguments.strings.size(); ++i) {
1500
0
        if (auto job_id = resolve_job_spec(arguments.strings[i]); job_id.has_value()) {
1501
0
            auto job = find_job(job_id.value());
1502
0
            if (job) {
1503
0
                replaced_values.append(String::number(job->pid()));
1504
0
            } else {
1505
0
                warnln("kill: Job with pid {} not found", job_id.value());
1506
0
                return 1;
1507
0
            }
1508
0
        } else {
1509
0
            replaced_values.append(TRY(String::from_utf8(arguments.strings[i])));
1510
0
        }
1511
0
    }
1512
1513
    // Now just run `kill'
1514
0
    AST::Command command;
1515
0
    command.argv = move(replaced_values);
1516
0
    command.position = m_source_position.has_value() ? m_source_position->position : Optional<AST::Position> {};
1517
1518
0
    auto exit_code = 1;
1519
0
    auto job_result = run_command(command);
1520
0
    if (job_result.is_error()) {
1521
0
        warnln("kill: Failed to run {}: {}", command.argv.first(), job_result.error());
1522
0
        return exit_code;
1523
0
    }
1524
1525
0
    if (auto job = job_result.release_value()) {
1526
0
        block_on_job(job);
1527
0
        exit_code = job->exit_code();
1528
0
    }
1529
0
    return exit_code;
1530
0
}
1531
1532
ErrorOr<bool> Shell::run_builtin(const AST::Command& command, Vector<NonnullRefPtr<AST::Rewiring>> const& rewirings, int& retval)
1533
0
{
1534
0
    if (command.argv.is_empty())
1535
0
        return false;
1536
1537
0
    if (!has_builtin(command.argv.first()))
1538
0
        return false;
1539
1540
0
    Vector<StringView> arguments;
1541
0
    TRY(arguments.try_ensure_capacity(command.argv.size()));
1542
0
    for (auto& arg : command.argv)
1543
0
        arguments.unchecked_append(arg);
1544
1545
0
    Main::Arguments arguments_object {
1546
0
        .argc = 0,
1547
0
        .argv = nullptr,
1548
0
        .strings = arguments
1549
0
    };
1550
1551
0
    StringView name = command.argv.first();
1552
1553
0
    SavedFileDescriptors fds { rewirings };
1554
1555
0
    for (auto& rewiring : rewirings) {
1556
0
        int rc = dup2(rewiring->old_fd, rewiring->new_fd);
1557
0
        if (rc < 0) {
1558
0
            perror("dup2(run)");
1559
0
            return false;
1560
0
        }
1561
0
    }
1562
1563
0
    Core::EventLoop loop;
1564
0
    setup_signals();
1565
1566
0
    if (name == ":"sv)
1567
0
        name = "noop"sv;
1568
0
    else if (m_in_posix_mode && name == "."sv)
1569
0
        name = "source"sv;
1570
1571
0
#define __ENUMERATE_SHELL_BUILTIN(builtin, _mode)                        \
1572
0
    if (name == #builtin) {                                              \
1573
0
        retval = TRY(builtin_##builtin(arguments_object));               \
1574
0
        if (!has_error(ShellError::None))                                \
1575
0
            raise_error(m_error, m_error_description, command.position); \
1576
0
        fflush(stdout);                                                  \
1577
0
        fflush(stderr);                                                  \
1578
0
        return true;                                                     \
1579
0
    }
1580
1581
0
    ENUMERATE_SHELL_BUILTINS();
1582
1583
0
#undef __ENUMERATE_SHELL_BUILTIN
1584
0
    return false;
1585
0
}
1586
1587
ErrorOr<int> Shell::builtin_argsparser_parse(Main::Arguments arguments)
1588
0
{
1589
    // argsparser_parse
1590
    //   --add-option variable [--type (bool | string | i32 | u32 | double | size)] --help-string "" --long-name "" --short-name "" [--value-name "" <if not --type bool>] --list
1591
    //   --add-positional-argument variable [--type (bool | string | i32 | u32 | double | size)] ([--min n] [--max n] | [--required]) --help-string "" --value-name ""
1592
    //   [--general-help ""]
1593
    //   [--stop-on-first-non-option]
1594
    //   --
1595
    //   $args_to_parse
1596
0
    Core::ArgsParser parser;
1597
1598
0
    Core::ArgsParser user_parser;
1599
1600
0
    Vector<StringView> descriptors;
1601
0
    Variant<Core::ArgsParser::Option, Core::ArgsParser::Arg, Empty> current;
1602
0
    Vector<ByteString> help_string_storage;
1603
0
    Vector<ByteString> long_name_storage;
1604
0
    Vector<ByteString> value_name_storage;
1605
0
    Vector<ByteString> name_storage;
1606
0
    ByteString current_variable;
1607
    // if max > 1 or min < 1, or explicit `--list`.
1608
0
    bool treat_arg_as_list = false;
1609
0
    enum class Type {
1610
0
        Bool,
1611
0
        String,
1612
0
        I32,
1613
0
        U32,
1614
0
        Double,
1615
0
        Size,
1616
0
    };
1617
1618
0
    auto type = Type::String;
1619
1620
0
    auto try_convert = [](StringView value, Type type) -> ErrorOr<Optional<RefPtr<AST::Value>>> {
1621
0
        switch (type) {
1622
0
        case Type::Bool:
1623
0
            return AST::make_ref_counted<AST::StringValue>("true"_string);
1624
0
        case Type::String:
1625
0
            return AST::make_ref_counted<AST::StringValue>(TRY(String::from_utf8(value)));
1626
0
        case Type::I32:
1627
0
            if (auto number = value.to_number<int>(); number.has_value())
1628
0
                return AST::make_ref_counted<AST::StringValue>(String::number(*number));
1629
1630
0
            warnln("Invalid value for type i32: {}", value);
1631
0
            return OptionalNone {};
1632
0
        case Type::U32:
1633
0
        case Type::Size:
1634
0
            if (auto number = value.to_number<unsigned>(); number.has_value())
1635
0
                return AST::make_ref_counted<AST::StringValue>(String::number(*number));
1636
1637
0
            warnln("Invalid value for type u32|size: {}", value);
1638
0
            return OptionalNone {};
1639
0
        case Type::Double: {
1640
0
            ByteString string = value;
1641
0
            char* endptr = nullptr;
1642
0
            auto number = strtod(string.characters(), &endptr);
1643
0
            if (endptr != string.characters() + string.length()) {
1644
0
                warnln("Invalid value for type double: {}", value);
1645
0
                return OptionalNone {};
1646
0
            }
1647
1648
0
            return AST::make_ref_counted<AST::StringValue>(String::number(number));
1649
0
        }
1650
0
        default:
1651
0
            VERIFY_NOT_REACHED();
1652
0
        }
1653
0
    };
1654
1655
0
    auto enlist = [&](auto name, auto value) -> ErrorOr<NonnullRefPtr<AST::Value>> {
1656
0
        auto variable = TRY(look_up_local_variable(name));
1657
0
        if (variable) {
1658
0
            auto list = TRY(const_cast<AST::Value&>(*variable).resolve_as_list(*this));
1659
0
            auto new_value = TRY(value->resolve_as_string(*this));
1660
0
            list.append(move(new_value));
1661
0
            return try_make_ref_counted<AST::ListValue>(move(list));
1662
0
        }
1663
0
        return *value;
1664
0
    };
1665
1666
    // FIXME: We cannot return ErrorOr<T> from Core::ArgsParser::Option::accept_value(), fix the MUST's here whenever that function is ErrorOr-aware.
1667
0
    auto commit = [&] {
1668
0
        return current.visit(
1669
0
            [&](Core::ArgsParser::Option& option) {
1670
0
                if (!option.long_name && !option.short_name) {
1671
0
                    warnln("Defined option must have at least one of --long-name or --short-name");
1672
0
                    return false;
1673
0
                }
1674
0
                option.accept_value = [&, current_variable, treat_arg_as_list, type](StringView value) {
1675
0
                    auto result = MUST(try_convert(value, type));
1676
0
                    if (result.has_value()) {
1677
0
                        auto value = result.release_value();
1678
0
                        if (treat_arg_as_list)
1679
0
                            value = MUST(enlist(current_variable, move(value)));
1680
0
                        this->set_local_variable(current_variable, move(value), true);
1681
0
                        return true;
1682
0
                    }
1683
1684
0
                    return false;
1685
0
                };
1686
0
                user_parser.add_option(move(option));
1687
0
                type = Type::String;
1688
0
                treat_arg_as_list = false;
1689
0
                return true;
1690
0
            },
1691
0
            [&](Core::ArgsParser::Arg& arg) {
1692
0
                if (!arg.name) {
1693
0
                    warnln("Defined positional argument must have a name");
1694
0
                    return false;
1695
0
                }
1696
0
                arg.accept_value = [&, current_variable, treat_arg_as_list, type](StringView value) {
1697
0
                    auto result = MUST(try_convert(value, type));
1698
0
                    if (result.has_value()) {
1699
0
                        auto value = result.release_value();
1700
0
                        if (treat_arg_as_list)
1701
0
                            value = MUST(enlist(current_variable, move(value)));
1702
0
                        this->set_local_variable(current_variable, move(value), true);
1703
0
                        return true;
1704
0
                    }
1705
1706
0
                    return false;
1707
0
                };
1708
0
                user_parser.add_positional_argument(move(arg));
1709
0
                type = Type::String;
1710
0
                treat_arg_as_list = false;
1711
0
                return true;
1712
0
            },
1713
0
            [&](Empty) {
1714
0
                return true;
1715
0
            });
1716
0
    };
1717
1718
0
    parser.add_option(Core::ArgsParser::Option {
1719
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
1720
0
        .help_string = "Stop processing descriptors after a non-argument parameter is seen",
1721
0
        .long_name = "stop-on-first-non-option",
1722
0
        .accept_value = [&](auto) {
1723
0
            user_parser.set_stop_on_first_non_option(true);
1724
0
            return true;
1725
0
        },
1726
0
    });
1727
0
    parser.add_option(Core::ArgsParser::Option {
1728
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1729
0
        .help_string = "Set the general help string for the parser",
1730
0
        .long_name = "general-help",
1731
0
        .value_name = "string",
1732
0
        .accept_value = [&](StringView value) {
1733
0
            VERIFY(strlen(value.characters_without_null_termination()) == value.length());
1734
0
            user_parser.set_general_help(value.characters_without_null_termination());
1735
0
            return true;
1736
0
        },
1737
0
    });
1738
0
    parser.add_option(Core::ArgsParser::Option {
1739
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1740
0
        .help_string = "Start describing an option",
1741
0
        .long_name = "add-option",
1742
0
        .value_name = "variable-name",
1743
0
        .accept_value = [&](auto name) {
1744
0
            if (!commit())
1745
0
                return false;
1746
1747
0
            current = Core::ArgsParser::Option {};
1748
0
            current_variable = name;
1749
0
            if (current_variable.is_empty() || !all_of(current_variable, [](auto ch) { return ch == '_' || isalnum(ch); })) {
1750
0
                warnln("Option variable name must be a valid identifier");
1751
0
                return false;
1752
0
            }
1753
1754
0
            return true;
1755
0
        },
1756
0
    });
1757
0
    parser.add_option(Core::ArgsParser::Option {
1758
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
1759
0
        .help_string = "Accept multiple of the current option being given",
1760
0
        .long_name = "list",
1761
0
        .accept_value = [&](auto) {
1762
0
            if (!current.has<Core::ArgsParser::Option>()) {
1763
0
                warnln("Must be defining an option to use --list");
1764
0
                return false;
1765
0
            }
1766
0
            treat_arg_as_list = true;
1767
0
            return true;
1768
0
        },
1769
0
    });
1770
0
    parser.add_option(Core::ArgsParser::Option {
1771
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1772
0
        .help_string = "Define the type of the option or argument being described",
1773
0
        .long_name = "type",
1774
0
        .value_name = "type",
1775
0
        .accept_value = [&](StringView ty) {
1776
0
            if (current.has<Empty>()) {
1777
0
                warnln("Must be defining an argument or option to use --type");
1778
0
                return false;
1779
0
            }
1780
1781
0
            if (ty == "bool") {
1782
0
                if (auto option = current.get_pointer<Core::ArgsParser::Option>()) {
1783
0
                    if (option->value_name != nullptr) {
1784
0
                        warnln("Type 'bool' does not apply to options with a value (value name is set to {})", option->value_name);
1785
0
                        return false;
1786
0
                    }
1787
1788
0
                    option->argument_mode = Core::ArgsParser::OptionArgumentMode::None;
1789
0
                }
1790
0
                type = Type::Bool;
1791
0
            } else if (ty == "string") {
1792
0
                type = Type::String;
1793
0
            } else if (ty == "i32") {
1794
0
                type = Type::I32;
1795
0
            } else if (ty == "u32") {
1796
0
                type = Type::U32;
1797
0
            } else if (ty == "double") {
1798
0
                type = Type::Double;
1799
0
            } else if (ty == "size") {
1800
0
                type = Type::Size;
1801
0
            } else {
1802
0
                warnln("Invalid type '{}', expected one of bool | string | i32 | u32 | double | size", ty);
1803
0
                return false;
1804
0
            }
1805
1806
0
            if (type == Type::Bool) {
1807
0
                set_local_variable(
1808
0
                    current_variable,
1809
0
                    make_ref_counted<AST::StringValue>("false"_string),
1810
0
                    true);
1811
0
            }
1812
0
            return true;
1813
0
        },
1814
0
    });
1815
1816
0
    parser.add_option(Core::ArgsParser::Option {
1817
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1818
0
        .help_string = "Set the help string of the option or argument being defined",
1819
0
        .long_name = "help-string",
1820
0
        .value_name = "string",
1821
0
        .accept_value = [&](StringView value) {
1822
0
            return current.visit(
1823
0
                [](Empty) {
1824
0
                    warnln("Must be defining an option or argument to use --help-string");
1825
0
                    return false;
1826
0
                },
1827
0
                [&](auto& option) {
1828
0
                    help_string_storage.append(value);
1829
0
                    option.help_string = help_string_storage.last().characters();
1830
0
                    return true;
1831
0
                });
Unexecuted instantiation: Builtin.cpp:auto Shell::Shell::builtin_argsparser_parse(Main::Arguments)::$_6::operator()(AK::StringView) const::{lambda(auto:1&)#1}::operator()<Core::ArgsParser::Option>(Core::ArgsParser::Option&) const
Unexecuted instantiation: Builtin.cpp:auto Shell::Shell::builtin_argsparser_parse(Main::Arguments)::$_6::operator()(AK::StringView) const::{lambda(auto:1&)#1}::operator()<Core::ArgsParser::Arg>(Core::ArgsParser::Arg&) const
1832
0
        },
1833
0
    });
1834
0
    parser.add_option(Core::ArgsParser::Option {
1835
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1836
0
        .help_string = "Set the long name of the option being defined",
1837
0
        .long_name = "long-name",
1838
0
        .value_name = "name",
1839
0
        .accept_value = [&](StringView value) {
1840
0
            auto option = current.get_pointer<Core::ArgsParser::Option>();
1841
0
            if (!option) {
1842
0
                warnln("Must be defining an option to use --long-name");
1843
0
                return false;
1844
0
            }
1845
0
            if (option->long_name) {
1846
0
                warnln("Repeated application of --long-name is not allowed, current option has long name set to \"{}\"", option->long_name);
1847
0
                return false;
1848
0
            }
1849
1850
0
            long_name_storage.append(value);
1851
0
            option->long_name = long_name_storage.last().characters();
1852
0
            return true;
1853
0
        },
1854
0
    });
1855
0
    parser.add_option(Core::ArgsParser::Option {
1856
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1857
0
        .help_string = "Set the short name of the option being defined",
1858
0
        .long_name = "short-name",
1859
0
        .value_name = "char",
1860
0
        .accept_value = [&](StringView value) {
1861
0
            auto option = current.get_pointer<Core::ArgsParser::Option>();
1862
0
            if (!option) {
1863
0
                warnln("Must be defining an option to use --short-name");
1864
0
                return false;
1865
0
            }
1866
0
            if (value.length() != 1) {
1867
0
                warnln("Option short name ('{}') must be exactly one character long", value);
1868
0
                return false;
1869
0
            }
1870
0
            if (option->short_name) {
1871
0
                warnln("Repeated application of --short-name is not allowed, current option has short name set to '{}'", option->short_name);
1872
0
                return false;
1873
0
            }
1874
0
            option->short_name = value[0];
1875
0
            return true;
1876
0
        },
1877
0
    });
1878
0
    parser.add_option(Core::ArgsParser::Option {
1879
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1880
0
        .help_string = "Set the value name of the option being defined",
1881
0
        .long_name = "value-name",
1882
0
        .value_name = "string",
1883
0
        .accept_value = [&](StringView value) {
1884
0
            return current.visit(
1885
0
                [](Empty) {
1886
0
                    warnln("Must be defining an option or a positional argument to use --value-name");
1887
0
                    return false;
1888
0
                },
1889
0
                [&](Core::ArgsParser::Option& option) {
1890
0
                    if (option.value_name) {
1891
0
                        warnln("Repeated application of --value-name is not allowed, current option has value name set to \"{}\"", option.value_name);
1892
0
                        return false;
1893
0
                    }
1894
0
                    if (type == Type::Bool) {
1895
0
                        warnln("Options of type bool cannot have a value name");
1896
0
                        return false;
1897
0
                    }
1898
1899
0
                    value_name_storage.append(value);
1900
0
                    option.value_name = value_name_storage.last().characters();
1901
0
                    return true;
1902
0
                },
1903
0
                [&](Core::ArgsParser::Arg& arg) {
1904
0
                    if (arg.name) {
1905
0
                        warnln("Repeated application of --value-name is not allowed, current argument has value name set to \"{}\"", arg.name);
1906
0
                        return false;
1907
0
                    }
1908
1909
0
                    name_storage.append(value);
1910
0
                    arg.name = name_storage.last().characters();
1911
0
                    return true;
1912
0
                });
1913
0
        },
1914
0
    });
1915
0
    parser.add_option(Core::ArgsParser::Option {
1916
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1917
0
        .help_string = "Start describing a positional argument",
1918
0
        .long_name = "add-positional-argument",
1919
0
        .value_name = "variable",
1920
0
        .accept_value = [&](auto value) {
1921
0
            if (!commit())
1922
0
                return false;
1923
1924
0
            current = Core::ArgsParser::Arg {};
1925
0
            current_variable = value;
1926
0
            if (current_variable.is_empty() || !all_of(current_variable, [](auto ch) { return ch == '_' || isalnum(ch); })) {
1927
0
                warnln("Argument variable name must be a valid identifier");
1928
0
                return false;
1929
0
            }
1930
1931
0
            return true;
1932
0
        },
1933
0
    });
1934
0
    parser.add_option(Core::ArgsParser::Option {
1935
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1936
0
        .help_string = "Set the minimum required number of positional descriptors for the argument being described",
1937
0
        .long_name = "min",
1938
0
        .value_name = "n",
1939
0
        .accept_value = [&](StringView value) {
1940
0
            auto arg = current.get_pointer<Core::ArgsParser::Arg>();
1941
0
            if (!arg) {
1942
0
                warnln("Must be describing a positional argument to use --min");
1943
0
                return false;
1944
0
            }
1945
1946
0
            auto number = value.to_number<unsigned>();
1947
0
            if (!number.has_value()) {
1948
0
                warnln("Invalid value for --min: '{}', expected a non-negative number", value);
1949
0
                return false;
1950
0
            }
1951
1952
0
            if (static_cast<unsigned>(arg->max_values) < *number) {
1953
0
                warnln("Invalid value for --min: {}, min must not be larger than max ({})", *number, arg->max_values);
1954
0
                return false;
1955
0
            }
1956
1957
0
            arg->min_values = *number;
1958
0
            treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
1959
0
            return true;
1960
0
        },
1961
0
    });
1962
0
    parser.add_option(Core::ArgsParser::Option {
1963
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
1964
0
        .help_string = "Set the maximum required number of positional descriptors for the argument being described",
1965
0
        .long_name = "max",
1966
0
        .value_name = "n",
1967
0
        .accept_value = [&](StringView value) {
1968
0
            auto arg = current.get_pointer<Core::ArgsParser::Arg>();
1969
0
            if (!arg) {
1970
0
                warnln("Must be describing a positional argument to use --max");
1971
0
                return false;
1972
0
            }
1973
1974
0
            auto number = value.to_number<unsigned>();
1975
0
            if (!number.has_value()) {
1976
0
                warnln("Invalid value for --max: '{}', expected a non-negative number", value);
1977
0
                return false;
1978
0
            }
1979
1980
0
            if (static_cast<unsigned>(arg->min_values) > *number) {
1981
0
                warnln("Invalid value for --max: {}, max must not be smaller than min ({})", *number, arg->min_values);
1982
0
                return false;
1983
0
            }
1984
1985
0
            arg->max_values = *number;
1986
0
            treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
1987
0
            return true;
1988
0
        },
1989
0
    });
1990
0
    parser.add_option(Core::ArgsParser::Option {
1991
0
        .argument_mode = Core::ArgsParser::OptionArgumentMode::None,
1992
0
        .help_string = "Mark the positional argument being described as required (shorthand for --min 1)",
1993
0
        .long_name = "required",
1994
0
        .accept_value = [&](auto) {
1995
0
            auto arg = current.get_pointer<Core::ArgsParser::Arg>();
1996
0
            if (!arg) {
1997
0
                warnln("Must be describing a positional argument to use --required");
1998
0
                return false;
1999
0
            }
2000
0
            arg->min_values = 1;
2001
0
            if (arg->max_values < arg->min_values)
2002
0
                arg->max_values = 1;
2003
0
            treat_arg_as_list = arg->max_values > 1 || arg->min_values < 1;
2004
0
            return true;
2005
0
        },
2006
0
    });
2007
0
    parser.add_positional_argument(descriptors, "Arguments to parse via the described ArgsParser configuration", "arg", Core::ArgsParser::Required::No);
2008
2009
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
2010
0
        return 2;
2011
2012
0
    if (!commit())
2013
0
        return 2;
2014
2015
0
    if (!user_parser.parse(descriptors, Core::ArgsParser::FailureBehavior::Ignore))
2016
0
        return 1;
2017
2018
0
    return 0;
2019
0
}
2020
2021
ErrorOr<int> Shell::builtin_read(Main::Arguments arguments)
2022
0
{
2023
0
    bool no_escape = false;
2024
0
    Vector<ByteString> variables;
2025
2026
0
    Core::ArgsParser parser;
2027
0
    parser.add_option(no_escape, "Do not interpret backslash escapes", "no-escape", 'r');
2028
0
    parser.add_positional_argument(variables, "Variables to read into", "variable", Core::ArgsParser::Required::Yes);
2029
2030
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
2031
0
        return 1;
2032
2033
0
    auto split_by_any_of = " \t\n"_string;
2034
2035
0
    if (auto const* value_from_env = getenv("IFS"); value_from_env)
2036
0
        split_by_any_of = TRY(String::from_utf8({ value_from_env, strlen(value_from_env) }));
2037
0
    else if (auto split_by_variable = TRY(look_up_local_variable("IFS"sv)); split_by_variable)
2038
0
        split_by_any_of = TRY(const_cast<AST::Value&>(*split_by_variable).resolve_as_string(*this));
2039
2040
0
    auto file = TRY(Core::File::standard_input());
2041
0
    auto buffered_stream = TRY(Core::InputBufferedFile::create(move(file)));
2042
2043
0
    StringBuilder builder;
2044
0
    ByteBuffer buffer;
2045
2046
0
    enum class LineState {
2047
0
        Done,
2048
0
        EscapedNewline,
2049
0
    };
2050
0
    auto read_line = [&]() -> ErrorOr<LineState> {
2051
0
        if (m_is_interactive && isatty(STDIN_FILENO)) {
2052
            // Show prompt
2053
0
            warn("read: ");
2054
0
        }
2055
0
        size_t attempted_line_size = 32;
2056
2057
0
        for (;;) {
2058
0
            auto result = buffered_stream->read_line(TRY(buffer.get_bytes_for_writing(attempted_line_size)));
2059
0
            if (result.is_error() && result.error().is_errno() && result.error().code() == EMSGSIZE) {
2060
0
                attempted_line_size *= 2;
2061
0
                continue;
2062
0
            }
2063
2064
0
            auto used_bytes = TRY(move(result));
2065
0
            if (!no_escape && used_bytes.ends_with("\\\n"sv)) {
2066
0
                builder.append(used_bytes.substring_view(0, used_bytes.length() - 2));
2067
0
                return LineState::EscapedNewline;
2068
0
            }
2069
2070
0
            if (used_bytes.ends_with("\n"sv))
2071
0
                used_bytes = used_bytes.substring_view(0, used_bytes.length() - 1);
2072
2073
0
            builder.append(used_bytes);
2074
0
            return LineState::Done;
2075
0
        }
2076
0
    };
2077
2078
0
    LineState state;
2079
0
    do {
2080
0
        state = TRY(read_line());
2081
0
    } while (state == LineState::EscapedNewline);
2082
2083
0
    auto line = builder.string_view();
2084
0
    if (variables.size() == 1) {
2085
0
        set_local_variable(variables[0], make_ref_counted<AST::StringValue>(TRY(String::from_utf8(line))));
2086
0
        return 0;
2087
0
    }
2088
2089
0
    auto fields = line.split_view_if(is_any_of(split_by_any_of), SplitBehavior::KeepEmpty);
2090
2091
0
    for (size_t i = 0; i < variables.size(); ++i) {
2092
0
        auto& variable = variables[i];
2093
0
        StringView variable_value;
2094
0
        if (i >= fields.size())
2095
0
            variable_value = ""sv;
2096
0
        else if (i == variables.size() - 1)
2097
0
            variable_value = line.substring_view_starting_from_substring(fields[i]);
2098
0
        else
2099
0
            variable_value = fields[i];
2100
2101
0
        set_local_variable(variable, make_ref_counted<AST::StringValue>(TRY(String::from_utf8(variable_value))));
2102
0
    }
2103
2104
0
    return 0;
2105
0
}
2106
2107
ErrorOr<int> Shell::builtin_run_with_env(Main::Arguments arguments)
2108
0
{
2109
0
    Vector<ByteString> environment_variables;
2110
0
    Vector<StringView> command_and_arguments;
2111
2112
0
    Core::ArgsParser parser;
2113
0
    parser.add_option(environment_variables, "Environment variables to set", "env", 'e', "NAME=VALUE");
2114
0
    parser.add_positional_argument(command_and_arguments, "Command and arguments to run", "command", Core::ArgsParser::Required::Yes);
2115
0
    parser.set_stop_on_first_non_option(true);
2116
2117
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
2118
0
        return 1;
2119
2120
0
    if (command_and_arguments.is_empty()) {
2121
0
        warnln("run_with_env: No command to run");
2122
0
        return 1;
2123
0
    }
2124
2125
0
    AST::Command command;
2126
0
    TRY(command.argv.try_ensure_capacity(command_and_arguments.size()));
2127
0
    for (auto& arg : command_and_arguments)
2128
0
        command.argv.append(TRY(String::from_utf8(arg)));
2129
2130
0
    auto commands = TRY(expand_aliases({ move(command) }));
2131
2132
0
    HashMap<ByteString, Optional<ByteString>> old_environment_entries;
2133
0
    for (auto& variable : environment_variables) {
2134
0
        auto parts = variable.split_limit('=', 2, SplitBehavior::KeepEmpty);
2135
0
        if (parts.size() != 2) {
2136
0
            warnln("run_with_env: Invalid environment variable: '{}'", variable);
2137
0
            return 1;
2138
0
        }
2139
2140
0
        ByteString name = parts[0];
2141
0
        old_environment_entries.set(name, getenv(name.characters()) ?: Optional<ByteString> {});
2142
2143
0
        ByteString value = parts[1];
2144
0
        setenv(name.characters(), value.characters(), 1);
2145
0
    }
2146
2147
0
    int exit_code = 0;
2148
0
    for (auto& job : run_commands(commands)) {
2149
0
        block_on_job(job);
2150
0
        exit_code = job->exit_code();
2151
0
    }
2152
2153
0
    for (auto& entry : old_environment_entries) {
2154
0
        if (entry.value.has_value())
2155
0
            setenv(entry.key.characters(), entry.value->characters(), 1);
2156
0
        else
2157
0
            unsetenv(entry.key.characters());
2158
0
    }
2159
2160
0
    return exit_code;
2161
0
}
2162
2163
ErrorOr<int> Shell::builtin_shell_set_active_prompt(Main::Arguments arguments)
2164
0
{
2165
0
    StringView new_prompt;
2166
2167
0
    Core::ArgsParser parser;
2168
0
    parser.add_positional_argument(new_prompt, "New prompt text", "prompt", Core::ArgsParser::Required::Yes);
2169
2170
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
2171
0
        return 1;
2172
2173
0
    if (!m_editor) {
2174
0
        warnln("shell_set_active_prompt: No active prompt");
2175
0
        return 1;
2176
0
    }
2177
2178
0
    if (m_editor->is_editing())
2179
0
        m_editor->set_prompt(new_prompt);
2180
0
    else
2181
0
        m_next_scheduled_prompt_text = new_prompt;
2182
0
    return 0;
2183
0
}
2184
2185
ErrorOr<int> Shell::builtin_in_parallel(Main::Arguments arguments)
2186
0
{
2187
0
    unsigned max_jobs = 1;
2188
0
    Vector<StringView> command_and_arguments;
2189
2190
0
#ifdef _SC_NPROCESSORS_ONLN
2191
0
    max_jobs = sysconf(_SC_NPROCESSORS_ONLN);
2192
0
#endif
2193
2194
0
    Core::ArgsParser parser;
2195
0
    parser.set_general_help("Run the given command in the background, allowing at most <N> jobs running at once.");
2196
0
    parser.add_option(max_jobs, "Maximum number of jobs to run in parallel", "max-jobs", 'j', "N");
2197
0
    parser.add_positional_argument(command_and_arguments, "Command and arguments to run", "argument", Core::ArgsParser::Required::Yes);
2198
0
    parser.set_stop_on_first_non_option(true);
2199
2200
0
    if (!parser.parse(arguments, Core::ArgsParser::FailureBehavior::Ignore))
2201
0
        return 1;
2202
2203
0
    if (command_and_arguments.is_empty()) {
2204
0
        warnln("in_parallel: No command to run");
2205
0
        return 1;
2206
0
    }
2207
2208
0
    AST::Command command;
2209
0
    TRY(command.argv.try_ensure_capacity(command_and_arguments.size()));
2210
0
    for (auto& arg : command_and_arguments)
2211
0
        command.argv.append(TRY(String::from_utf8(arg)));
2212
2213
0
    auto commands = TRY(expand_aliases({ move(command) }));
2214
2215
0
    Vector<AST::Command> commands_to_run;
2216
0
    for (auto& command : commands) {
2217
0
        if (command.argv.is_empty())
2218
0
            continue;
2219
0
        command.should_notify_if_in_background = false;
2220
0
        command.should_wait = false;
2221
0
        commands_to_run.append(move(command));
2222
0
    }
2223
2224
0
    if (commands_to_run.is_empty()) {
2225
0
        warnln("in_parallel: No command to run");
2226
0
        return 1;
2227
0
    }
2228
2229
0
    Core::EventLoop loop;
2230
0
    loop.spin_until([&] { return jobs.size() + commands_to_run.size() <= max_jobs; });
2231
0
    run_commands(commands_to_run);
2232
0
    return 0;
2233
0
}
2234
2235
bool Shell::has_builtin(StringView name) const
2236
0
{
2237
0
    if (name == ":"sv || (m_in_posix_mode && name == "."sv))
2238
0
        return true;
2239
2240
0
#define __ENUMERATE_SHELL_BUILTIN(builtin, mode)                            \
2241
0
    if (name == #builtin) {                                                 \
2242
0
        if (POSIXModeRequirement::mode == POSIXModeRequirement::InAllModes) \
2243
0
            return true;                                                    \
2244
0
        return m_in_posix_mode;                                             \
2245
0
    }
2246
2247
0
    ENUMERATE_SHELL_BUILTINS();
2248
2249
0
#undef __ENUMERATE_SHELL_BUILTIN
2250
0
    return false;
2251
0
}
2252
}