Commit Graph

842 Commits

Author SHA1 Message Date
Jilles Tjoelker
61fb716ac9 sh: Inline waitproc() into its only caller. 2012-07-28 14:56:50 +00:00
Jilles Tjoelker
faa787d323 sh: Track continued jobs (even if not continued by bg or fg).
This uses wait3's WCONTINUED flag.

There is no message for this. The change is visible in "jobs" or if the job
stops again.
2012-07-28 14:32:55 +00:00
Jilles Tjoelker
fa7ccda2c4 sh: Reset pendingsigs before checking pending traps, not after.
Otherwise, a signal arriving at exactly the right moment might not be
processed until another signal arrived.
2012-07-15 11:18:52 +00:00
Jilles Tjoelker
184dcee217 sh: Remove unused variable in_dowait. 2012-07-15 10:49:16 +00:00
Jilles Tjoelker
84fbdd8ca0 sh: Expand assignment-like words specially for export/readonly/local.
Examples:
  export x=~
now expands the tilde
  local y=$1
is now safe, even if $1 contains IFS characters or metacharacters.

For a word to "look like an assignment", it must start with a name followed
by an equals sign, none of which may be quoted.

The special treatment applies when the first word (potentially after
"command") is "export", "readonly" or "local". There may be quoting
characters but no expansions. If "local" is overridden with a function there
is no special treatment ("export" and "readonly" cannot be overridden with a
function).

If things like
  local arr=(1 2 3)
are ever allowed in the future, they cannot call a "local" function. This
would either be a run-time error or it would call the builtin.

This matches Austin Group bug #351, planned for the next issue of POSIX.1.

PR:		bin/166771
2012-07-15 10:19:43 +00:00
Pedro F. Giffuni
00c43e0ca4 Merge libedit adjustment from NetBSD.
On recent versions of NetBSD's libedit, el_gets
now sets el_len to -1 on error so we can
distinguish between a NULL string and an error.

This fixes sh from exiting with newer versions
of libedit now allowing EINTR to return.

Obtained from:	NetBSD
Reviewed by:	jilles
MFC after:	3 weeks
2012-07-11 22:17:58 +00:00
Marcel Moolenaar
937b0a997b Work better with how make/bmake works:
1.  Avoid a cd back into ${.CURDIR} to run mkbuiltins when we know make
    will first cd into ${.OBJDIR}. Keep the cwd to what make sets it to.
2.  Don't tell mkbuiltins where to write to (= ${.OBJDIR}), but where to
    get sources from (= ${.CURDIR}). This to compensate for point 1.

This fixes a problem with bmake's mk files that optimize ${.OBJDIR} to
expand to "." after changing cwd, not taking into account that the
target is pretty much undoing that and not getting the full path to the
object tree anymore.
2012-05-24 19:48:15 +00:00
Jilles Tjoelker
ad859ed8cf sh: Remove an unused header.
The read builtin no longer does things with termios.
2012-05-15 22:50:47 +00:00
Joel Dahl
35471bf8ef Minor mdoc nits. 2012-05-13 14:16:04 +00:00
Joel Dahl
748611c9c0 mdoc: fix column names, indentation, column separation within each row, and
quotation. Also make sure we have the same amount of columns in each row as
the number of columns we specify in the head arguments.

Reviewed by:	brueffer
2012-04-07 09:05:30 +00:00
Jilles Tjoelker
b95fca474d sh: Fix build with -DDEBUG=2.
Reported by:	Kristof Provost
MFC after:	1 week
2012-04-02 17:16:24 +00:00
Eitan Adler
50d675f7a9 Remove trailing whitespace per mdoc lint warning
Disussed with:	gavin
No objection from:	doc
Approved by:	joel
MFC after:	3 days
2012-03-29 05:02:12 +00:00
Joel Dahl
904d0726c8 Remove superfluous paragraph macro. 2012-03-25 09:20:14 +00:00
Jilles Tjoelker
c0b3cf0676 sh: Make 'hash' return 1 if at least one utility is not found.
Reported by:	lme
2012-02-11 21:06:45 +00:00
Jilles Tjoelker
33233ec76e sh: Fix swapped INTON/INTOFF.
A possible consequence of this bug was a memory leak if SIGINT arrived
during a 'set' command (listing variables).

MFC after:	1 week
2012-02-04 23:29:07 +00:00
Jilles Tjoelker
caf29fab8c sh: Use vfork in a few common cases.
This uses vfork() for simple commands and command substitutions containing a
single simple command, invoking an external program under certain conditions
(no redirections or variable assignments, non-interactive shell, no job
control). These restrictions limit the amount of code executed in a vforked
child.

There is a large speedup (for example 35%) in microbenchmarks. The
difference in buildkernel is smaller (for example 0.5%) but still
statistically significant. See
http://lists.freebsd.org/pipermail/freebsd-hackers/2012-January/037581.html
for some numbers.

The use of vfork() can be disabled by setting a variable named
SH_DISABLE_VFORK.
2012-02-04 23:12:14 +00:00
Philippe Charnier
2fae4c3d95 Add prototypes, ANSIfy functions definitions to reduce WARNS=6 output. 2012-01-25 08:42:19 +00:00
Jilles Tjoelker
6eff4a75d5 sh: Fix $? in the first command of a 'for'.
In the first command of a 'for', $? should be the exit status of the last
pipeline (command substitution in the word list or command before 'for'),
not always 0.
2012-01-22 14:00:33 +00:00
Jilles Tjoelker
0105d7224d sh: Remove "kill" example function, which is superseded by the kill builtin
MFC after:	1 week
2012-01-21 20:39:17 +00:00
Jean-Sébastien Pédron
01a43bcf7b sh: Fix execution of multiple statements in a trap when evalskip is set
Before this fix, only the first statement of the trap was executed if
evalskip was set. This is for example the case when:
    o  "-e" is set for this shell
    o  a trap is set on EXIT
    o  a function returns 1 and causes the script to abort

Reviewed by:	jilles
MFC after:	2 weeks
2012-01-16 11:07:46 +00:00
Jilles Tjoelker
93fcb2511b sh: Fix some bugs with exit status from case containing ;&.
Also, rework evalcase() to not evaluate any tree. Instead, return the
NCLISTFALLTHRU node and handle it in evaltree().

Fixed bugs:

* If a ;& list with non-zero exit status is followed by an empty ;; or final
  list, the exit status of the case command should be equal to the exit
  status of the ;& list, not 0.

* An empty ;& case should not reset $?.
2012-01-15 21:39:38 +00:00
Jilles Tjoelker
92371efca2 sh: Fix two bugs with case and exit status:
* If no pattern is matched, POSIX says the exit status shall be 0 (even if
  there are command substitutions).
* If a pattern is matched and there are no command substitutions, the first
  command should see the $? from before the case command, not always 0.
2012-01-15 20:04:05 +00:00
Jilles Tjoelker
7f40c1f876 sh: Change input buffer size from 1023 to 1024.
PR:		bin/161756
2012-01-14 22:46:18 +00:00
Jilles Tjoelker
52c450395a sh: Fix out of bounds array access when trap is used with an invalid signal.
MFC after:	1 week
2012-01-14 21:54:12 +00:00
Jilles Tjoelker
e94e3511bd sh: Properly show "Not a directory" error in cd builtin.
The errno message display added in r222292 did not take attempting to
cd to a non-directory or something that cannot be stat()ed into account.

PR:		bin/164070
MFC after:	10 days
2012-01-13 23:32:27 +00:00
Jilles Tjoelker
260fc3f4d2 sh: Make various functions static. 2012-01-01 22:17:12 +00:00
Jilles Tjoelker
f6d3a9b03f sh: Remove unused function scopyn(). 2012-01-01 22:15:38 +00:00
Jilles Tjoelker
820491f824 sh: Make patmatch() non-recursive. 2012-01-01 20:50:19 +00:00
Jilles Tjoelker
3a1b9c9e82 sh: Allow quoting ^ and ] in bracket expressions. 2011-12-28 23:51:17 +00:00
Jilles Tjoelker
6e8db49a44 sh: Use dirent.d_type in pathname generation.
This improves performance for globs where a slash or another component
follows a component with metacharacters by eliminating unnecessary attempts
to open directories that are not.
2011-12-28 23:40:46 +00:00
Jilles Tjoelker
7a2b9d4b38 sh: Cache de->d_namlen in a local variable. 2011-12-28 23:30:17 +00:00
Jilles Tjoelker
a82f5687bf sh: Do not force special builtins non-special in optimized command subst.
This is not necessary: errors are already caught in evalbackcmd() and
forcelocal handles changes to variables.

Note that this depends on r223024.

MFC after:	4 weeks
2011-12-28 22:10:12 +00:00
Jilles Tjoelker
03f33e912d sh: Remove impossible evalskip check in 'for'. 2011-11-27 00:09:59 +00:00
Jilles Tjoelker
a157dc4d90 sh: Reduce one level of evaltree() recursion when executing 'case'.
Free expanded case text before executing commands.
Remove impossible evalskip checks (expanding an argument cannot set
evalskip anymore since $(break) and the like are properly executed in a
subshell environment).
2011-11-26 23:28:31 +00:00
Jilles Tjoelker
bf3db314f7 sh: Allow unsetting OPTIND.
Note that only assigning the decimal value 1 resets getopts, as before.
2011-11-20 21:48:50 +00:00
Jilles Tjoelker
876f9b7800 sh: Remove undefined behaviour due to overflow in +/-/* in arithmetic.
With i386 base gcc and i386 base clang, arith_yacc.o remains unchanged.
2011-11-08 23:54:39 +00:00
Jilles Tjoelker
ad56ebdc15 sh(1): Improve documentation of field splitting. 2011-11-05 21:56:45 +00:00
Jilles Tjoelker
51a514adf2 sh(1): Extend documentation about subshells.
Because sh executes commands in subshell environments without forking in
more and more cases (particularly from 8.0 on), it makes sense to describe
subshell environments more precisely using ideas from POSIX, together with
some FreeBSD-specific items.

In particular, the hash and times builtins may not behave as if their state
is copied for a subshell environment while leaving the parent shell
environment unchanged.
2011-07-10 15:02:25 +00:00
Jilles Tjoelker
4004e05e8a sh: Include <limits.h> instead of non-standard <sys/limits.h>. 2011-06-26 20:12:05 +00:00
Jilles Tjoelker
519c4ef391 sh(1): Improve documentation of shell patterns:
* Shell patterns are also for ${var#pat} and the like.
* An '!' by itself will not trigger pathname generation so do not call it a
  meta-character, even though it has a special meaning directly after an
  '['.
* Character ranges are locale-dependent.
* A '^' will complement a character class like '!' but is non-standard.

MFC after:	1 week
2011-06-24 22:08:26 +00:00
Jilles Tjoelker
b97989d659 sh(1): Document the case command better.
Suggested by:	netchild
Reviewed by:	gjb
2011-06-24 20:23:50 +00:00
Kevin Lo
ecd9e552d0 Remove duplicated header files 2011-06-24 07:29:04 +00:00
Jilles Tjoelker
47e5204ee3 sh: Remove special support for background simple commands.
It expands the arguments in the parent shell process, which is incorrect.
2011-06-18 23:58:59 +00:00
Jilles Tjoelker
54b16435b7 sh: Add do-nothing -h option.
POSIX requires a -h option to sh and set, to locate and remember utilities
invoked by functions as they are defined. Given that this
locate-and-remember process is optional elsewhere, it seems safe enough to
make this option do nothing.

POSIX does not specify a long name for this option. Follow ksh in calling it
"trackall".
2011-06-18 23:43:28 +00:00
Jilles Tjoelker
c9afaa6389 sh: Add case statement fallthrough (with ';&' instead of ';;').
Replacing ;; with the new control operator ;& will cause the next list to be
executed as well without checking its pattern, continuing until a list ends
with ;; or until the end of the case statement. This is like omitting
"break" in a C "switch" statement.

The sequence ;& was formerly invalid.

This feature is proposed for the next POSIX issue in Austin Group issue
#449.
2011-06-17 13:03:49 +00:00
Jilles Tjoelker
f5f215e251 sh: Skip variables with invalid names in "set", "export -p", "readonly -p".
This ensures the output of these commands is valid shell input.
2011-06-17 10:21:24 +00:00
Jilles Tjoelker
c5aef5377c sh: Reduce unnecessary forks with eval.
The eval special builtin now runs the code with EV_EXIT if it was run
with EV_EXIT itself.

In particular, this eliminates one fork when a command substitution contains
an eval command that ends with an external program or a subshell.

This is similar to what r220978 did for functions.
2011-06-16 21:50:28 +00:00
Jilles Tjoelker
ff4dc67299 sh: Add support for named character classes in bracket expressions.
Example:
  case x in [[:alpha:]]) echo yes ;; esac
2011-06-15 21:48:10 +00:00
Jilles Tjoelker
454a02b372 sh: Fix duplicate prototypes for builtins.
Have mkbuiltins write the prototypes for the *cmd functions to builtins.h
instead of builtins.c and include builtins.h in more .c files instead of
duplicating prototypes for *cmd functions in other headers.
2011-06-13 21:03:27 +00:00
Jilles Tjoelker
c543e1ae9e sh: Save/restore changed variables in optimized command substitution.
In optimized command substitution, save and restore any variables changed by
expansions (${var=value} and $((var=assigned))), instead of trying to
determine if an expansion may cause such changes.

If $! is referenced in optimized command substitution, do not cause jobs to
be remembered longer.

This fixes $(jobs $!) again, simplifies the man page and shortens the code.
2011-06-12 23:06:04 +00:00
Jilles Tjoelker
f5ac5937d3 sh: Fix locale-dependent ranges in bracket expressions.
When I added UTF-8 support in r221646, the LC_COLLATE-based ordering broke
because of sign extension of char.

Because of libc restrictions, this does not work for UTF-8. For UTF-8
locales, ranges always use character code order.
2011-06-12 12:54:52 +00:00
Jilles Tjoelker
c5f4fe06fe sh: Read .profile from the home directory (or / if HOME is not set).
In most cases, login shells are started from the home directory, but not in
all, such as xterm -ls.

This commit depends on r222957 for read_profile() performing parameter
expansion.

PR:		bin/50569
2011-06-12 10:13:48 +00:00
Jilles Tjoelker
1a62d8843d sh: Do parameter expansion on ENV before using it.
This is required by POSIX, and allows things like ENV=\$HOME/.shrc.

Note that tilde expansion is explicitly not performed.
2011-06-10 22:42:00 +00:00
Jilles Tjoelker
292e667663 sh: Do parameter expansion before printing PS4 (set -x).
The function name expandstr() and the general idea of doing this kind of
expansion by treating the text as a here document without end marker is from
dash.

All variants of parameter expansion and arithmetic expansion also work (the
latter is not required by POSIX but it does not take extra code and many
other shells also allow it).

Command substitution is prevented because I think it causes too much code to
be re-entered (for example creating an unbounded recursion of trace lines).

Unfortunately, our LINENO is somewhat crude, otherwise PS4='$LINENO+ ' would
be quite useful.
2011-06-09 23:12:23 +00:00
Jilles Tjoelker
b3f892d9e0 sh: Fix $? in heredocs on simple commands.
PR:		bin/41410
2011-06-05 14:13:15 +00:00
Jilles Tjoelker
af449f7fef sh: Improve error message if the script cannot be opened.
Avoid "<nosuchfile>: cannot open <nosuchfile>: ...".
2011-06-04 22:19:00 +00:00
Jilles Tjoelker
47a5ab295a sh: Reduce more needless differences between error messages. 2011-06-04 15:05:52 +00:00
Jilles Tjoelker
9338c85c31 sh: Honour -n while processing -c string. 2011-06-04 11:28:42 +00:00
Jilles Tjoelker
8d5a14301f sh: Remove the "exp" builtin.
The "exp" builtin is undocumented, non-standard and not very useful.

If exp's return value is not used, something like
VAR=$(exp EXPRESSION)
is equivalent to
VAR=$((EXPRESSION))
except that errors in the expression are fatal and quoting special
characters is not needed in the latter case.

If exp's return value is used, something like
if exp EXPRESSION >/dev/null
can be replaced by
if [ $((EXPRESSION)) -ne 0 ]
with similar differences.

The exp-run showed that "let" is close enough to bash's and ksh's builtin
that removing it would break a few ports. Therefore, "let" remains in 9.x.

PR:		bin/104432
Exp-run done by: pav (with some other sh(1) changes)
2011-05-27 20:53:07 +00:00
Jilles Tjoelker
64fa41f3e1 sh: Correct criterion for using CDPATH in cd.
CDPATH should be ignored not only for pathnames starting with '/' but also
for pathnames whose first component is '.' or '..'.

The man page already describes this behaviour.
2011-05-27 20:01:46 +00:00
Jilles Tjoelker
241f15dfaf sh: Various updates to the TOUR document. 2011-05-27 16:00:37 +00:00
Jilles Tjoelker
715a0dd556 sh: Fix unquoted $@/$* if IFS=''.
If IFS is null, unquoted $@/$* should still expand to separate words.
This differs from quoted $@ (which does not depend on IFS) in that pathname
generation is performed and empty words are removed.
2011-05-27 15:56:13 +00:00
Jilles Tjoelker
168b9dd182 sh: Show errno messages in cd. 2011-05-25 21:38:16 +00:00
Jilles Tjoelker
f3ac36e151 sh: Remove obsolete token type TENDBQUOTE.
This token type was related to Almquist's original version of backquotes
that could not nest and fell into disuse fairly soon.
2011-05-22 15:24:56 +00:00
Ulrich Spörlein
bf2fe08eea Fix some typos under bin/
Found by:	codespell
2011-05-22 14:03:46 +00:00
Jilles Tjoelker
c9e93e6739 sh: Fix bss-based buffer overflow in . builtin.
If the length of a directory in PATH together with the given filename
exceeded FILENAME_MAX (which may happen even for pathnames that work), a
static buffer was overflown.

The static buffer is unnecessary, we can use the stalloc() stack.

Obtained from:	NetBSD
MFC after:	1 week
2011-05-22 12:12:28 +00:00
Jilles Tjoelker
05a447d0b9 sh: Expand aliases after assignments and redirections. 2011-05-21 22:03:06 +00:00
Jilles Tjoelker
d6ee26ad02 sh: Implement the cd -e flag proposed for the next POSIX issue.
This reflects failure to determine the pathname of the new directory in the
exit status (1). Normally, cd returns successfully if it did chdir() and the
call was successful.

In POSIX, -e only has meaning with -P; because our -L is not entirely
compliant and may fall back to -P mode, -e has some effect with -L as well.
2011-05-20 22:55:18 +00:00
Jilles Tjoelker
85307c9ed9 sh: Allow terminating a heredoc with a terminator at EOF without a newline.
This is sometimes used with eval or old-style command substitution, and most
shells other than ash derivatives allow it.

It can also be used with scripts that violate POSIX's requirement on the
application that they end in a newline (scripts must be text files except
that line length is unlimited).

Example:
v=`cat <<EOF
foo
EOF`
echo $v

This commit does not add support for the similar construct with new-style
command substitution, like
v=$(cat <<EOF
foo
EOF)
This continues to require a newline after the terminator.
2011-05-20 16:03:36 +00:00
Jilles Tjoelker
258ef734e7 sh: Minor optimization to output from ulimit/export/readonly.
No functional change is intended.
2011-05-15 22:09:27 +00:00
Jilles Tjoelker
e64a11e9eb sh: Avoid close(-1) when evaluating a multi-command pipeline.
Valgrind complains about this.
2011-05-15 17:00:43 +00:00
Jilles Tjoelker
07eb7033a6 sh: Add \u/\U support (in $'...') for UTF-8.
Because we have no iconv in base, support for other charsets is not
possible.

Note that \u/\U are processed using the locale that was active when the
shell started. This is necessary to avoid behaviour that depends on the
parse/execute split (for example when placing braces around an entire
script). Therefore, UTF-8 encoding is implemented manually.
2011-05-08 17:40:10 +00:00
Jilles Tjoelker
3a99ed469a sh: Optimize variable code by storing the length of the name.
Obtained from:	NetBSD
2011-05-08 16:15:50 +00:00
Jilles Tjoelker
50df342447 sh(1): Update BUGS section for UTF-8 support. 2011-05-08 14:03:44 +00:00
Jilles Tjoelker
7cc6b3df80 sh: Add UTF-8 support to pattern matching.
?, [...] patterns match codepoints instead of bytes. They do not match
invalid sequences. [...] patterns must not contain invalid sequences
otherwise they will not match anything. This is so that ${var#?} removes the
first codepoint, not the first byte, without putting UTF-8 knowledge into
the ${var#pattern} code. However, * continues to match any string and an
invalid sequence matches an identical invalid sequence. (This differs from
fnmatch(3).)
2011-05-08 11:32:20 +00:00
Jilles Tjoelker
4c244ed255 sh: Add UTF-8 support to ${#var}.
If the current locale uses UTF-8, ${#var} counts codepoints (more precisely,
bytes b with (b & 0xc0) != 0x80).
2011-05-07 14:32:16 +00:00
Jilles Tjoelker
6ed74a0a1c sh: Track if the current locale's charset is UTF-8 or not. 2011-05-06 22:31:27 +00:00
Jilles Tjoelker
c76aed958b sh: Change the CTL* bytes to ones invalid in UTF-8.
This ensures that mbrtowc(3) can be used directly once it has been verified
that there is no CTL* byte. Dealing with a CTLESC byte within a multibyte
character would be complicated.

The new values do occur in iso-8859-* encodings. This decreases efficiency
slightly but should not affect correctness.

Caveat: Updating across this change and rebuilding without cleaning may
yield a subtly broken sh binary. By default, make buildworld will clean and
avoid problems.
2011-05-06 20:45:50 +00:00
Jilles Tjoelker
a62ab0274a sh: Add $'quoting' (C-style escape sequences).
A string between $' and ' may contain backslash escape sequences similar to
the ones in a C string constant (except that a single-quote must be escaped
and a double-quote need not be). Details are in the sh(1) man page.

This construct is useful to include unprintable characters, tabs and
newlines in strings; while this can be done with a command substitution
containing a printf command, that needs ugly workarounds if the result is to
end with a newline as command substitution removes all trailing newlines.

The construct may also be useful in future to describe unprintable
characters without needing to write those characters themselves in 'set -x',
'export -p' and the like.

The implementation attempts to comply to the proposal for the next issue of
the POSIX specification. Because this construct is not in POSIX.1-2008,
using it in scripts intended to be portable is unwise.

Matching the minimal locale support in the rest of sh, the \u and \U
sequences are currently not useful.

Exp-run done by: pav (with some other sh(1) changes)
2011-05-05 20:55:55 +00:00
Jilles Tjoelker
3937fc9c26 sh: Apply set -u to variables in arithmetic.
Note that this only applies to variables that are actually used.
Things like (0 && unsetvar) do not cause an error.

Exp-run done by: pav (with some other sh(1) changes)
2011-05-04 22:12:22 +00:00
Jilles Tjoelker
fc0818fef3 sh: Detect an error for ${#var<GARBAGE>}.
In particular, this makes things like ${#foo[0]} and ${#foo[@]} errors
rather than silent equivalents of ${#foo}.

PR:		bin/151720
Submitted by:	Mark Johnston
Exp-run done by: pav (with some other sh(1) changes)
2011-05-04 21:49:34 +00:00
Jilles Tjoelker
03b3a844d0 sh: Set $? to 0 for background commands.
For backgrounded pipelines and subshells, the previous value of $? was being
preserved, which is incorrect.

For backgrounded simple commands containing a command substitution, the
status of the last command substitution was returned instead of 0.

If fork() fails, this is an error.
2011-04-25 20:54:12 +00:00
Jilles Tjoelker
92a1de471c sh: Check setuid()/setgid() return values.
If the -p option is turned off, privileges from a setuid or setgid binary
are dropped. Make sure to check if this succeeds. If it fails, this is an
error which will cause the shell to abort except in interactive mode or if
'command' was used to make 'set' or an outer 'eval' or '.' non-special.

Note that taking advantage of this feature and writing setuid shell scripts
seems unwise.

MFC after:	1 week
2011-04-25 10:14:29 +00:00
Jilles Tjoelker
b7b23db5e2 sh: Remove duplicate code resetting uid/gid for set +p/+o privileged.
MFC after:	1 week
2011-04-25 10:08:34 +00:00
Jilles Tjoelker
45496405c6 sh: Allow EV_EXIT through function calls, make {...} <redir more consistent.
If EV_EXIT causes an exit, use the exception mechanism to unwind
redirections and local variables. This way, if the final command is a
redirected command, an EXIT trap now executes without the redirections.

Because of these changes, EV_EXIT can now be inherited by the body of a
function, so do so. This means that a function no longer prevents a fork
before an exec being skipped, such as in
  f() { head -1 /etc/passwd; }; echo $(f)

Wrapping a single builtin in a function may still cause an otherwise
unnecessary fork with command substitution, however.

An exit command or -e failure still invokes the EXIT trap with the
original redirections and local variables in place.

Note: this depends on SHELLPROC being gone. A SHELLPROC depended on
keeping the redirections and local variables and only cleaning up the
state to restore them.
2011-04-23 22:28:56 +00:00
Jilles Tjoelker
caa7ccdc54 sh: Do not word split "${#parameter}".
This is only a problem if IFS contains digits, which is unusual but valid.

Because of an incorrect fix for PR bin/12137, "${#parameter}" was treated
as ${#parameter}. The underlying problem was that "${#parameter}"
erroneously added CTLESC bytes before determining the length. This
was properly fixed for PR bin/56147 but the incorrect fix was not backed
out.

Reported by:	Seeker on forums.freebsd.org
MFC after:	2 weeks
2011-04-20 22:24:54 +00:00
Jilles Tjoelker
ef89d04f13 sh(1): Describe subshell environment, command substitution more correctly.
POSIX does not require the shell to fork for a subshell environment, and we
use that possibility in various ways (command substitutions with a single
command and most subshells that are the final command of a shell process).
Therefore do not tie subshells to forking in the man page.

Command substitutions with expansions are a bit strange, causing a fork for
$(...$(($x))...) because $x might expand to y=2; they will probably be
changed later but this is how they work now.
2011-03-20 23:52:45 +00:00
Jilles Tjoelker
35c641ed21 sh: Fix some parameter expansion variants ${#...}.
These already worked: $# ${#} ${##} ${#-} ${#?}
These now work as well: ${#+word} ${#-word} ${##word} ${#%word}

There is an ambiguity in the standard with ${#?}: it could be the length of
$? or it could be $# giving an error in the (impossible) case that it is not
set. We continue to use the former interpretation as it seems more useful.
2011-03-13 20:02:39 +00:00
Stefan Farfeleder
5db2bbd692 Remove unnecessary cast.
Reviewed by:	jilles
2011-03-07 07:31:15 +00:00
Jilles Tjoelker
ea381e691a sh(1): Reduce excessive semicolon-separated sentences.
Reported by:	Benjamin Kaduk
2011-03-06 21:20:53 +00:00
Jilles Tjoelker
976018d24f sh: Fix some warnings in code for arithmetic expressions.
Submitted by:	eadler
2011-03-05 13:27:13 +00:00
Rebecca Cran
6bccea7c2b Fix typos - remove duplicate "the".
PR:	bin/154928
Submitted by:	Eitan Adler <lists at eitanadler.com>
MFC after: 	3 days
2011-02-21 09:01:34 +00:00
Jilles Tjoelker
e9749129ad sh: Detect dividing the smallest integer by -1.
This overflows and on some architectures such as amd64 it generates SIGFPE.
Generate an error on all architectures.
2011-02-12 23:44:05 +00:00
Jilles Tjoelker
075b72ef01 sh(1): Update description of arithmetic. 2011-02-08 23:19:40 +00:00
Jilles Tjoelker
6262b84eee sh: Import arithmetic expression code from dash.
New features:
* proper lazy evaluation of || and &&
* ?: ternary operator
* executable is considerably smaller (8K on i386) because lex and yacc are
  no longer used

Differences from dash:
* arith_t instead of intmax_t
* imaxdiv() not used
* unset or null variables default to 0
* let/exp builtin (undocumented, will probably be removed later)

Obtained from:	dash
2011-02-08 23:18:06 +00:00
Jilles Tjoelker
b15e9aa322 sh: Fix two things about {(...)} <redir:
* In {(...) <redir1;} <redir2, do not drop redir1.
* Maintain the difference between (...) <redir and {(...)} <redir:
  In (...) <redir, the redirection is performed in the child, while in
  {(...)} <redir it should be performed in the parent (like {(...); :;}
  <redir)
2011-02-05 15:02:19 +00:00
Jilles Tjoelker
c059d82290 sh: Remove clearcmdentry()'s now unused argument. 2011-02-05 14:08:51 +00:00
Jilles Tjoelker
ef0cb80dd4 sh: Forget all cached command locations on any PATH change.
POSIX requires this and it is simpler than the previous code that remembered
command locations when appending directories to PATH.

In particular,
  PATH=$PATH
is no longer a no-op but discards all cached command locations.
2011-02-05 14:01:46 +00:00
Jilles Tjoelker
604e8224f8 sh: Do not try to execute binary files as scripts.
If execve() returns an [ENOEXEC] error, check if the file is binary before
trying to execute it using sh. A file is considered binary if at least one
of the first 256 bytes is '\0'.

In particular, trying to execute ELF binaries for the wrong architecture now
fails with an "Exec format error" message instead of syntax errors and
potentially strange results.
2011-02-05 12:54:59 +00:00
Jilles Tjoelker
3835f47c7e sh: Remove special code for shell scripts without magic number.
These are called "shell procedures" in the source.

If execve() failed with [ENOEXEC], the shell would reinitialize itself
and execute the program as a script. This requires a fair amount of code
which is not frequently used (most scripts have a #! magic number).
Therefore just execute a new instance of sh (_PATH_BSHELL) to run the
script.
2011-02-04 22:47:55 +00:00