Commit Graph

355 Commits

Author SHA1 Message Date
Ali Mohammad Pur
5f950df3d4 Shell: Make Immediate expression invocation fallible
This removes a whole bunch of FIXMEs in the immediate expr
implementations as well :^)
2023-02-28 15:52:24 +03:30
Ali Mohammad Pur
007767fc14 Shell: Convert builtins to use the modern main() style
That is, return ErrorOr<int>, handle fallible ops with TRY() and accept
a Main::Arguments.
Note that we do not populate the argc/argv members of Main::Arguments,
so all accesses have to go through .strings.
2023-02-28 15:52:24 +03:30
Ali Mohammad Pur
d575c50f3e Shell: Make AST::dump() ErrorOr-aware 2023-02-28 15:52:24 +03:30
Ali Mohammad Pur
beeb58bd93 Shell+LibCodeComprehension: Start replacing {Deprecated => }String
This starts by switching all AST members to Strings, and dealing with
the fallout.
2023-02-28 15:52:24 +03:30
Andreas Kling
68b5df6bf1 Shell: Fix (and paper over) various const-correctness issues 2023-02-21 00:54:04 +01:00
Ali Mohammad Pur
99d264afbe Shell: Correct the out-of-bounds expansion bailing condition
Also adds a couple (useful) debug prints which helped track down the
problem.
2023-02-18 06:55:46 +03:30
Ali Mohammad Pur
d56fbaa7e8 Shell: Allow underscores in normal expansion names 2023-02-18 06:55:46 +03:30
Ali Mohammad Pur
a6d77162f4 Shell: Correctly keep track of special parameter length
We were previously treating special expansions (e.g. $#) as zero-length
expansions, which made the shell repeat them literally after expanding
them.
2023-02-18 06:55:46 +03:30
Ali Mohammad Pur
6da438e992 Shell: Clear expansions after committing a word in the POSIX parser 2023-02-18 06:55:46 +03:30
Ali Mohammad Pur
2881bb4c3a Shell: Add support for heredocs to the POSIX parser 2023-02-18 06:55:46 +03:30
Ali Mohammad Pur
a5e4bc4faf Shell: Add a '--posix' mode to the 'dump' builtin 2023-02-18 06:55:46 +03:30
Ali Mohammad Pur
4efc632e15 Shell: Allow the heredoc node to act as a redirection too
This will be used in a future commit to implement POSIX sh heredocs.
2023-02-18 06:55:46 +03:30
Ali Mohammad Pur
eb20fbe145 Everywhere: Use /bin/Shell as the shebang for Shell scripts 2023-02-13 23:00:15 +03:30
Ali Mohammad Pur
beaae6b420 Shell: Use the POSIX parser if run as /bin/sh or passed the --posix flag
Note that the default shellrc is most likely not valid posix sh code, so
passing --skip-shellrc is suggested until we come up with a separate
shellrc file for the POSIX parser to use when interactive.
2023-02-13 23:00:15 +03:30
Ali Mohammad Pur
2a276c86d4 Shell: Start implementing a POSIX-compliant parser
The parser is still very much a work-in-progress, but it can currently
parse most of the basic bits, the only *completely* unimplemented things
in the parser are:
- heredocs (io_here)
- alias expansion
- arithmetic expansion

There are a whole suite of bugs, and syntax highlighting is unreliable
at best.
For now, this is not attached anywhere, a future commit will enable it
for /bin/sh or a `Shell --posix` invocation.
2023-02-13 23:00:15 +03:30
Tim Schumacher
874c7bba28 LibCore: Remove Stream.h 2023-02-13 00:50:07 +00:00
Tim Schumacher
d43a7eae54 LibCore: Rename File to DeprecatedFile
As usual, this removes many unused includes and moves used includes
further down the chain.
2023-02-13 00:50:07 +00:00
Tim Schumacher
093cf428a3 AK: Move memory streams from LibCore 2023-01-29 19:16:44 -07:00
Linus Groh
6e7459322d AK: Remove StringBuilder::build() in favor of to_deprecated_string()
Having an alias function that only wraps another one is silly, and
keeping the more obvious name should flush out more uses of deprecated
strings.
No behavior change.
2023-01-27 20:38:49 +00:00
Sam Atkins
95b1cf2dcd Shell: Replace uses of JsonObject::get_deprecated()/get_ptr() 2023-01-27 08:07:24 -05:00
Sam Atkins
1dd6b7f5b7 AK+Everywhere: Rename JsonObject::get() to ::get_deprecated()
This is a preparatory step to making `get()` return `ErrorOr`.
2023-01-17 19:52:52 -05:00
Tim Schumacher
2150e1b3a5 Shell: Use AllocatingMemoryStream to search for the IFS 2023-01-14 00:33:35 +03:30
Sam Atkins
a8cf0c9371 LibCore+Userland: Make Core::Timer::create_single_shot() return ErrorOr
clang-format sure has some interesting opinions about where to put a
method call that comes after a lambda. :thonk:
2023-01-12 11:25:51 +01:00
Andrew Kaster
a492e2018d Userland: Silence warnings from ElapsedTimer::elapsed() type change
We changed elapsed() to return i64 instead of int as that's what
AK::Time::to_milliseconds() returns, causing a bunch of implicit lossy
conversions in callers. Clean those up with a mix of type changes and
casts.
2023-01-07 14:51:04 +01:00
Ben Wiederhake
b83cb09db1 Everywhere: Fix badly-formatted includes
In 7c5e30daaa, the focus was "only" on
Userland/Libraries/, whereas this commit cleans up the remaining
headers in the repo, and any new badly-formatted include.
2023-01-02 11:06:15 -05:00
Vetrox
0e26f2657e Shell: Add where builtin
The builtin is based on the behaviour of the z-shell.
Namely it tries to resolve every argument one by one.

When resolving (in the order below) the following results can occur:
  1. The argument is a shell built-in command. Then print it.
  2. The argument is an alias. In this case we print the mapped value.
  3. The argument was found in the `PATH` environment variable.
     In this case we print the resolved absolute path
     and try to find more occurences in the `PATH` environment variable.
  4. None of the above. If no earlier argument got resolved,
     we print the error `{argument} not found`.

If at least one argument got resolved we exit with exit code 0,
otherwise 1.

By not using Core::File to resolve the executable in the environment
but rather using a modified version of the code we print every
matching executable of the given name. This behaviour matches
up with the z-shell.

The builtin has the following flags to modify the behaviour according
to the users needs:
  - `-p --path-only`: This skips the built-in and alias checks
  (step 1 & 2)
  - `-s --follow-symlink`: This follows the symlinks of an executable to
  its symlink-free location.
  - `-w --type`: This displays the type of the found object
  without any additional descriptive information.
2022-12-27 07:25:42 +03:30
Ali Mohammad Pur
4311c2164e Shell: Disable interactive mode on '-c'
This also disables the full suite of interactive stuff in LibLine.
2022-12-12 13:57:06 +00:00
Linus Groh
57dc179b1f Everywhere: Rename to_{string => deprecated_string}() where applicable
This will make it easier to support both string types at the same time
while we convert code, and tracking down remaining uses.

One big exception is Value::to_string() in LibJS, where the name is
dictated by the ToString AO.
2022-12-06 08:54:33 +01:00
Linus Groh
6e19ab2bbc AK+Everywhere: Rename String to DeprecatedString
We have a new, improved string type coming up in AK (OOM aware, no null
state), and while it's going to use UTF-8, the name UTF8String is a
mouthful - so let's free up the String name by renaming the existing
class.
Making the old one have an annoying name will hopefully also help with
quick adoption :^)
2022-12-06 08:54:33 +01:00
Kyle Lanmon
31290c8527 LibSyntax: Teach each highlighter about it's comment syntax 2022-11-27 18:28:43 -07:00
Ali Mohammad Pur
77cc8c5612 Shell: Re-block SIGTT{IN,OU} on start
This also shows up when trying to read from a 0x0 buffer as it has no
PTY attached, avoid the mess by just blocking them (instead of ignoring
them).
2022-11-03 00:01:42 +03:30
Tim Schumacher
ce2f1b845f Everywhere: Mark dependencies of most targets as PRIVATE
Otherwise, we end up propagating those dependencies into targets that
link against that library, which creates unnecessary link-time
dependencies.

Also included are changes to readd now missing dependencies to tools
that actually need them.
2022-11-01 14:49:09 +00:00
demostanis
3e8b5ac920 AK+Everywhere: Turn bool keep_empty to an enum in split* functions 2022-10-24 23:29:18 +01:00
Andrew Kaster
1ae0cfd08b CMake+Userland: Use CMakeLists from Userland to build Lagom Libraries
Also do this for Shell.

This greatly simplifies the CMakeLists in Lagom, replacing many glob
patterns with a big list of libraries. There are still a few special
libraries that need some help to conform to the pattern, like LibELF and
LibWebView.

It also lets us remove essentially all of the Serenity or Lagom binary
directory detection logic from code generators, as now both projects
directories enter the generator logic from the same place.
2022-10-16 16:36:39 +02:00
Andrew Kaster
539fb08551 Userland: Remove unecessary uses of __serenity__ macro 2022-10-10 12:23:12 +02:00
Andrew Kaster
828441852f Everywhere: Replace uses of __serenity__ with AK_OS_SERENITY
Now that we have OS macros for essentially every supported OS, let's try
to use them everywhere.
2022-10-10 12:23:12 +02:00
networkException
4230dbbb21 AK+Everywhere: Replace "protocol" with "scheme" url helpers
URL had properly named replacements for protocol(), set_protocol() and
create_with_file_protocol() already. This patch removes these function
and updates all call sites to use the functions named according to the
specification.

See https://url.spec.whatwg.org/#concept-url-scheme
2022-09-29 09:39:04 +01:00
Ben Wiederhake
79ec6ed03d Shell: Fix 'Command:' output for built-in 'time' command 2022-09-16 05:38:09 +00:00
Brian Gianforcaro
d0a1775369 Everywhere: Fix a variety of typos
Spelling fixes found by `codespell`.
2022-09-14 04:46:49 +00:00
Ben Wiederhake
0e901f8c68 Shell: Sort CompletionSuggestions for paths lexicographically
This used to be ordered by inode, which can be surprising.
2022-09-12 16:49:48 +01:00
Sam Atkins
edc3ed2a0e AK: Allow creating NonnullPtrVectors from an initializer list
This was present in Vector already. Clang-format fixed some const
positions automatically too.

Also removed a now-ambiguous and unnecessary constructor from Shell.
2022-09-08 18:53:08 +02:00
Tim Schumacher
5f99934dce Userland: Consolidate most PATH resolving into a single implementation
We previously had at least three different implementations for resolving
executables in the PATH, all of which had slightly different
characteristics.

Merge those into a single implementation to keep the behaviour
consistent, and maybe to make that implementation more configurable in
the future.
2022-08-23 19:00:04 +01:00
Tim Schumacher
39a3775f48 Userland: Rely on a single authoritative source for the default PATH 2022-08-23 19:00:04 +01:00
Ali Mohammad Pur
c90cf67dc6 Shell: Avoid StringView OOB access in Formatter ctor 2022-08-11 14:12:55 +00:00
Ali Mohammad Pur
bbce061a61 Shell: Stop printing 'sh -c' commands
That's getting too spammy and too useless.
2022-08-11 14:12:55 +00:00
sin-ack
fbf91f41e7 Shell: Add the |& construct for piping stderr along with stdout
When |& is typed, stderr will be piped to stdout before the actual
piping happens. This behaves basically like a 2>&1 | (and the
underlying implementation transforms it to that anyway).
2022-07-17 00:51:31 +00:00
Tim Schumacher
3d51642037 LibCore: Replace the ArgsParser option argument setting with an enum
Replacement conditions for `requires_argument` have been chosen based
on what would be most convenient for implementing an eventual optional
argument mode.
2022-07-14 00:24:24 +01:00
sin-ack
c8585b77d2 Everywhere: Replace single-char StringView op. arguments with chars
This prevents us from needing a sv suffix, and potentially reduces the
need to run generic code for a single character (as contains,
starts_with, ends_with etc. for a char will be just a length and
equality check).

No functional changes.
2022-07-12 23:11:35 +02:00
sin-ack
3f3f45580a Everywhere: Add sv suffix to strings relying on StringView(char const*)
Each of these strings would previously rely on StringView's char const*
constructor overload, which would call __builtin_strlen on the string.
Since we now have operator ""sv, we can replace these with much simpler
versions. This opens the door to being able to remove
StringView(char const*).

No functional changes.
2022-07-12 23:11:35 +02:00
sin-ack
c70f45ff44 Everywhere: Explicitly specify the size in StringView constructors
This commit moves the length calculations out to be directly on the
StringView users. This is an important step towards the goal of removing
StringView(char const*), as it moves the responsibility of calculating
the size of the string to the user of the StringView (which will prevent
naive uses causing OOB access).
2022-07-12 23:11:35 +02:00
sin-ack
60f6bc902b Userland: Convert command line arguments to String/StringView
StringView was used where possible. Some utilities still use libc
functions which expect null-terminated strings, so String objects were
used there instead.
2022-07-12 23:11:35 +02:00
Tim Schumacher
84e1017272 Userland: Add /usr/local/sbin to PATH by default
`e2fsprogs` adds its tools there.
2022-07-08 12:04:01 +02:00
Ali Mohammad Pur
6e24d845e0 Shell: Immediately resolve value when setting a variable
The lazy resolution mechanism made it so that the variables were linked
together, causing unexpected behaviour:

    true
    x=$? # expected: x=0
    false
    echo $x # expected: 0, actual: 1
2022-07-04 10:23:15 +00:00
Ali Mohammad Pur
d338d2b59b Shell: Ignore SIGCHLD after a few unsuccessful attempts at handling it
As noted by the comment, a stray SIGCHLD can make the shell go into an
infinite loop, pretend the signal doesn't exist after trying 10 times in
5ms.
2022-06-24 22:53:16 +01:00
Itamar
b35293d945 LibCodeComprehension: Re-organize code comprehension related code
This moves all code comprehension-related code to a new library,
LibCodeComprehension.

This also moves some types related to code comprehension tasks (such as
autocomplete, find declaration) out of LibGUI and into
LibCodeComprehension.
2022-05-21 18:15:58 +02:00
ForLoveOfCats
99c0b895fe Shell: Highlight commands with a hyperlink to open their help pages 2022-04-21 09:12:37 +04:30
Ali Mohammad Pur
ae27d7e442 Shell: Make program-based completion with no actual token possible
31ca48e made this default to paths, but now that we have a few sensible
ways to complete things, let's make those work too.
For instance, prior to this `kill <tab>` would've suggested paths, but
now it will suggest processes.
2022-04-18 19:53:10 +04:30
Ali Mohammad Pur
1699ddc186 LibLine: Make it possible to avoid autocompletion if requested
Setting 'allow_commit_without_listing' to false will now make LibLine
show the suggestion before actually committing to it; this is useful for
completions that will replace all the user input, where mistakes can go
unnoticed without some visual cue.
2022-04-18 19:53:10 +04:30
Ali Mohammad Pur
d5b3998d23 LibLine: Respect the provided completion static offset
Now that we can resolve these correctly and they're per-suggestion, we
can finally use them for their intended purpose of letting suggestions
overwrite stuff in the buffer.
2022-04-18 19:53:10 +04:30
Ali Mohammad Pur
4ea9ca06b4 Shell: Allow completions to request further action from the shell
The shell now expects a JSON object of the form {"kind":<kind>,...} per
line in the standard output of the completion process, where 'kind' is
one of:
- "plain": Just a plain suggestion.
- "program": Prompts the shell to complete a program name starting with
  the given "name".
- "proxy": Prompts the shell to act as if a completion for "argv" was
  requested.
- "path": Prompts the shell to complete a path given the "base" and
  "part" (same as completing part in cwd=base).
2022-04-18 19:53:10 +04:30
Ali Mohammad Pur
4ede121d31 Shell: Add support for regex match patterns
We previously allowed globs as match pattern, but for more complex
matching needs, it's nice to have regular expressions.
And as the existing "name a part of the match" concept maps nicely to
named capture groups, we can simply reuse the same code and make groups
with names available in the match body.
2022-04-18 19:53:10 +04:30
Damien Firmenich
31ca48ebb2 Shell: Complete for current path when the text is empty
For example, when typing `cd <tab>`, the shell will show a list of
files in the current directory. This behavior is similar to typing `cd
./<tab>`.

It makes it easier to `cd` into directories without having to list them
first.
2022-04-15 13:08:41 +04:30
Sam Atkins
84b67754c0 Shell: Read script arguments as Strings instead of char*s
This saves work in places that previously had to create a
`Vector<String>` anyway, or repeatedly cast the char* to a String.
Plus, Strings are nicer than char*. :^)
2022-04-11 21:09:42 +02:00
Simon Wanner
206d6ece55 LibGfx: Move other font-related files to LibGfx/Font/ 2022-04-09 23:48:18 +02:00
Brian Gianforcaro
4d0317ae7a Shell: Use default execpromises parameter to pledge(..) 2022-04-03 17:13:51 -07:00
Humberto Alves
5506932788 Shell: Refresh PATH cache after running shellrc files
This fixes the highlight of runnable commands, whenever PATH variable
is changed in one of the shellrc files.
2022-04-03 23:28:01 +02:00
Idan Horowitz
086969277e Everywhere: Run clang-format 2022-04-01 21:24:45 +01:00
Ali Mohammad Pur
e1cf51b0bd Shell: Add a shell option for autocompleting via the program itself
This feature needs a bit more work, so let's disable it by default.
Note that the shell will still use _complete_foo if it is defined
regardless of this setting.
2022-03-29 15:42:55 +02:00
Ali Mohammad Pur
5e541aaebd Shell: Keep the stdio and rpath pledges for execute_process()
If the command fails, we'd like to still be capable of printing out
diagnostics, so restore stdio and rpath.
Fixes #13281.
2022-03-27 21:05:44 +02:00
Ali Mohammad Pur
f12d81ddf5 Shell: Limit the access of processes spawned for autocompletion
This commit limits the autocomplete processes to effectively have
readonly access to the fs, and only enough pledges to get the dynamic
loader working.
2022-03-26 21:34:56 +04:30
Ali Mohammad Pur
ef5523231c Shell+LibCore: Provide argument help strings as display trivia 2022-03-26 21:34:56 +04:30
Ali Mohammad Pur
9453e0e6d2 Shell: Add an ArgsParser-based argument parser builtin
Afterall, why _shouldn't_ Shell functions have nice interfaces?
also helps with autocompletion :^)
2022-03-26 21:34:56 +04:30
Ali Mohammad Pur
7e4cc187d9 Shell: Implement program-aware autocompletion
A program can either respond to `--complete -- some args to complete`
directly, or add a `_complete_<program name>` invokable (i.e. shell
function, or just a plain binary in PATH) that completes the given
command and lists the completions on stdout.
Should such a completion fail or yield no results, we'll fall back to
the previous completion algorithm.
2022-03-26 21:34:56 +04:30
Ali Mohammad Pur
e6bd1f8807 Shell: Add the 'join' and 'filter_glob' immediate functions
'split' was missing its other half, and to avoid globbing the
filesystem, let's keep the globbing to shell-internal state.
2022-03-26 21:34:56 +04:30
Lenny Maiorani
dd05934539 Shell: Use default constructors/destructors
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#cother-other-default-operation-rules

"The compiler is more likely to get the default semantics right and
you cannot implement these functions better than the compiler."
2022-03-24 20:09:26 -07:00
Tim Schumacher
83609adbdf Shell: Stop parsing options after the script name 2022-03-11 08:41:21 +03:30
Ali Mohammad Pur
a76730823a Shell: Be more smart with pasted stuff
Shell can now use LibLine's `on_paste` hook to more intelligently escape
pasted data, with the following heuristics:
- If the current command is invalid, just pile the pasted string on top
- If the cursor is *after* a command node, escape the pasted data,
  whichever way yields a smaller encoding
- If the cursor is at the start of or in the middle of a command name,
  paste the data as-is, assuming that the user wants to paste code
- If the cursor is otherwise in some argument, escape the pasted data
  according to which kind of string the cursor is in the middle of
  (double-quoted, single-quoted or a simple bareword)
2022-03-06 13:20:41 +01:00
Ali Mohammad Pur
c4d9377477 Shell: Implement leftmost_trivial_literal() for Sequence nodes 2022-03-06 13:20:41 +01:00
Ali Mohammad Pur
0ea775f257 Shell: Allow completing StringLiterals as paths
This auto-escapes the token as well :^)
2022-03-06 13:20:41 +01:00
Ali Mohammad Pur
118590325a LibLine+Userland: Make suggestion offsets per-suggestion
This allows the user to modify different parts of the input with
different suggestions.
2022-03-06 13:20:41 +01:00
kperdlich
a3ab8dcecd Shell: Use an opaque color for SyntaxError
Use an opaque color for SyntaxError in
Syntax Highlighter to avoid transparent errors.
2022-02-23 21:56:16 +00:00
Ryan Chandler
05cdfb8698 Shell: Start history counter from 1
Previously would show the list of history items starting from
an index of 0.

This is a bit misleading though. Running `!0` would actually cause
the parser to error out and prevent you from running the command.
2022-02-22 21:26:25 +03:30
kperdlich
ad722a9f06 Shell: Use an opaque default color for BarewordLiteral
Use an opaque default color for BarewordLiteral in
Syntax Highlighter to avoid transparent barewords.
2022-02-19 11:33:28 +01:00
Ali Mohammad Pur
222e580fa8 Shell: Use strncmp() instead of string.compare() for name completions
The "at most n bytes" behaviour of strncmp is required for this logic to
work, this was overlooked in 5b64abe when converting Strings to
StringViews, which lead to broken autocomplete.
2022-02-05 16:59:12 +03:30
Tom Martin
6ec4fd9d3c Shell: Add total time to builtin_time Timing Report 2022-02-04 15:09:22 +03:30
Daniel Bertalan
5b64abe76e Shell: Use StringView instead of String const& where feasible 2022-01-29 23:08:27 +01:00
Sam Atkins
45cf40653a Everywhere: Convert ByteBuffer factory methods from Optional -> ErrorOr
Apologies for the enormous commit, but I don't see a way to split this
up nicely. In the vast majority of cases it's a simple change. A few
extra places can use TRY instead of manual error checking though. :^)
2022-01-24 22:36:09 +01:00
Ali Mohammad Pur
78d1093dab Shell: Make Juxtaposition autocompletion smarter
Now something like `"$HOME"/` autocompletes correctly.
Note that only the first element of lists is used to autocomplete
things.
2022-01-21 18:58:28 +03:30
Ali Mohammad Pur
2e333b3571 Shell: Make SimpleVariable::hit_test_position not hit irrelevant offsets
Without this, any offset would be accepted as being part of the
SimpleVariable.
Fixes #11976 (by making it no longer crash).
2022-01-21 18:58:28 +03:30
Ali Mohammad Pur
5c0c126122 Shell: Add a "noop" builtin aliased to ":"
POSIX comes up with such silly names sometimes...
This builtin does nothing. at all.
2022-01-09 12:25:36 +01:00
Ali Mohammad Pur
6a245de911 Shell: Refresh PATH cache after 'unset PATH'
Note that `execvp` has a default value for PATH (both on Serenity and on
Linux) and so this does not 'fix' #11608.
2022-01-09 12:25:36 +01:00
Ali Mohammad Pur
310a18da1e Shell: Don't reset 'last_return_code' before running commands
Some variables depend on its value to function correctly.
Fixes the following issue:
    $ false; echo $?
    1
    $ false
    $ echo $?
    128
2022-01-09 12:25:36 +01:00
Ali Mohammad Pur
ea66750640 Shell: Make interrupts kill the whole chain and not just the current job
This makes interrupting `sleep 10; echo hi` not print `hi` anymore,
which is the expected behaviour anyway.
Also fixes the problem with fast-running loops "eating" interrupts and
not quitting.
2022-01-09 11:16:17 +03:30
Lucas CHOLLET
ed0f4bdfaf Shell: Port to LibMain 2022-01-09 03:22:10 +03:30
Andrew Kaster
170a7e263c Userland: Fail Core::find_executable_in_path on empty inputs
Before this patch, `which ""` or `type ""` would say that the empty
string is `/usr/local/bin/`.

Convert callers to consistently call is_empty() on the returned string
while we're at it, to support eventually removing the is_null() String
state in the future.
2022-01-04 07:38:42 +00:00
Ali Mohammad Pur
783e27f8f9 Shell: Make redirection errors raise ShellErrors
Naturally, this means that a command with a failing redirection will
not start, and so will terminate the pipeline (if any).
This also applies to the `exit` run when the shell is closed, fixing a
fun bug there as well (thanks to Discord user Salanty for pointing that
out) where closing the terminal (i.e. I/O error on the tty) with a
failing `exit` command would make the shell retry executing `exit` every
time, leading to an eventual stack overflow.
2021-12-31 02:19:45 +03:30
Daniel Bertalan
6b39c6b1bf Shell: Avoid many single byte write() syscalls when printing the prompt
Whenever the prompt is printed, we write a line's worth of space
characters to the terminal to ensure that the prompt ends up on a new
line even if there is dangling output on the current line.

We write these to the stderr, which is unbuffered, so each putc() call
would come with the overhead of a system call. Let's use a buffer
+ fwrite() instead, since heap allocation is much faster.
2021-12-30 14:26:29 +01:00
Ali Mohammad Pur
9bf81463f5 Shell: Don't skip over the first brace expansion entry if it's empty
Previously we were simply ignoring the empty entry in '{,x}', making it
resolve to a list with a single element '(x)', this commit makes that
work as expected and resolve to '("" x)'.
2021-12-16 03:26:59 +03:30
Ali Mohammad Pur
7ac8bd44f8 Shell: Set subshell flag after checking for its value in parent shell
This also reverts commit 07cc7eed29, as
that attempted to fix the issue this caused (and succeeded...but it
broke something else on linux).
2021-12-16 03:26:59 +03:30
Ali Mohammad Pur
6bf50bc40b Shell: Make the Join operation respect nodes that have a next chain
This would show up when resolving aliases, when an alias contains a
sequence.
Fixes #11219.
2021-12-13 16:26:10 +03:30
Michel Hermier
18f053ac31 Shell: Remove sigpipe.sh.out artefact after failure
Helps to avoid to erroneously add the file to git.
2021-12-13 16:20:29 +03:30
Daniel Bertalan
4a81b33c07 Everywhere: Fix -Winconsistent-missing-override warnings from Clang
This option is already enabled when building Lagom, so let's enable it
for the main build too. We will no longer be surprised by Lagom Clang
CI builds failing while everything compiles locally.

Furthermore, the stronger `-Wsuggest-override` warning is enabled in
this commit, which enforces the use of the `override` keyword in all
classes, not just those which already have some methods marked as
`override`. This works with both GCC and Clang.
2021-12-11 13:14:15 -08:00
Sam Atkins
b138070da9 Shell: Cast unused smart-pointer return values to void 2021-12-05 15:31:03 +01:00
Andreas Kling
216e21a1fa AK: Convert AK::Format formatting helpers to returning ErrorOr<void>
This isn't a complete conversion to ErrorOr<void>, but a good chunk.
The end goal here is to propagate buffer allocation failures to the
caller, and allow the use of TRY() with formatting functions.
2021-11-17 00:21:13 +01:00
Andreas Kling
8b1108e485 Everywhere: Pass AK::StringView by value 2021-11-11 01:27:46 +01:00
Andreas Kling
5f7d008791 AK+Everywhere: Stop including Vector.h from StringView.h
Preparation for using Error.h from Vector.h. This required moving some
things out of line.
2021-11-10 21:58:58 +01:00
Andreas Kling
d1477bcb8e Shell: Replace Result<T, E> use with ErrorOr<T> 2021-11-08 00:35:27 +01:00
Musab Kılıç
3b8853c3cd Shell: Add min and max iteration times to time -n in builtin_time 2021-11-06 22:09:25 -07:00
Ben Wiederhake
b8f11b1bae Everywhere: Remove unused ArgsParser header
Found while trying to enumerate all programs that use ArgsParser.
2021-11-01 21:12:58 +01:00
Ali Mohammad Pur
d020d46846 Shell: Unwind execution after runtime errors
This commit makes the Shell check for errors after a node is run(), and
prevents further execution by unwinding until the error is cleared.
Fixes #10649.
2021-10-31 12:02:20 +01:00
Ben Wiederhake
48e4fb239a Shell: Prevent exponential explosion around '$(('
When parse_expression looks at '$((', there are two ways it can end up
in parse_expression again, three consumed characters later. All these
ways fail, so what happened was that the parser tried all possible
combinations, hence taking potentially an exponential amount of time.

1. parse_evaluate swallows the '$(', a new invocation of
   parse_expression swallows the other '(', and through
   parse_list_expression we're at another parse_expression.
2. parse_evaluate swallows the '$(', but returns a SyntaxError.
   parse_expression used to not recognize the error, and treated it as a
   regular AST node, calling into read_concat, then a new invocation of
   parse_expression swallows the other '(', and through
   parse_list_expression we're at another parse_expression.

Fixes #10561.

Found by OSS Fuzz, long-standing issue
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28113
2021-10-23 19:29:59 +01:00
Ali Mohammad Pur
045c85af4b Shell: Raise an error if an execute node ends up trying to run nothing
...while capturing its standard output.
As `$()` is an invalid construct, execute nodes are not supposed to
capture the output of no command being run; but it is possible to create
empty commands such as CastToCommand(Redirection(...)) or similar.
Make this a hard error instead of an unescapable select().
This was noticed in #10432, which should now error out like so:
```
Error: Cannot capture standard output when no command is being executed
  0| $(<$file)
~~~~~^^^^^^^^^
  1|
```
2021-10-11 10:56:01 +03:30
Nico Weber
9d06448bc7 Shell: Fix -Wunreachable-code warnings from clang 2021-10-08 23:33:46 +02:00
Ali Mohammad Pur
b946a1ce48 Shell: Make ArgsParser not exit on failure in builtin_exit()
Fixes #10128.
2021-09-20 03:31:57 +04:30
Brian Gianforcaro
951cd68979 Shell: Use default instead of an empty constructor/destructor
Default implementations allow for more optimizations.
See: https://pvs-studio.com/en/docs/warnings/v832/
2021-09-16 17:17:13 +02:00
Brian Gianforcaro
f6d179b304 Shell: Use ElapsedTimer::start_new() 2021-09-12 17:24:44 +00:00
Andreas Kling
6ad427993a Everywhere: Behaviour => Behavior 2021-09-07 13:53:14 +02:00
Ali Mohammad Pur
97e97bccab Everywhere: Make ByteBuffer::{create_*,copy}() OOM-safe 2021-09-06 01:53:26 +02:00
Daniel Bertalan
d7b6cc6421 Everywhere: Prevent risky implicit casts of (Nonnull)RefPtr
Our existing implementation did not check the element type of the other
pointer in the constructors and move assignment operators. This meant
that some operations that would require explicit casting on raw pointers
were done implicitly, such as:
- downcasting a base class to a derived class (e.g. `Kernel::Inode` =>
  `Kernel::ProcFSDirectoryInode` in Kernel/ProcFS.cpp),
- casting to an unrelated type (e.g. `Promise<bool>` => `Promise<Empty>`
  in LibIMAP/Client.cpp)

This, of course, allows gross violations of the type system, and makes
the need to type-check less obvious before downcasting. Luckily, while
adding the `static_ptr_cast`s, only two truly incorrect usages were
found; in the other instances, our casts just needed to be made
explicit.
2021-09-03 23:20:23 +02:00
Andreas Kling
eaf88cc78a AK: Rename create<T> => make_ref_counted<T>
And also try_create<T> => try_make_ref_counted<T>.

A global "create" was a bit much. The new name matches make<T> better,
which we've used for making single-owner objects since forever.
2021-09-03 02:36:09 +02:00
sin-ack
8ea22121ac Userland: Migrate to argument-less deferred_invoke
Only one place used this argument and it was to hold on to a strong ref
for the object. Since we already do that now, there's no need to keep
this argument around since this can be easily captured.

This commit contains no changes.
2021-09-02 03:47:47 +04:30
Tobias Christiansen
32b4470ea3 Shell: Use new Statistics tool in 'time -n' command
The new Statistics utility is now used when calling 'time -n' to get
some more information of the timings. For now only the standard
deviation is given in addition to the average.

This commit completely undos #9645 because everything that touched moved
into AK::Statistics.
2021-08-31 16:38:22 +02:00
Andreas Kling
47420e72b8 Shell: Fix a TOCTOU in popd by simplifying it
This builtin was doing a lot of redundant work, including doing a stat()
followed by a chdir(), when just a chdir() would suffice.

SonarCloud: https://sonarcloud.io/project/issues?id=SerenityOS_serenity&issues=AXuVPAHNk92xXUF3qTNb&open=AXuVPAHNk92xXUF3qTNb
2021-08-30 18:35:36 +02:00
Ali Mohammad Pur
74c3359bed Shell: Use a relative path in builtin_cd for chdir if possible
This kinda sorta addresses the Shell side of #9655, however the fact
that `chdir` (and most other syscalls that take paths) are artifically
limited to a length of PATH_MAX remains.
2021-08-28 20:02:27 +02:00
Musab Kılıç
3edeb9b7e7 Shell: Use variable instead of iteration_times.size() in builtin_time 2021-08-27 23:16:53 +02:00
Musab Kılıç
29a9be6503 Shell: Add iteration_times.ensure_capacity() in builtin_time 2021-08-27 23:16:53 +02:00
Ralf Donau
19aeb71d15 Shell: Use String::join for the command in timing report 2021-08-23 22:46:41 +02:00
Valtteri Koskivuori
b28b4c643e Shell: Avoid a needless loop in builtin_time()
Not performance sensitive, but perhaps a bit neater? :^)
2021-08-23 22:44:32 +02:00
Andreas Kling
b9ab7a5095 Shell: Support time -n <iterations>
You can now specify a number of iterations when timing a command.
The default value is 1 and behaves exactly as before.

If the iteration count is greater than 1, the command will be executed
that many times, and then you get a little timing report afterwards with
the average runtime per iteration, and also the average runtime
excluding the very first iteration. (Excluding the first iteration is
useful when it's slowed down by cold caches, etc.)

This is something I've been doing manually forever (running `time foo`
and then eyeballing the results to headmath an average) and this makes
that whole process so much nicer. :^)
2021-08-23 20:15:14 +02:00
Timothy Flynn
02e3633b7f AK: Move FormatParser definition from header to implementation file
This is primarily to be able to remove the GenericLexer include out of
Format.h as well. A subsequent commit will add AK::Result to
GenericLexer, which will cause naming conflicts with other structures
named Result. This can be avoided (for now) by preventing nearly every
file in the system from implicitly including GenericLexer.

Other changes in this commit are to add the GenericLexer include to
files where it is missing.
2021-08-19 23:49:25 +02:00
sin-ack
4c6a97e757 Shell: Make caller specify the string parsing end condition
Heredocs have a different parse end condition than double-quoted
strings. parse_doublequoted_string_inner would assume that a string
would always end in a double quote, so let's generalize it to
parse_string_inner and have it take a StringEndCondition enum which
specifies how the string terminates.
2021-08-13 01:20:35 +04:30
sin-ack
c419b1ade6 Shell: Remove dbgln related to process group IDs
This is insignificant debugging information and will print out during
runs with Lagom.
2021-08-12 22:42:50 +02:00
Jean-Baptiste Boric
2084289162 Userland: Fix PATH environment variable ordering 2021-08-12 18:56:30 +02:00
Gunnar Beutner
07cc7eed29 Shell: Make sure TTY echo is enabled when running external commands
When running external commands via "Shell -c" LibLine turns of TTY echo
before running the command. This ensures that it is turned on.
2021-08-04 03:14:59 +04:30
TheFightingCatfish
f67c2c97b1 Shell: Improve the parsing of history event designators 2021-08-02 02:58:55 +04:30
Ali Mohammad Pur
124ca30d49 Shell: Don't assume that only the current shell may continue children
That can happen because of anyone sending the process a SIGCONT.
Fixes an issue where continuing a process launched by the shell from
the System Monitor would cause the shell to spin on waitpid().
2021-07-17 02:00:24 +04:30
Gunnar Beutner
c7265ee6bd Assistant: Keep the Terminal window open after the command has run 2021-07-16 13:05:55 +02:00
TheFightingCatfish
72e661b542 Shell: Add unalias builtin
Add shell unalias builtin to remove aliases
2021-07-13 11:57:11 +04:30
Daniel Bertalan
e32692ea68 Shell: Use correct printf format string for size_t 2021-07-08 10:11:00 +02:00
Gunnar Beutner
3bbe86d8ea Everywhere: Prefer using "..."sv over StringView { "..." } 2021-07-04 14:24:03 +02:00
Max Wipfli
9b8f35259c AK: Remove the LexicalPath::is_valid() API
Since this is always set to true on the non-default constructor and
subsequently never modified, it is somewhat pointless. Furthermore,
there are arguably no invalid relative paths.
2021-06-30 11:13:54 +02:00
Daniel Bertalan
65b2d3add3 Shell: Don't do null check on NonnullRefPtr<T>
This will cause a problem when `NonnullRefPtr<T>::operator T*` will be
declared as RETURNS_NONNULL. Clang emits a warning for this pointless
null check, which breaks CI.
2021-06-29 22:57:52 +04:30
Daniel Bertalan
f820917a76 Everywhere: Use nothrow new with adopt_{ref,own}_if_nonnull
This commit converts naked `new`s to `AK::try_make` and `AK::try_create`
wherever possible. If the called constructor is private, this can not be
done, so we instead now use the standard-defined and compiler-agnostic
`new (nothrow)`.
2021-06-24 17:35:49 +04:30
coderdreams
6bc7f2204e Tests: Run each test in their respective directories
This is so they can find their associated resources and it's
the same behavior as in Lagom.

This also required changing some tests so that they could
write their resources in a writable location.
2021-06-22 18:54:40 +04:30
Gunnar Beutner
631d36fd98 Everywhere: Add component declarations
This adds component declarations so that users can select to not build
certain parts of the OS.
2021-06-17 11:03:51 +02:00
Brian Gianforcaro
8063ca881d Shell: Remove unused InlineLinkedList header include 2021-06-16 10:40:01 +02:00
Gunnar Beutner
d476144565 Userland: Allow building SerenityOS with -funsigned-char
Some of the code assumed that chars were always signed while that is
not the case on ARM hosts.

Also, some of the code tried to use EOF (-1) in a way similar to what
fgetc() does, however instead of storing the characters in an int
variable a char was used.

While this seemed to work it also meant that character 0xFF would be
incorrectly seen as an end-of-file.

Careful reading of fgetc() reveals that fgetc() stores character
data in an int where valid characters are in the range of 0-255 and
the EOF value is explicitly outside of that range (usually -1).
2021-06-13 18:52:58 +02:00
Andreas Kling
dc65f54c06 AK: Rename Vector::append(Vector) => Vector::extend(Vector)
Let's make it a bit more clear when we're appending the elements from
one vector to the end of another vector.
2021-06-12 13:24:45 +02:00
Jelle Raaijmakers
00fc0a6cf0 Shell: Make time stop parsing options on first non-option 2021-06-08 11:30:58 +02:00
Jelle Raaijmakers
250f8eccf3 LibCore: Support fine-grained failure behavior for ArgsParser 2021-06-08 11:30:58 +02:00